-
-
Notifications
You must be signed in to change notification settings - Fork 45
/
dmalloc_rand.c
92 lines (82 loc) · 2.33 KB
/
dmalloc_rand.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/*
* Internal random number generator
*
* This file is part of the dmalloc package.
*
* Permission to use, copy, modify, and distribute this software for
* any purpose and without fee is hereby granted, provided that the
* above copyright notice and this permission notice appear in all
* copies, and that the name of Gray Watson not be used in advertising
* or publicity pertaining to distribution of the document or software
* without specific, written prior permission.
*
* Gray Watson makes no representations about the suitability of the
* software described herein for any purpose. It is provided "as is"
* without express or implied warranty.
*
* The author of dmalloc may be contacted via https://dmalloc.com/
*/
/*
* Minimal Standard Pseudo-Random Number Generator
*
* Author: Fuat C. Baran, Columbia University, 1988
*
* Based on code in "Random Number Generators: Good Ones are Hard to
* Find", by Stephen K. Park and Keith W. Miller in Communications of
* the ACM, 31, 10 (Oct. 1988) pp. 1192-1201.
*
* Requirements: MAXINT must be 2 ^ 31 - 1 or larger
*
* Auto-seeding random number generator. Just start to call random
* and it will take care of seeding, etc.
*/
#include "dmalloc_rand.h"
#define MAGIC_A 16807 /* magic number */
#define MERSENNE_PRIME 2147483647UL /* mersenne prime 2^31 -1 */
#define MAGIC_QUOTIENT 127773 /* M div A (M / A) */
#define MAGIC_REMAINDER 2836 /* M mod A (M % A) */
/* local variables */
static long value = 0; /* our random value */
/*
* static void auto_seed
*
* Automatically seed the random number generation algorithm.
*/
static void auto_seed(void)
{
/* set the seed to a constant so we don't produce random addresses */
value = 0xDEADBEEF;
}
/*
* static void _dmalloc_srand
*
* Seed the random number generator with the user argument.
*
* ARGUMENTS:
*
* seed -> Value to seed the algorithm with.
*/
void _dmalloc_srand(const long seed)
{
value = seed;
}
/*
* static long _dmalloc_rand
*
* Get a pseudo-random number from the random algorithm.
*
* Returns a random number.
*/
long _dmalloc_rand(void)
{
if (value == 0) {
auto_seed();
}
/* do the magic seed calculation */
value = MAGIC_A * (value % MAGIC_QUOTIENT) -
MAGIC_REMAINDER * (value / MAGIC_QUOTIENT);
if (value <= 0) {
value += MERSENNE_PRIME;
}
return value;
}