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