Coverage Report

Created: 2025-07-09 06:20

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