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
70 extern "C" {
71 DECLSPEC_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
91 QT_BEGIN_NAMESPACE
92
93 enum {
94 // may be "overridden" by a member enum
95 FillBufferNoexcept = true
96 };
97
98 struct QRandomGenerator::SystemGenerator
99 {
100 #if QT_CONFIG(getentropy)
fillBufferQRandomGenerator::SystemGenerator101 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(reinterpret_cast<uchar *>(buffer) + read, 256);
108 Q_ASSERT(ret == 0);
109 Q_UNUSED(ret);
110 read += 256;
111 }
112
113 int ret = getentropy(reinterpret_cast<uchar *>(buffer) + read, 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.
generateQRandomGenerator::SystemGenerator190 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(reinterpret_cast<quint32 *>(begin), reinterpret_cast<quint32 *>(end));
196 } else {
197 // Slow path. Fix your C++ library.
198 std::generate(begin, end, [this]() {
199 quint32 datum;
200 generate(&datum, &datum + 1);
201 return datum;
202 });
203 }
204 }
205 };
206
207 #if defined(Q_OS_WIN)
fallback_update_seed(unsigned)208 static void fallback_update_seed(unsigned) {}
fallback_fill(quint32 * ptr,qsizetype left)209 static 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)
fallback_update_seed(unsigned)220 static void fallback_update_seed(unsigned) {}
fallback_fill(quint32 *,qsizetype)221 static 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__)
fallback_update_seed(unsigned)227 static void fallback_update_seed(unsigned) {}
fallback_fill(quint32 * ptr,qsizetype left)228 static 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
234 static QBasicAtomicInteger<unsigned> seed = Q_BASIC_ATOMIC_INITIALIZER(0U);
fallback_update_seed(unsigned value)235 static 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
243 Q_NEVER_INLINE
244 #ifdef Q_CC_GNU
245 __attribute__((cold)) // this function is pretty big, so optimize for size
246 #endif
fallback_fill(quint32 * ptr,qsizetype left)247 static 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
generate(quint32 * begin,quint32 * end)320 Q_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(buffer, count, 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 + filled, (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
350 struct 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
SystemAndGlobalGeneratorsQRandomGenerator::SystemAndGlobalGenerators370 constexpr SystemAndGlobalGenerators()
371 : globalPRNGMutex{}, system_{0}, sys{}, global_{}
372 {}
373 #endif
374
confirmLiteralQRandomGenerator::SystemAndGlobalGenerators375 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 #endif
387 }
388
selfQRandomGenerator::SystemAndGlobalGenerators389 static SystemAndGlobalGenerators *self()
390 {
391 static SystemAndGlobalGenerators g;
392 Q_STATIC_ASSERT(sizeof(g) > sizeof(QRandomGenerator64));
393 return &g;
394 }
395
systemQRandomGenerator::SystemAndGlobalGenerators396 static QRandomGenerator64 *system()
397 {
398 // Though we never call the constructor, the system QRandomGenerator is
399 // properly initialized by the zero initialization performed in self().
400 // Though QRandomGenerator is has non-vacuous initialization, we
401 // consider it initialized because of the common initial sequence.
402 return reinterpret_cast<QRandomGenerator64 *>(&self()->system_);
403 }
404
globalNoInitQRandomGenerator::SystemAndGlobalGenerators405 static QRandomGenerator64 *globalNoInit()
406 {
407 // This function returns the pointer to the global QRandomGenerator,
408 // but does not initialize it. Only call it directly if you meant to do
409 // a pointer comparison.
410 return reinterpret_cast<QRandomGenerator64 *>(&self()->global_);
411 }
412
securelySeedQRandomGenerator::SystemAndGlobalGenerators413 static void securelySeed(QRandomGenerator *rng)
414 {
415 // force reconstruction, just to be pedantic
416 new (rng) QRandomGenerator{System{}};
417
418 rng->type = MersenneTwister;
419 new (&rng->storage.engine()) RandomEngine(self()->sys);
420 }
421
422 struct PRNGLocker {
423 const bool locked;
PRNGLockerQRandomGenerator::SystemAndGlobalGenerators::PRNGLocker424 PRNGLocker(const QRandomGenerator *that)
425 : locked(that == globalNoInit())
426 {
427 if (locked)
428 self()->globalPRNGMutex.lock();
429 }
~PRNGLockerQRandomGenerator::SystemAndGlobalGenerators::PRNGLocker430 ~PRNGLocker()
431 {
432 if (locked)
433 self()->globalPRNGMutex.unlock();
434 }
435 };
436 };
437
self()438 inline QRandomGenerator::SystemGenerator &QRandomGenerator::SystemGenerator::self()
439 {
440 return SystemAndGlobalGenerators::self()->sys;
441 }
442
443 /*!
444 \class QRandomGenerator
445 \inmodule QtCore
446 \reentrant
447 \since 5.10
448
449 \brief The QRandomGenerator class allows one to obtain random values from a
450 high-quality Random Number Generator.
451
452 QRandomGenerator may be used to generate random values from a high-quality
453 random number generator. Like the C++ random engines, QRandomGenerator can
454 be seeded with user-provided values through the constructor.
455 When seeded, the sequence of numbers generated by this
456 class is deterministic. That is to say, given the same seed data,
457 QRandomGenerator will generate the same sequence of numbers. But given
458 different seeds, the results should be considerably different.
459
460 QRandomGenerator::securelySeeded() can be used to create a QRandomGenerator
461 that is securely seeded with QRandomGenerator::system(), meaning that the
462 sequence of numbers it generates cannot be easily predicted. Additionally,
463 QRandomGenerator::global() returns a global instance of QRandomGenerator
464 that Qt will ensure to be securely seeded. This object is thread-safe, may
465 be shared for most uses, and is always seeded from
466 QRandomGenerator::system()
467
468 QRandomGenerator::system() may be used to access the system's
469 cryptographically-safe random generator. On Unix systems, it's equivalent
470 to reading from \c {/dev/urandom} or the \c {getrandom()} or \c
471 {getentropy()} system calls.
472
473 The class can generate 32-bit or 64-bit quantities, or fill an array of
474 those. The most common way of generating new values is to call the generate(),
475 generate64() or fillRange() functions. One would use it as:
476
477 \snippet code/src_corelib_global_qrandom.cpp 0
478
479 Additionally, it provides a floating-point function generateDouble() that
480 returns a number in the range [0, 1) (that is, inclusive of zero and
481 exclusive of 1). There's also a set of convenience functions that
482 facilitate obtaining a random number in a bounded, integral range.
483
484 \section1 Seeding and determinism
485
486 QRandomGenerator may be seeded with specific seed data. When that is done,
487 the numbers generated by the object will always be the same, as in the
488 following example:
489
490 \snippet code/src_corelib_global_qrandom.cpp 1
491
492 The seed data takes the form of one or more 32-bit words. The ideal seed
493 size is approximately equal to the size of the QRandomGenerator class
494 itself. Due to mixing of the seed data, QRandomGenerator cannot guarantee
495 that distinct seeds will produce different sequences.
496
497 QRandomGenerator::global(), like all generators created by
498 QRandomGenerator::securelySeeded(), is always seeded from
499 QRandomGenerator::system(), so it's not possible to make it produce
500 identical sequences.
501
502 \section1 Bulk data
503
504 When operating in deterministic mode, QRandomGenerator may be used for bulk
505 data generation. In fact, applications that do not need
506 cryptographically-secure or true random data are advised to use a regular
507 QRandomGenerator instead of QRandomGenerator::system() for their random
508 data needs.
509
510 For ease of use, QRandomGenerator provides a global object that can
511 be easily used, as in the following example:
512
513 \snippet code/src_corelib_global_qrandom.cpp 2
514
515 \section1 System-wide random number generator
516
517 QRandomGenerator::system() may be used to access the system-wide random
518 number generator, which is cryptographically-safe on all systems that Qt
519 runs on. This function will use hardware facilities to generate random
520 numbers where available. On such systems, those facilities are true Random
521 Number Generators. However, if they are true RNGs, those facilities have
522 finite entropy sources and thus may fail to produce any results if their
523 entropy pool is exhausted.
524
525 If that happens, first the operating system then QRandomGenerator will fall
526 back to Pseudo Random Number Generators of decreasing qualities (Qt's
527 fallback generator being the simplest). Whether those generators are still
528 of cryptographic quality is implementation-defined. Therefore,
529 QRandomGenerator::system() should not be used for high-frequency random
530 number generation, lest the entropy pool become empty. As a rule of thumb,
531 this class should not be called upon to generate more than a kilobyte per
532 second of random data (note: this may vary from system to system).
533
534 If an application needs true RNG data in bulk, it should use the operating
535 system facilities (such as \c{/dev/random} on Linux) directly and wait for
536 entropy to become available. If the application requires PRNG engines of
537 cryptographic quality but not of true randomness,
538 QRandomGenerator::system() may still be used (see section below).
539
540 If neither a true RNG nor a cryptographically secure PRNG are required,
541 applications should instead use PRNG engines like QRandomGenerator's
542 deterministic mode and those from the C++ Standard Library.
543 QRandomGenerator::system() can be used to seed those.
544
545 \section2 Fallback quality
546
547 QRandomGenerator::system() uses the operating system facilities to obtain
548 random numbers, which attempt to collect real entropy from the surrounding
549 environment to produce true random numbers. However, it's possible that the
550 entropy pool becomes exhausted, in which case the operating system will
551 fall back to a pseudo-random engine for a time. Under no circumstances will
552 QRandomGenerator::system() block, waiting for more entropy to be collected.
553
554 The following operating systems guarantee that the results from their
555 random-generation API will be of at least cryptographically-safe quality,
556 even if the entropy pool is exhausted: Apple OSes (Darwin), BSDs, Linux,
557 Windows. Barring a system installation problem (such as \c{/dev/urandom}
558 not being readable by the current process), QRandomGenerator::system() will
559 therefore have the same guarantees.
560
561 On other operating systems, QRandomGenerator will fall back to a PRNG of
562 good numeric distribution, but it cannot guarantee proper seeding in all
563 cases. Please consult the OS documentation for more information.
564
565 Applications that require QRandomGenerator not to fall back to
566 non-cryptographic quality generators are advised to check their operating
567 system documentation or restrict their deployment to one of the above.
568
569 \section1 Reentrancy and thread-safety
570
571 QRandomGenerator is reentrant, meaning that multiple threads can operate on
572 this class at the same time, so long as they operate on different objects.
573 If multiple threads need to share one PRNG sequence, external locking by a
574 mutex is required.
575
576 The exceptions are the objects returned by QRandomGenerator::global() and
577 QRandomGenerator::system(): those objects are thread-safe and may be used
578 by any thread without external locking. Note that thread-safety does not
579 extend to copying those objects: they should always be used by reference.
580
581 \section1 Standard C++ Library compatibility
582
583 QRandomGenerator is modeled after the requirements for random number
584 engines in the C++ Standard Library and may be used in almost all contexts
585 that the Standard Library engines can. Exceptions to the requirements are
586 the following:
587
588 \list
589 \li QRandomGenerator does not support seeding from another seed
590 sequence-like class besides std::seed_seq itself;
591 \li QRandomGenerator is not comparable (but is copyable) or
592 streamable to \c{std::ostream} or from \c{std::istream}.
593 \endlist
594
595 QRandomGenerator is also compatible with the uniform distribution classes
596 \c{std::uniform_int_distribution} and \c{std:uniform_real_distribution}, as
597 well as the free function \c{std::generate_canonical}. For example, the
598 following code may be used to generate a floating-point number in the range
599 [1, 2.5):
600
601 \snippet code/src_corelib_global_qrandom.cpp 3
602
603 \sa QRandomGenerator64, qrand()
604 */
605
606 /*!
607 \enum QRandomGenerator::System
608 \internal
609 */
610
611 /*!
612 \fn QRandomGenerator::QRandomGenerator(quint32 seedValue)
613
614 Initializes this QRandomGenerator object with the value \a seedValue as
615 the seed. Two objects constructed or reseeded with the same seed value will
616 produce the same number sequence.
617
618 \sa seed(), securelySeeded()
619 */
620
621 /*!
622 \fn template <qsizetype N> QRandomGenerator::QRandomGenerator(const quint32 (&seedBuffer)[N])
623 \overload
624
625 Initializes this QRandomGenerator object with the values found in the
626 array \a seedBuffer as the seed. Two objects constructed or reseeded with
627 the same seed value will produce the same number sequence.
628
629 \sa seed(), securelySeeded()
630 */
631
632 /*!
633 \fn QRandomGenerator::QRandomGenerator(const quint32 *seedBuffer, qsizetype len)
634 \overload
635
636 Initializes this QRandomGenerator object with \a len values found in
637 the array \a seedBuffer as the seed. Two objects constructed or reseeded
638 with the same seed value will produce the same number sequence.
639
640 This constructor is equivalent to:
641 \snippet code/src_corelib_global_qrandom.cpp 4
642
643 \sa seed(), securelySeeded()
644 */
645
646 /*!
647 \fn QRandomGenerator::QRandomGenerator(const quint32 *begin, const quint32 *end)
648 \overload
649
650 Initializes this QRandomGenerator object with the values found in the range
651 from \a begin to \a end as the seed. Two objects constructed or reseeded
652 with the same seed value will produce the same number sequence.
653
654 This constructor is equivalent to:
655 \snippet code/src_corelib_global_qrandom.cpp 5
656
657 \sa seed(), securelySeeded()
658 */
659
660 /*!
661 \fn QRandomGenerator::QRandomGenerator(std::seed_seq &sseq)
662 \overload
663
664 Initializes this QRandomGenerator object with the seed sequence \a
665 sseq as the seed. Two objects constructed or reseeded with the same seed
666 value will produce the same number sequence.
667
668 \sa seed(), securelySeeded()
669 */
670
671 /*!
672 \fn QRandomGenerator::QRandomGenerator(const QRandomGenerator &other)
673
674 Creates a copy of the generator state in the \a other object. If \a other is
675 QRandomGenerator::system() or a copy of that, this object will also read
676 from the operating system random-generating facilities. In that case, the
677 sequences generated by the two objects will be different.
678
679 In all other cases, the new QRandomGenerator object will start at the same
680 position in the deterministic sequence as the \a other object was. Both
681 objects will generate the same sequence from this point on.
682
683 For that reason, it is not adviseable to create a copy of
684 QRandomGenerator::global(). If one needs an exclusive deterministic
685 generator, consider instead using securelySeeded() to obtain a new object
686 that shares no relationship with the QRandomGenerator::global().
687 */
688
689 /*!
690 \fn bool operator==(const QRandomGenerator &rng1, const QRandomGenerator &rng2)
691 \relates QRandomGenerator
692
693 Returns true if the two the two engines \a rng1 and \a rng2 are at the same
694 state or if they are both reading from the operating system facilities,
695 false otherwise.
696 */
697
698 /*!
699 \fn bool operator!=(const QRandomGenerator &rng1, const QRandomGenerator &rng2)
700 \relates QRandomGenerator
701
702 Returns true if the two the two engines \a rng1 and \a rng2 are at
703 different states or if one of them is reading from the operating system
704 facilities and the other is not, false otherwise.
705 */
706
707 /*!
708 \typedef QRandomGenerator::result_type
709
710 A typedef to the type that operator() returns. That is, quint32.
711
712 \sa operator()
713 */
714
715 /*!
716 \fn result_type QRandomGenerator::operator()()
717
718 Generates a 32-bit random quantity and returns it.
719
720 \sa generate(), generate64()
721 */
722
723 /*!
724 \fn quint32 QRandomGenerator::generate()
725
726 Generates a 32-bit random quantity and returns it.
727
728 \sa {QRandomGenerator::operator()}{operator()()}, generate64()
729 */
730
731 /*!
732 \fn quint64 QRandomGenerator::generate64()
733
734 Generates a 64-bit random quantity and returns it.
735
736 \sa {QRandomGenerator::operator()}{operator()()}, generate()
737 */
738
739 /*!
740 \fn result_type QRandomGenerator::min()
741
742 Returns the minimum value that QRandomGenerator may ever generate. That is, 0.
743
744 \sa max(), QRandomGenerator64::min()
745 */
746
747 /*!
748 \fn result_type QRandomGenerator::max()
749
750 Returns the maximum value that QRandomGenerator may ever generate. That is,
751 \c {std::numeric_limits<result_type>::max()}.
752
753 \sa min(), QRandomGenerator64::max()
754 */
755
756 /*!
757 \fn void QRandomGenerator::seed(quint32 seed)
758
759 Reseeds this object using the value \a seed as the seed.
760 */
761
762 /*!
763 \fn void QRandomGenerator::seed(std::seed_seq &seed)
764 \overload
765
766 Reseeds this object using the seed sequence \a seed as the seed.
767 */
768
769 /*!
770 \fn void QRandomGenerator::discard(unsigned long long z)
771
772 Discards the next \a z entries from the sequence. This method is equivalent
773 to calling generate() \a z times and discarding the result, as in:
774
775 \snippet code/src_corelib_global_qrandom.cpp 6
776 */
777
778 /*!
779 \fn template <typename ForwardIterator> void QRandomGenerator::generate(ForwardIterator begin, ForwardIterator end)
780
781 Generates 32-bit quantities and stores them in the range between \a begin
782 and \a end. This function is equivalent to (and is implemented as):
783
784 \snippet code/src_corelib_global_qrandom.cpp 7
785
786 This function complies with the requirements for the function
787 \l{http://en.cppreference.com/w/cpp/numeric/random/seed_seq/generate}{\c std::seed_seq::generate},
788 which requires unsigned 32-bit integer values.
789
790 Note that if the [begin, end) range refers to an area that can store more
791 than 32 bits per element, the elements will still be initialized with only
792 32 bits of data. Any other bits will be zero. To fill the range with 64 bit
793 quantities, one can write:
794
795 \snippet code/src_corelib_global_qrandom.cpp 8
796
797 If the range refers to contiguous memory (such as an array or the data from
798 a QVector), the fillRange() function may be used too.
799
800 \sa fillRange()
801 */
802
803 /*!
804 \fn void QRandomGenerator::generate(quint32 *begin, quint32 *end)
805 \overload
806 \internal
807
808 Same as the other overload, but more efficiently fills \a begin to \a end.
809 */
810
811 /*!
812 \fn template <typename UInt> void QRandomGenerator::fillRange(UInt *buffer, qsizetype count)
813
814 Generates \a count 32- or 64-bit quantities (depending on the type \c UInt)
815 and stores them in the buffer pointed by \a buffer. This is the most
816 efficient way to obtain more than one quantity at a time, as it reduces the
817 number of calls into the Random Number Generator source.
818
819 For example, to fill a vector of 16 entries with random values, one may
820 write:
821
822 \snippet code/src_corelib_global_qrandom.cpp 9
823
824 \sa generate()
825 */
826
827 /*!
828 \fn template <typename UInt, size_t N> void QRandomGenerator::fillRange(UInt (&buffer)[N])
829
830 Generates \c N 32- or 64-bit quantities (depending on the type \c UInt) and
831 stores them in the \a buffer array. This is the most efficient way to
832 obtain more than one quantity at a time, as it reduces the number of calls
833 into the Random Number Generator source.
834
835 For example, to fill generate two 32-bit quantities, one may write:
836
837 \snippet code/src_corelib_global_qrandom.cpp 10
838
839 It would have also been possible to make one call to generate64() and then split
840 the two halves of the 64-bit value.
841
842 \sa generate()
843 */
844
845 /*!
846 \fn qreal QRandomGenerator::generateDouble()
847
848 Generates one random qreal in the canonical range [0, 1) (that is,
849 inclusive of zero and exclusive of 1).
850
851 This function is equivalent to:
852 \snippet code/src_corelib_global_qrandom.cpp 11
853
854 The same may also be obtained by using
855 \l{http://en.cppreference.com/w/cpp/numeric/random/uniform_real_distribution}{\c std::uniform_real_distribution}
856 with parameters 0 and 1.
857
858 \sa generate(), generate64(), bounded()
859 */
860
861 /*!
862 \fn double QRandomGenerator::bounded(double highest)
863
864 Generates one random double in the range between 0 (inclusive) and \a
865 highest (exclusive). This function is equivalent to and is implemented as:
866
867 \snippet code/src_corelib_global_qrandom.cpp 12
868
869 If the \a highest parameter is negative, the result will be negative too;
870 if it is infinite or NaN, the result will be infinite or NaN too (that is,
871 not random).
872
873 \sa generateDouble(), bounded()
874 */
875
876 /*!
877 \fn quint32 QRandomGenerator::bounded(quint32 highest)
878 \overload
879
880 Generates one random 32-bit quantity in the range between 0 (inclusive) and
881 \a highest (exclusive). The same result may also be obtained by using
882 \l{http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution}{\c std::uniform_int_distribution}
883 with parameters 0 and \c{highest - 1}. That class can also be used to obtain
884 quantities larger than 32 bits.
885
886 For example, to obtain a value between 0 and 255 (inclusive), one would write:
887
888 \snippet code/src_corelib_global_qrandom.cpp 13
889
890 Naturally, the same could also be obtained by masking the result of generate()
891 to only the lower 8 bits. Either solution is as efficient.
892
893 Note that this function cannot be used to obtain values in the full 32-bit
894 range of quint32. Instead, use generate().
895
896 \sa generate(), generate64(), generateDouble()
897 */
898
899 /*!
900 \fn int QRandomGenerator::bounded(int highest)
901 \overload
902
903 Generates one random 32-bit quantity in the range between 0 (inclusive) and
904 \a highest (exclusive). \a highest must be positive.
905
906 Note that this function cannot be used to obtain values in the full 32-bit
907 range of int. Instead, use generate() and cast to int.
908
909 \sa generate(), generate64(), generateDouble()
910 */
911
912 /*!
913 \fn quint32 QRandomGenerator::bounded(quint32 lowest, quint32 highest)
914 \overload
915
916 Generates one random 32-bit quantity in the range between \a lowest
917 (inclusive) and \a highest (exclusive). The \a highest parameter must be
918 greater than \a lowest.
919
920 The same result may also be obtained by using
921 \l{http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution}{\c std::uniform_int_distribution}
922 with parameters \a lowest and \c{\a highest - 1}. That class can also be used to
923 obtain quantities larger than 32 bits.
924
925 For example, to obtain a value between 1000 (incl.) and 2000 (excl.), one
926 would write:
927
928 \snippet code/src_corelib_global_qrandom.cpp 14
929
930 Note that this function cannot be used to obtain values in the full 32-bit
931 range of quint32. Instead, use generate().
932
933 \sa generate(), generate64(), generateDouble()
934 */
935
936 /*!
937 \fn int QRandomGenerator::bounded(int lowest, int highest)
938 \overload
939
940 Generates one random 32-bit quantity in the range between \a lowest
941 (inclusive) and \a highest (exclusive), both of which may be negative, but
942 \a highest must be greater than \a lowest.
943
944 Note that this function cannot be used to obtain values in the full 32-bit
945 range of int. Instead, use generate() and cast to int.
946
947 \sa generate(), generate64(), generateDouble()
948 */
949
950 /*!
951 \fn QRandomGenerator *QRandomGenerator::system()
952 \threadsafe
953
954 Returns a pointer to a shared QRandomGenerator that always uses the
955 facilities provided by the operating system to generate random numbers. The
956 system facilities are considered to be cryptographically safe on at least
957 the following operating systems: Apple OSes (Darwin), BSDs, Linux, Windows.
958 That may also be the case on other operating systems.
959
960 They are also possibly backed by a true hardware random number generator.
961 For that reason, the QRandomGenerator returned by this function should not
962 be used for bulk data generation. Instead, use it to seed QRandomGenerator
963 or a random engine from the <random> header.
964
965 The object returned by this function is thread-safe and may be used in any
966 thread without locks. It may also be copied and the resulting
967 QRandomGenerator will also access the operating system facilities, but they
968 will not generate the same sequence.
969
970 \sa securelySeeded(), global()
971 */
972
973 /*!
974 \fn QRandomGenerator *QRandomGenerator::global()
975 \threadsafe
976
977 Returns a pointer to a shared QRandomGenerator that was seeded using
978 securelySeeded(). This function should be used to create random data
979 without the expensive creation of a securely-seeded QRandomGenerator
980 for a specific use or storing the rather large QRandomGenerator object.
981
982 For example, the following creates a random RGB color:
983
984 \snippet code/src_corelib_global_qrandom.cpp 15
985
986 Accesses to this object are thread-safe and it may therefore be used in any
987 thread without locks. The object may also be copied and the sequence
988 produced by the copy will be the same as the shared object will produce.
989 Note, however, that if there are other threads accessing the global object,
990 those threads may obtain samples at unpredictable intervals.
991
992 \sa securelySeeded(), system()
993 */
994
995 /*!
996 \fn QRandomGenerator QRandomGenerator::securelySeeded()
997
998 Returns a new QRandomGenerator object that was securely seeded with
999 QRandomGenerator::system(). This function will obtain the ideal seed size
1000 for the algorithm that QRandomGenerator uses and is therefore the
1001 recommended way for creating a new QRandomGenerator object that will be
1002 kept for some time.
1003
1004 Given the amount of data required to securely seed the deterministic
1005 engine, this function is somewhat expensive and should not be used for
1006 short-term uses of QRandomGenerator (using it to generate fewer than 2600
1007 bytes of random data is effectively a waste of resources). If the use
1008 doesn't require that much data, consider using QRandomGenerator::global()
1009 and not storing a QRandomGenerator object instead.
1010
1011 \sa global(), system()
1012 */
1013
1014 /*!
1015 \class QRandomGenerator64
1016 \inmodule QtCore
1017 \since 5.10
1018
1019 \brief The QRandomGenerator64 class allows one to obtain 64-bit random values
1020 from a high-quality, seed-less Random Number Generator.
1021
1022 QRandomGenerator64 is a simple adaptor class around QRandomGenerator, making the
1023 QRandomGenerator::generate64() function the default for operator()(), instead of the
1024 function that returns 32-bit quantities. This class is intended to be used
1025 in conjunction with Standard Library algorithms that need 64-bit quantities
1026 instead of 32-bit ones.
1027
1028 In all other aspects, the class is the same. Please refer to
1029 QRandomGenerator's documentation for more information.
1030
1031 \sa QRandomGenerator
1032 */
1033
1034 /*!
1035 \typedef QRandomGenerator64::result_type
1036
1037 A typedef to the type that operator() returns. That is, quint64.
1038
1039 \sa operator()
1040 */
1041
1042 /*!
1043 \fn quint64 QRandomGenerator64::generate()
1044
1045 Generates one 64-bit random value and returns it.
1046
1047 Note about casting to a signed integer: all bits returned by this function
1048 are random, so there's a 50% chance that the most significant bit will be
1049 set. If you wish to cast the returned value to qint64 and keep it positive,
1050 you should mask the sign bit off:
1051
1052 \snippet code/src_corelib_global_qrandom.cpp 16
1053
1054 \sa QRandomGenerator, QRandomGenerator::generate64()
1055 */
1056
1057 /*!
1058 \fn result_type QRandomGenerator64::operator()()
1059
1060 Generates a 64-bit random quantity and returns it.
1061
1062 \sa QRandomGenerator::generate(), QRandomGenerator::generate64()
1063 */
1064
Storage()1065 Q_DECL_CONSTEXPR QRandomGenerator::Storage::Storage()
1066 : dummy(0)
1067 {
1068 // nothing
1069 }
1070
QRandomGenerator64(System s)1071 inline QRandomGenerator64::QRandomGenerator64(System s)
1072 : QRandomGenerator(s)
1073 {
1074 }
1075
system()1076 QRandomGenerator64 *QRandomGenerator64::system()
1077 {
1078 auto self = SystemAndGlobalGenerators::system();
1079 Q_ASSERT(self->type == SystemRNG);
1080 return self;
1081 }
1082
global()1083 QRandomGenerator64 *QRandomGenerator64::global()
1084 {
1085 auto self = SystemAndGlobalGenerators::globalNoInit();
1086
1087 // Yes, this is a double-checked lock.
1088 // We can return even if the type is not completely initialized yet:
1089 // any thread trying to actually use the contents of the random engine
1090 // will necessarily wait on the lock.
1091 if (Q_LIKELY(self->type != SystemRNG))
1092 return self;
1093
1094 SystemAndGlobalGenerators::PRNGLocker locker(self);
1095 if (self->type == SystemRNG)
1096 SystemAndGlobalGenerators::securelySeed(self);
1097
1098 return self;
1099 }
1100
securelySeeded()1101 QRandomGenerator64 QRandomGenerator64::securelySeeded()
1102 {
1103 QRandomGenerator64 result(System{});
1104 SystemAndGlobalGenerators::securelySeed(&result);
1105 return result;
1106 }
1107
1108 /*!
1109 \internal
1110 */
QRandomGenerator(System)1111 inline QRandomGenerator::QRandomGenerator(System)
1112 : type(SystemRNG)
1113 {
1114 // don't touch storage
1115 }
1116
QRandomGenerator(const QRandomGenerator & other)1117 QRandomGenerator::QRandomGenerator(const QRandomGenerator &other)
1118 : type(other.type)
1119 {
1120 Q_ASSERT(this != system());
1121 Q_ASSERT(this != SystemAndGlobalGenerators::globalNoInit());
1122
1123 if (type != SystemRNG) {
1124 SystemAndGlobalGenerators::PRNGLocker lock(&other);
1125 storage.engine() = other.storage.engine();
1126 }
1127 }
1128
operator =(const QRandomGenerator & other)1129 QRandomGenerator &QRandomGenerator::operator=(const QRandomGenerator &other)
1130 {
1131 if (Q_UNLIKELY(this == system()) || Q_UNLIKELY(this == SystemAndGlobalGenerators::globalNoInit()))
1132 qFatal("Attempted to overwrite a QRandomGenerator to system() or global().");
1133
1134 if ((type = other.type) != SystemRNG) {
1135 SystemAndGlobalGenerators::PRNGLocker lock(&other);
1136 storage.engine() = other.storage.engine();
1137 }
1138 return *this;
1139 }
1140
QRandomGenerator(std::seed_seq & sseq)1141 QRandomGenerator::QRandomGenerator(std::seed_seq &sseq) noexcept
1142 : type(MersenneTwister)
1143 {
1144 Q_ASSERT(this != system());
1145 Q_ASSERT(this != SystemAndGlobalGenerators::globalNoInit());
1146
1147 new (&storage.engine()) RandomEngine(sseq);
1148 }
1149
QRandomGenerator(const quint32 * begin,const quint32 * end)1150 QRandomGenerator::QRandomGenerator(const quint32 *begin, const quint32 *end)
1151 : type(MersenneTwister)
1152 {
1153 Q_ASSERT(this != system());
1154 Q_ASSERT(this != SystemAndGlobalGenerators::globalNoInit());
1155
1156 std::seed_seq s(begin, end);
1157 new (&storage.engine()) RandomEngine(s);
1158 }
1159
discard(unsigned long long z)1160 void QRandomGenerator::discard(unsigned long long z)
1161 {
1162 if (Q_UNLIKELY(type == SystemRNG))
1163 return;
1164
1165 SystemAndGlobalGenerators::PRNGLocker lock(this);
1166 storage.engine().discard(z);
1167 }
1168
operator ==(const QRandomGenerator & rng1,const QRandomGenerator & rng2)1169 bool operator==(const QRandomGenerator &rng1, const QRandomGenerator &rng2)
1170 {
1171 if (rng1.type != rng2.type)
1172 return false;
1173 if (rng1.type == SystemRNG)
1174 return true;
1175
1176 // Lock global() if either is it (otherwise this locking is a no-op)
1177 using PRNGLocker = QRandomGenerator::SystemAndGlobalGenerators::PRNGLocker;
1178 PRNGLocker locker(&rng1 == QRandomGenerator::global() ? &rng1 : &rng2);
1179 return rng1.storage.engine() == rng2.storage.engine();
1180 }
1181
1182 /*!
1183 \internal
1184
1185 Fills the range pointed by \a buffer and \a bufferEnd with 32-bit random
1186 values. The buffer must be correctly aligned.
1187 */
_fillRange(void * buffer,void * bufferEnd)1188 void QRandomGenerator::_fillRange(void *buffer, void *bufferEnd)
1189 {
1190 // Verify that the pointers are properly aligned for 32-bit
1191 Q_ASSERT(quintptr(buffer) % sizeof(quint32) == 0);
1192 Q_ASSERT(quintptr(bufferEnd) % sizeof(quint32) == 0);
1193 quint32 *begin = static_cast<quint32 *>(buffer);
1194 quint32 *end = static_cast<quint32 *>(bufferEnd);
1195
1196 if (type == SystemRNG || Q_UNLIKELY(uint(qt_randomdevice_control.loadAcquire()) & (UseSystemRNG|SetRandomData)))
1197 return SystemGenerator::self().generate(begin, end);
1198
1199 SystemAndGlobalGenerators::PRNGLocker lock(this);
1200 std::generate(begin, end, [this]() { return storage.engine()(); });
1201 }
1202
1203 namespace {
1204 struct QRandEngine
1205 {
1206 std::minstd_rand engine;
QRandEngine__anona03d4d740611::QRandEngine1207 QRandEngine() : engine(1) {}
1208
generate__anona03d4d740611::QRandEngine1209 int generate()
1210 {
1211 std::minstd_rand::result_type v = engine();
1212 if (std::numeric_limits<int>::max() != RAND_MAX)
1213 v %= uint(RAND_MAX) + 1;
1214
1215 return int(v);
1216 }
1217
seed__anona03d4d740611::QRandEngine1218 void seed(std::minstd_rand::result_type q)
1219 {
1220 engine.seed(q);
1221 }
1222 };
1223 }
1224
1225 #if defined(Q_OS_WIN)
1226 // On Windows srand() and rand() already use Thread-Local-Storage
1227 // to store the seed between calls
randTLS()1228 static inline QRandEngine *randTLS()
1229 {
1230 return nullptr;
1231 }
1232 #elif defined(Q_COMPILER_THREAD_LOCAL)
randTLS()1233 static inline QRandEngine *randTLS()
1234 {
1235 thread_local QRandEngine r;
1236 return &r;
1237 }
1238 #else
Q_GLOBAL_STATIC(QThreadStorage<QRandEngine>,g_randTLS)1239 Q_GLOBAL_STATIC(QThreadStorage<QRandEngine>, g_randTLS)
1240 static inline QRandEngine *randTLS()
1241 {
1242 auto tls = g_randTLS();
1243 if (!tls)
1244 return nullptr;
1245 return &tls->localData();
1246
1247 }
1248 #endif
1249
1250 /*!
1251 \relates <QtGlobal>
1252 \deprecated
1253 \since 4.2
1254
1255 Thread-safe version of the standard C++ \c srand() function.
1256
1257 Sets the argument \a seed to be used to generate a new random number sequence of
1258 pseudo random integers to be returned by qrand().
1259
1260 The sequence of random numbers generated is deterministic per thread. For example,
1261 if two threads call qsrand(1) and subsequently call qrand(), the threads will get
1262 the same random number sequence.
1263
1264 \note This function is deprecated. In new applications, use
1265 QRandomGenerator instead.
1266
1267 \sa qrand(), QRandomGenerator
1268 */
qsrand(uint seed)1269 void qsrand(uint seed)
1270 {
1271 auto prng = randTLS();
1272 if (prng)
1273 prng->seed(seed);
1274 else
1275 srand(seed);
1276 }
1277
1278 /*!
1279 \relates <QtGlobal>
1280 \deprecated
1281 \since 4.2
1282
1283 Thread-safe version of the standard C++ \c rand() function.
1284
1285 Returns a value between 0 and \c RAND_MAX (defined in \c <cstdlib> and
1286 \c <stdlib.h>), the next number in the current sequence of pseudo-random
1287 integers.
1288
1289 Use \c qsrand() to initialize the pseudo-random number generator with a
1290 seed value. Seeding must be performed at least once on each thread. If that
1291 step is skipped, then the sequence will be pre-seeded with a constant
1292 value.
1293
1294 \note This function is deprecated. In new applications, use
1295 QRandomGenerator instead.
1296
1297 \sa qsrand(), QRandomGenerator
1298 */
qrand()1299 int qrand()
1300 {
1301 auto prng = randTLS();
1302 if (prng)
1303 return prng->generate();
1304 else
1305 return rand();
1306 }
1307
1308 QT_END_NAMESPACE
1309