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