Imported Upstream version 2.74.3
[platform/upstream/glib.git] / glib / grand.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * SPDX-License-Identifier: LGPL-2.1-or-later
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
18  */
19
20 /* Originally developed and coded by Makoto Matsumoto and Takuji
21  * Nishimura.  Please mail <matumoto@math.keio.ac.jp>, if you're using
22  * code from this file in your own programs or libraries.
23  * Further information on the Mersenne Twister can be found at
24  * http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
25  * This code was adapted to glib by Sebastian Wilhelmi.
26  */
27
28 /*
29  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
30  * file for a list of people on the GLib Team.  See the ChangeLog
31  * files for a list of changes.  These files are distributed with
32  * GLib at ftp://ftp.gtk.org/pub/gtk/.
33  */
34
35 /*
36  * MT safe
37  */
38
39 #include "config.h"
40 #define _CRT_RAND_S
41
42 #include <math.h>
43 #include <errno.h>
44 #include <stdio.h>
45 #include <string.h>
46 #include <sys/types.h>
47 #include "grand.h"
48
49 #include "genviron.h"
50 #include "gmain.h"
51 #include "gmem.h"
52 #include "gtestutils.h"
53 #include "gthread.h"
54 #include "gtimer.h"
55
56 #ifdef G_OS_UNIX
57 #include <unistd.h>
58 #endif
59
60 #ifdef G_OS_WIN32
61 #include <stdlib.h>
62 #include <process.h> /* For getpid() */
63 #endif
64
65 /**
66  * SECTION:random_numbers
67  * @title: Random Numbers
68  * @short_description: pseudo-random number generator
69  *
70  * The following functions allow you to use a portable, fast and good
71  * pseudo-random number generator (PRNG).
72  * 
73  * Do not use this API for cryptographic purposes such as key
74  * generation, nonces, salts or one-time pads.
75  *
76  * This PRNG is suitable for non-cryptographic use such as in games
77  * (shuffling a card deck, generating levels), generating data for
78  * a test suite, etc. If you need random data for cryptographic
79  * purposes, it is recommended to use platform-specific APIs such
80  * as `/dev/random` on UNIX, or CryptGenRandom() on Windows.
81  *
82  * GRand uses the Mersenne Twister PRNG, which was originally
83  * developed by Makoto Matsumoto and Takuji Nishimura. Further
84  * information can be found at
85  * [this page](http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html).
86  *
87  * If you just need a random number, you simply call the g_random_*
88  * functions, which will create a globally used #GRand and use the
89  * according g_rand_* functions internally. Whenever you need a
90  * stream of reproducible random numbers, you better create a
91  * #GRand yourself and use the g_rand_* functions directly, which
92  * will also be slightly faster. Initializing a #GRand with a
93  * certain seed will produce exactly the same series of random
94  * numbers on all platforms. This can thus be used as a seed for
95  * e.g. games.
96  *
97  * The g_rand*_range functions will return high quality equally
98  * distributed random numbers, whereas for example the
99  * `(g_random_int()%max)` approach often
100  * doesn't yield equally distributed numbers.
101  *
102  * GLib changed the seeding algorithm for the pseudo-random number
103  * generator Mersenne Twister, as used by #GRand. This was necessary,
104  * because some seeds would yield very bad pseudo-random streams.
105  * Also the pseudo-random integers generated by g_rand*_int_range()
106  * will have a slightly better equal distribution with the new
107  * version of GLib.
108  *
109  * The original seeding and generation algorithms, as found in
110  * GLib 2.0.x, can be used instead of the new ones by setting the
111  * environment variable `G_RANDOM_VERSION` to the value of '2.0'.
112  * Use the GLib-2.0 algorithms only if you have sequences of numbers
113  * generated with Glib-2.0 that you need to reproduce exactly.
114  */
115
116 /**
117  * GRand:
118  *
119  * The GRand struct is an opaque data structure. It should only be
120  * accessed through the g_rand_* functions.
121  **/
122
123 G_LOCK_DEFINE_STATIC (global_random);
124
125 /* Period parameters */  
126 #define N 624
127 #define M 397
128 #define MATRIX_A 0x9908b0df   /* constant vector a */
129 #define UPPER_MASK 0x80000000 /* most significant w-r bits */
130 #define LOWER_MASK 0x7fffffff /* least significant r bits */
131
132 /* Tempering parameters */   
133 #define TEMPERING_MASK_B 0x9d2c5680
134 #define TEMPERING_MASK_C 0xefc60000
135 #define TEMPERING_SHIFT_U(y)  (y >> 11)
136 #define TEMPERING_SHIFT_S(y)  (y << 7)
137 #define TEMPERING_SHIFT_T(y)  (y << 15)
138 #define TEMPERING_SHIFT_L(y)  (y >> 18)
139
140 static guint
141 get_random_version (void)
142 {
143   static gsize initialized = FALSE;
144   static guint random_version;
145
146   if (g_once_init_enter (&initialized))
147     {
148       const gchar *version_string = g_getenv ("G_RANDOM_VERSION");
149       if (!version_string || version_string[0] == '\000' || 
150           strcmp (version_string, "2.2") == 0)
151         random_version = 22;
152       else if (strcmp (version_string, "2.0") == 0)
153         random_version = 20;
154       else
155         {
156           g_warning ("Unknown G_RANDOM_VERSION \"%s\". Using version 2.2.",
157                      version_string);
158           random_version = 22;
159         }
160       g_once_init_leave (&initialized, TRUE);
161     }
162   
163   return random_version;
164 }
165
166 struct _GRand
167 {
168   guint32 mt[N]; /* the array for the state vector  */
169   guint mti; 
170 };
171
172 /**
173  * g_rand_new_with_seed:
174  * @seed: a value to initialize the random number generator
175  * 
176  * Creates a new random number generator initialized with @seed.
177  * 
178  * Returns: the new #GRand
179  **/
180 GRand*
181 g_rand_new_with_seed (guint32 seed)
182 {
183   GRand *rand = g_new0 (GRand, 1);
184   g_rand_set_seed (rand, seed);
185   return rand;
186 }
187
188 /**
189  * g_rand_new_with_seed_array:
190  * @seed: an array of seeds to initialize the random number generator
191  * @seed_length: an array of seeds to initialize the random number
192  *     generator
193  * 
194  * Creates a new random number generator initialized with @seed.
195  * 
196  * Returns: the new #GRand
197  *
198  * Since: 2.4
199  */
200 GRand*
201 g_rand_new_with_seed_array (const guint32 *seed,
202                             guint          seed_length)
203 {
204   GRand *rand = g_new0 (GRand, 1);
205   g_rand_set_seed_array (rand, seed, seed_length);
206   return rand;
207 }
208
209 /**
210  * g_rand_new:
211  * 
212  * Creates a new random number generator initialized with a seed taken
213  * either from `/dev/urandom` (if existing) or from the current time
214  * (as a fallback).
215  *
216  * On Windows, the seed is taken from rand_s().
217  * 
218  * Returns: the new #GRand
219  */
220 GRand* 
221 g_rand_new (void)
222 {
223   guint32 seed[4];
224 #ifdef G_OS_UNIX
225   static gboolean dev_urandom_exists = TRUE;
226
227   if (dev_urandom_exists)
228     {
229       FILE* dev_urandom;
230
231       do
232         {
233           dev_urandom = fopen("/dev/urandom", "rb");
234         }
235       while G_UNLIKELY (dev_urandom == NULL && errno == EINTR);
236
237       if (dev_urandom)
238         {
239           int r;
240
241           setvbuf (dev_urandom, NULL, _IONBF, 0);
242           do
243             {
244               errno = 0;
245               r = fread (seed, sizeof (seed), 1, dev_urandom);
246             }
247           while G_UNLIKELY (errno == EINTR);
248
249           if (r != 1)
250             dev_urandom_exists = FALSE;
251
252           fclose (dev_urandom);
253         }       
254       else
255         dev_urandom_exists = FALSE;
256     }
257
258   if (!dev_urandom_exists)
259     {
260       gint64 now_us = g_get_real_time ();
261       seed[0] = now_us / G_USEC_PER_SEC;
262       seed[1] = now_us % G_USEC_PER_SEC;
263       seed[2] = getpid ();
264       seed[3] = getppid ();
265     }
266 #else /* G_OS_WIN32 */
267   /* rand_s() is only available since Visual Studio 2005 and
268    * MinGW-w64 has a wrapper that will emulate rand_s() if it's not in msvcrt
269    */
270 #if (defined(_MSC_VER) && _MSC_VER >= 1400) || defined(__MINGW64_VERSION_MAJOR)
271   gsize i;
272
273   for (i = 0; i < G_N_ELEMENTS (seed); i++)
274     rand_s (&seed[i]);
275 #else
276 #warning Using insecure seed for random number generation because of missing rand_s() in Windows XP
277   GTimeVal now;
278
279   g_get_current_time (&now);
280   seed[0] = now.tv_sec;
281   seed[1] = now.tv_usec;
282   seed[2] = getpid ();
283   seed[3] = 0;
284 #endif
285
286 #endif
287
288   return g_rand_new_with_seed_array (seed, 4);
289 }
290
291 /**
292  * g_rand_free:
293  * @rand_: a #GRand
294  *
295  * Frees the memory allocated for the #GRand.
296  */
297 void
298 g_rand_free (GRand *rand)
299 {
300   g_return_if_fail (rand != NULL);
301
302   g_free (rand);
303 }
304
305 /**
306  * g_rand_copy:
307  * @rand_: a #GRand
308  *
309  * Copies a #GRand into a new one with the same exact state as before.
310  * This way you can take a snapshot of the random number generator for
311  * replaying later.
312  *
313  * Returns: the new #GRand
314  *
315  * Since: 2.4
316  */
317 GRand*
318 g_rand_copy (GRand *rand)
319 {
320   GRand* new_rand;
321
322   g_return_val_if_fail (rand != NULL, NULL);
323
324   new_rand = g_new0 (GRand, 1);
325   memcpy (new_rand, rand, sizeof (GRand));
326
327   return new_rand;
328 }
329
330 /**
331  * g_rand_set_seed:
332  * @rand_: a #GRand
333  * @seed: a value to reinitialize the random number generator
334  *
335  * Sets the seed for the random number generator #GRand to @seed.
336  */
337 void
338 g_rand_set_seed (GRand   *rand,
339                  guint32  seed)
340 {
341   g_return_if_fail (rand != NULL);
342
343   switch (get_random_version ())
344     {
345     case 20:
346       /* setting initial seeds to mt[N] using         */
347       /* the generator Line 25 of Table 1 in          */
348       /* [KNUTH 1981, The Art of Computer Programming */
349       /*    Vol. 2 (2nd Ed.), pp102]                  */
350       
351       if (seed == 0) /* This would make the PRNG produce only zeros */
352         seed = 0x6b842128; /* Just set it to another number */
353       
354       rand->mt[0]= seed;
355       for (rand->mti=1; rand->mti<N; rand->mti++)
356         rand->mt[rand->mti] = (69069 * rand->mt[rand->mti-1]);
357       
358       break;
359     case 22:
360       /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
361       /* In the previous version (see above), MSBs of the    */
362       /* seed affect only MSBs of the array mt[].            */
363       
364       rand->mt[0]= seed;
365       for (rand->mti=1; rand->mti<N; rand->mti++)
366         rand->mt[rand->mti] = 1812433253UL * 
367           (rand->mt[rand->mti-1] ^ (rand->mt[rand->mti-1] >> 30)) + rand->mti; 
368       break;
369     default:
370       g_assert_not_reached ();
371     }
372 }
373
374 /**
375  * g_rand_set_seed_array:
376  * @rand_: a #GRand
377  * @seed: array to initialize with
378  * @seed_length: length of array
379  *
380  * Initializes the random number generator by an array of longs.
381  * Array can be of arbitrary size, though only the first 624 values
382  * are taken.  This function is useful if you have many low entropy
383  * seeds, or if you require more then 32 bits of actual entropy for
384  * your application.
385  *
386  * Since: 2.4
387  */
388 void
389 g_rand_set_seed_array (GRand         *rand,
390                        const guint32 *seed,
391                        guint          seed_length)
392 {
393   guint i, j, k;
394
395   g_return_if_fail (rand != NULL);
396   g_return_if_fail (seed_length >= 1);
397
398   g_rand_set_seed (rand, 19650218UL);
399
400   i=1; j=0;
401   k = (N>seed_length ? N : seed_length);
402   for (; k; k--)
403     {
404       rand->mt[i] = (rand->mt[i] ^
405                      ((rand->mt[i-1] ^ (rand->mt[i-1] >> 30)) * 1664525UL))
406               + seed[j] + j; /* non linear */
407       rand->mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
408       i++; j++;
409       if (i>=N)
410         {
411           rand->mt[0] = rand->mt[N-1];
412           i=1;
413         }
414       if (j>=seed_length)
415         j=0;
416     }
417   for (k=N-1; k; k--)
418     {
419       rand->mt[i] = (rand->mt[i] ^
420                      ((rand->mt[i-1] ^ (rand->mt[i-1] >> 30)) * 1566083941UL))
421               - i; /* non linear */
422       rand->mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
423       i++;
424       if (i>=N)
425         {
426           rand->mt[0] = rand->mt[N-1];
427           i=1;
428         }
429     }
430
431   rand->mt[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */ 
432 }
433
434 /**
435  * g_rand_boolean:
436  * @rand_: a #GRand
437  *
438  * Returns a random #gboolean from @rand_.
439  * This corresponds to an unbiased coin toss.
440  *
441  * Returns: a random #gboolean
442  */
443 /**
444  * g_rand_int:
445  * @rand_: a #GRand
446  *
447  * Returns the next random #guint32 from @rand_ equally distributed over
448  * the range [0..2^32-1].
449  *
450  * Returns: a random number
451  */
452 guint32
453 g_rand_int (GRand *rand)
454 {
455   guint32 y;
456   static const guint32 mag01[2]={0x0, MATRIX_A};
457   /* mag01[x] = x * MATRIX_A  for x=0,1 */
458
459   g_return_val_if_fail (rand != NULL, 0);
460
461   if (rand->mti >= N) { /* generate N words at one time */
462     int kk;
463     
464     for (kk = 0; kk < N - M; kk++) {
465       y = (rand->mt[kk]&UPPER_MASK)|(rand->mt[kk+1]&LOWER_MASK);
466       rand->mt[kk] = rand->mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1];
467     }
468     for (; kk < N - 1; kk++) {
469       y = (rand->mt[kk]&UPPER_MASK)|(rand->mt[kk+1]&LOWER_MASK);
470       rand->mt[kk] = rand->mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1];
471     }
472     y = (rand->mt[N-1]&UPPER_MASK)|(rand->mt[0]&LOWER_MASK);
473     rand->mt[N-1] = rand->mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1];
474     
475     rand->mti = 0;
476   }
477   
478   y = rand->mt[rand->mti++];
479   y ^= TEMPERING_SHIFT_U(y);
480   y ^= TEMPERING_SHIFT_S(y) & TEMPERING_MASK_B;
481   y ^= TEMPERING_SHIFT_T(y) & TEMPERING_MASK_C;
482   y ^= TEMPERING_SHIFT_L(y);
483   
484   return y; 
485 }
486
487 /* transform [0..2^32] -> [0..1] */
488 #define G_RAND_DOUBLE_TRANSFORM 2.3283064365386962890625e-10
489
490 /**
491  * g_rand_int_range:
492  * @rand_: a #GRand
493  * @begin: lower closed bound of the interval
494  * @end: upper open bound of the interval
495  *
496  * Returns the next random #gint32 from @rand_ equally distributed over
497  * the range [@begin..@end-1].
498  *
499  * Returns: a random number
500  */
501 gint32 
502 g_rand_int_range (GRand  *rand,
503                   gint32  begin,
504                   gint32  end)
505 {
506   guint32 dist = end - begin;
507   guint32 random = 0;
508
509   g_return_val_if_fail (rand != NULL, begin);
510   g_return_val_if_fail (end > begin, begin);
511
512   switch (get_random_version ())
513     {
514     case 20:
515       if (dist <= 0x10000L) /* 2^16 */
516         {
517           /* This method, which only calls g_rand_int once is only good
518            * for (end - begin) <= 2^16, because we only have 32 bits set
519            * from the one call to g_rand_int ().
520            *
521            * We are using (trans + trans * trans), because g_rand_int only
522            * covers [0..2^32-1] and thus g_rand_int * trans only covers
523            * [0..1-2^-32], but the biggest double < 1 is 1-2^-52. 
524            */
525           
526           gdouble double_rand = g_rand_int (rand) * 
527             (G_RAND_DOUBLE_TRANSFORM +
528              G_RAND_DOUBLE_TRANSFORM * G_RAND_DOUBLE_TRANSFORM);
529           
530           random = (gint32) (double_rand * dist);
531         }
532       else
533         {
534           /* Now we use g_rand_double_range (), which will set 52 bits
535            * for us, so that it is safe to round and still get a decent
536            * distribution
537            */
538           random = (gint32) g_rand_double_range (rand, 0, dist);
539         }
540       break;
541     case 22:
542       if (dist == 0)
543         random = 0;
544       else 
545         {
546           /* maxvalue is set to the predecessor of the greatest
547            * multiple of dist less or equal 2^32.
548            */
549           guint32 maxvalue;
550           if (dist <= 0x80000000u) /* 2^31 */
551             {
552               /* maxvalue = 2^32 - 1 - (2^32 % dist) */
553               guint32 leftover = (0x80000000u % dist) * 2;
554               if (leftover >= dist) leftover -= dist;
555               maxvalue = 0xffffffffu - leftover;
556             }
557           else
558             maxvalue = dist - 1;
559           
560           do
561             random = g_rand_int (rand);
562           while (random > maxvalue);
563           
564           random %= dist;
565         }
566       break;
567     default:
568       g_assert_not_reached ();
569     }      
570  
571   return begin + random;
572 }
573
574 /**
575  * g_rand_double:
576  * @rand_: a #GRand
577  *
578  * Returns the next random #gdouble from @rand_ equally distributed over
579  * the range [0..1).
580  *
581  * Returns: a random number
582  */
583 gdouble 
584 g_rand_double (GRand *rand)
585 {    
586   /* We set all 52 bits after the point for this, not only the first
587      32. That's why we need two calls to g_rand_int */
588   gdouble retval = g_rand_int (rand) * G_RAND_DOUBLE_TRANSFORM;
589   retval = (retval + g_rand_int (rand)) * G_RAND_DOUBLE_TRANSFORM;
590
591   /* The following might happen due to very bad rounding luck, but
592    * actually this should be more than rare, we just try again then */
593   if (retval >= 1.0) 
594     return g_rand_double (rand);
595
596   return retval;
597 }
598
599 /**
600  * g_rand_double_range:
601  * @rand_: a #GRand
602  * @begin: lower closed bound of the interval
603  * @end: upper open bound of the interval
604  *
605  * Returns the next random #gdouble from @rand_ equally distributed over
606  * the range [@begin..@end).
607  *
608  * Returns: a random number
609  */
610 gdouble 
611 g_rand_double_range (GRand   *rand,
612                      gdouble  begin,
613                      gdouble  end)
614 {
615   gdouble r;
616
617   r = g_rand_double (rand);
618
619   return r * end - (r - 1) * begin;
620 }
621
622 static GRand *
623 get_global_random (void)
624 {
625   static GRand *global_random;
626
627   /* called while locked */
628   if (!global_random)
629     global_random = g_rand_new ();
630
631   return global_random;
632 }
633
634 /**
635  * g_random_boolean:
636  *
637  * Returns a random #gboolean.
638  * This corresponds to an unbiased coin toss.
639  *
640  * Returns: a random #gboolean
641  */
642 /**
643  * g_random_int:
644  *
645  * Return a random #guint32 equally distributed over the range
646  * [0..2^32-1].
647  *
648  * Returns: a random number
649  */
650 guint32
651 g_random_int (void)
652 {
653   guint32 result;
654   G_LOCK (global_random);
655   result = g_rand_int (get_global_random ());
656   G_UNLOCK (global_random);
657   return result;
658 }
659
660 /**
661  * g_random_int_range:
662  * @begin: lower closed bound of the interval
663  * @end: upper open bound of the interval
664  *
665  * Returns a random #gint32 equally distributed over the range
666  * [@begin..@end-1].
667  *
668  * Returns: a random number
669  */
670 gint32 
671 g_random_int_range (gint32 begin,
672                     gint32 end)
673 {
674   gint32 result;
675   G_LOCK (global_random);
676   result = g_rand_int_range (get_global_random (), begin, end);
677   G_UNLOCK (global_random);
678   return result;
679 }
680
681 /**
682  * g_random_double:
683  *
684  * Returns a random #gdouble equally distributed over the range [0..1).
685  *
686  * Returns: a random number
687  */
688 gdouble 
689 g_random_double (void)
690 {
691   double result;
692   G_LOCK (global_random);
693   result = g_rand_double (get_global_random ());
694   G_UNLOCK (global_random);
695   return result;
696 }
697
698 /**
699  * g_random_double_range:
700  * @begin: lower closed bound of the interval
701  * @end: upper open bound of the interval
702  *
703  * Returns a random #gdouble equally distributed over the range
704  * [@begin..@end).
705  *
706  * Returns: a random number
707  */
708 gdouble 
709 g_random_double_range (gdouble begin,
710                        gdouble end)
711 {
712   double result;
713   G_LOCK (global_random);
714   result = g_rand_double_range (get_global_random (), begin, end);
715   G_UNLOCK (global_random);
716   return result;
717 }
718
719 /**
720  * g_random_set_seed:
721  * @seed: a value to reinitialize the global random number generator
722  * 
723  * Sets the seed for the global random number generator, which is used
724  * by the g_random_* functions, to @seed.
725  */
726 void
727 g_random_set_seed (guint32 seed)
728 {
729   G_LOCK (global_random);
730   g_rand_set_seed (get_global_random (), seed);
731   G_UNLOCK (global_random);
732 }