Back to index

glibc  2.9
random.c
Go to the documentation of this file.
00001 /* Copyright (C) 1995 Free Software Foundation
00002 
00003    The GNU C Library is free software; you can redistribute it and/or
00004    modify it under the terms of the GNU Lesser General Public
00005    License as published by the Free Software Foundation; either
00006    version 2.1 of the License, or (at your option) any later version.
00007 
00008    The GNU C Library is distributed in the hope that it will be useful,
00009    but WITHOUT ANY WARRANTY; without even the implied warranty of
00010    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00011    Lesser General Public License for more details.
00012 
00013    You should have received a copy of the GNU Lesser General Public
00014    License along with the GNU C Library; if not, write to the Free
00015    Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
00016    02111-1307 USA.  */
00017 
00018 /*
00019  * This is derived from the Berkeley source:
00020  *     @(#)random.c  5.5 (Berkeley) 7/6/88
00021  * It was reworked for the GNU C Library by Roland McGrath.
00022  * Rewritten to use reentrant functions by Ulrich Drepper, 1995.
00023  */
00024 
00025 /*
00026    Copyright (C) 1983 Regents of the University of California.
00027    All rights reserved.
00028  
00029    Redistribution and use in source and binary forms, with or without
00030    modification, are permitted provided that the following conditions
00031    are met:
00032 
00033    1. Redistributions of source code must retain the above copyright
00034       notice, this list of conditions and the following disclaimer.
00035    2. Redistributions in binary form must reproduce the above copyright
00036       notice, this list of conditions and the following disclaimer in the
00037       documentation and/or other materials provided with the distribution.
00038    4. Neither the name of the University nor the names of its contributors
00039       may be used to endorse or promote products derived from this software
00040       without specific prior written permission.
00041    
00042    THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
00043    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
00044    IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
00045    ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
00046    FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
00047    DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
00048    OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
00049    HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
00050    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
00051    OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
00052    SUCH DAMAGE.*/
00053 
00054 #include <bits/libc-lock.h>
00055 #include <limits.h>
00056 #include <stddef.h>
00057 #include <stdlib.h>
00058 
00059 
00060 /* An improved random number generation package.  In addition to the standard
00061    rand()/srand() like interface, this package also has a special state info
00062    interface.  The initstate() routine is called with a seed, an array of
00063    bytes, and a count of how many bytes are being passed in; this array is
00064    then initialized to contain information for random number generation with
00065    that much state information.  Good sizes for the amount of state
00066    information are 32, 64, 128, and 256 bytes.  The state can be switched by
00067    calling the setstate() function with the same array as was initialized
00068    with initstate().  By default, the package runs with 128 bytes of state
00069    information and generates far better random numbers than a linear
00070    congruential generator.  If the amount of state information is less than
00071    32 bytes, a simple linear congruential R.N.G. is used.  Internally, the
00072    state information is treated as an array of longs; the zeroth element of
00073    the array is the type of R.N.G. being used (small integer); the remainder
00074    of the array is the state information for the R.N.G.  Thus, 32 bytes of
00075    state information will give 7 longs worth of state information, which will
00076    allow a degree seven polynomial.  (Note: The zeroth word of state
00077    information also has some other information stored in it; see setstate
00078    for details).  The random number generation technique is a linear feedback
00079    shift register approach, employing trinomials (since there are fewer terms
00080    to sum up that way).  In this approach, the least significant bit of all
00081    the numbers in the state table will act as a linear feedback shift register,
00082    and will have period 2^deg - 1 (where deg is the degree of the polynomial
00083    being used, assuming that the polynomial is irreducible and primitive).
00084    The higher order bits will have longer periods, since their values are
00085    also influenced by pseudo-random carries out of the lower bits.  The
00086    total period of the generator is approximately deg*(2**deg - 1); thus
00087    doubling the amount of state information has a vast influence on the
00088    period of the generator.  Note: The deg*(2**deg - 1) is an approximation
00089    only good for large deg, when the period of the shift register is the
00090    dominant factor.  With deg equal to seven, the period is actually much
00091    longer than the 7*(2**7 - 1) predicted by this formula.  */
00092 
00093 
00094 
00095 /* For each of the currently supported random number generators, we have a
00096    break value on the amount of state information (you need at least this many
00097    bytes of state info to support this random number generator), a degree for
00098    the polynomial (actually a trinomial) that the R.N.G. is based on, and
00099    separation between the two lower order coefficients of the trinomial.  */
00100 
00101 /* Linear congruential.  */
00102 #define       TYPE_0        0
00103 #define       BREAK_0              8
00104 #define       DEG_0         0
00105 #define       SEP_0         0
00106 
00107 /* x**7 + x**3 + 1.  */
00108 #define       TYPE_1        1
00109 #define       BREAK_1              32
00110 #define       DEG_1         7
00111 #define       SEP_1         3
00112 
00113 /* x**15 + x + 1.  */
00114 #define       TYPE_2        2
00115 #define       BREAK_2              64
00116 #define       DEG_2         15
00117 #define       SEP_2         1
00118 
00119 /* x**31 + x**3 + 1.  */
00120 #define       TYPE_3        3
00121 #define       BREAK_3              128
00122 #define       DEG_3         31
00123 #define       SEP_3         3
00124 
00125 /* x**63 + x + 1.  */
00126 #define       TYPE_4        4
00127 #define       BREAK_4              256
00128 #define       DEG_4         63
00129 #define       SEP_4         1
00130 
00131 
00132 /* Array versions of the above information to make code run faster.
00133    Relies on fact that TYPE_i == i.  */
00134 
00135 #define       MAX_TYPES     5      /* Max number of types above.  */
00136 
00137 
00138 /* Initially, everything is set up as if from:
00139        initstate(1, randtbl, 128);
00140    Note that this initialization takes advantage of the fact that srandom
00141    advances the front and rear pointers 10*rand_deg times, and hence the
00142    rear pointer which starts at 0 will also end up at zero; thus the zeroth
00143    element of the state information, which contains info about the current
00144    position of the rear pointer is just
00145        (MAX_TYPES * (rptr - state)) + TYPE_3 == TYPE_3.  */
00146 
00147 static int32_t randtbl[DEG_3 + 1] =
00148   {
00149     TYPE_3,
00150 
00151     -1726662223, 379960547, 1735697613, 1040273694, 1313901226,
00152     1627687941, -179304937, -2073333483, 1780058412, -1989503057,
00153     -615974602, 344556628, 939512070, -1249116260, 1507946756,
00154     -812545463, 154635395, 1388815473, -1926676823, 525320961,
00155     -1009028674, 968117788, -123449607, 1284210865, 435012392,
00156     -2017506339, -911064859, -370259173, 1132637927, 1398500161,
00157     -205601318,
00158   };
00159 
00160 
00161 static struct random_data unsafe_state =
00162   {
00163 /* FPTR and RPTR are two pointers into the state info, a front and a rear
00164    pointer.  These two pointers are always rand_sep places aparts, as they
00165    cycle through the state information.  (Yes, this does mean we could get
00166    away with just one pointer, but the code for random is more efficient
00167    this way).  The pointers are left positioned as they would be from the call:
00168        initstate(1, randtbl, 128);
00169    (The position of the rear pointer, rptr, is really 0 (as explained above
00170    in the initialization of randtbl) because the state table pointer is set
00171    to point to randtbl[1] (as explained below).)  */
00172 
00173     .fptr = &randtbl[SEP_3 + 1],
00174     .rptr = &randtbl[1],
00175 
00176 /* The following things are the pointer to the state information table,
00177    the type of the current generator, the degree of the current polynomial
00178    being used, and the separation between the two pointers.
00179    Note that for efficiency of random, we remember the first location of
00180    the state information, not the zeroth.  Hence it is valid to access
00181    state[-1], which is used to store the type of the R.N.G.
00182    Also, we remember the last location, since this is more efficient than
00183    indexing every time to find the address of the last element to see if
00184    the front and rear pointers have wrapped.  */
00185 
00186     .state = &randtbl[1],
00187 
00188     .rand_type = TYPE_3,
00189     .rand_deg = DEG_3,
00190     .rand_sep = SEP_3,
00191 
00192     .end_ptr = &randtbl[sizeof (randtbl) / sizeof (randtbl[0])]
00193 };
00194 
00195 /* POSIX.1c requires that there is mutual exclusion for the `rand' and
00196    `srand' functions to prevent concurrent calls from modifying common
00197    data.  */
00198 __libc_lock_define_initialized (static, lock)
00199 
00200 /* Initialize the random number generator based on the given seed.  If the
00201    type is the trivial no-state-information type, just remember the seed.
00202    Otherwise, initializes state[] based on the given "seed" via a linear
00203    congruential generator.  Then, the pointers are set to known locations
00204    that are exactly rand_sep places apart.  Lastly, it cycles the state
00205    information a given number of times to get rid of any initial dependencies
00206    introduced by the L.C.R.N.G.  Note that the initialization of randtbl[]
00207    for default usage relies on values produced by this routine.  */
00208 void
00209 __srandom (x)
00210      unsigned int x;
00211 {
00212   __libc_lock_lock (lock);
00213   (void) __srandom_r (x, &unsafe_state);
00214   __libc_lock_unlock (lock);
00215 }
00216 
00217 weak_alias (__srandom, srandom)
00218 weak_alias (__srandom, srand)
00219 
00220 /* Initialize the state information in the given array of N bytes for
00221    future random number generation.  Based on the number of bytes we
00222    are given, and the break values for the different R.N.G.'s, we choose
00223    the best (largest) one we can and set things up for it.  srandom is
00224    then called to initialize the state information.  Note that on return
00225    from srandom, we set state[-1] to be the type multiplexed with the current
00226    value of the rear pointer; this is so successive calls to initstate won't
00227    lose this information and will be able to restart with setstate.
00228    Note: The first thing we do is save the current state, if any, just like
00229    setstate so that it doesn't matter when initstate is called.
00230    Returns a pointer to the old state.  */
00231 char *
00232 __initstate (seed, arg_state, n)
00233      unsigned int seed;
00234      char *arg_state;
00235      size_t n;
00236 {
00237   int32_t *ostate;
00238 
00239   __libc_lock_lock (lock);
00240 
00241   ostate = &unsafe_state.state[-1];
00242 
00243   __initstate_r (seed, arg_state, n, &unsafe_state);
00244 
00245   __libc_lock_unlock (lock);
00246 
00247   return (char *) ostate;
00248 }
00249 
00250 weak_alias (__initstate, initstate)
00251 
00252 /* Restore the state from the given state array.
00253    Note: It is important that we also remember the locations of the pointers
00254    in the current state information, and restore the locations of the pointers
00255    from the old state information.  This is done by multiplexing the pointer
00256    location into the zeroth word of the state information. Note that due
00257    to the order in which things are done, it is OK to call setstate with the
00258    same state as the current state
00259    Returns a pointer to the old state information.  */
00260 char *
00261 __setstate (arg_state)
00262      char *arg_state;
00263 {
00264   int32_t *ostate;
00265 
00266   __libc_lock_lock (lock);
00267 
00268   ostate = &unsafe_state.state[-1];
00269 
00270   if (__setstate_r (arg_state, &unsafe_state) < 0)
00271     ostate = NULL;
00272 
00273   __libc_lock_unlock (lock);
00274 
00275   return (char *) ostate;
00276 }
00277 
00278 weak_alias (__setstate, setstate)
00279 
00280 /* If we are using the trivial TYPE_0 R.N.G., just do the old linear
00281    congruential bit.  Otherwise, we do our fancy trinomial stuff, which is the
00282    same in all the other cases due to all the global variables that have been
00283    set up.  The basic operation is to add the number at the rear pointer into
00284    the one at the front pointer.  Then both pointers are advanced to the next
00285    location cyclically in the table.  The value returned is the sum generated,
00286    reduced to 31 bits by throwing away the "least random" low bit.
00287    Note: The code takes advantage of the fact that both the front and
00288    rear pointers can't wrap on the same call by not testing the rear
00289    pointer if the front one has wrapped.  Returns a 31-bit random number.  */
00290 
00291 long int
00292 __random ()
00293 {
00294   int32_t retval;
00295 
00296   __libc_lock_lock (lock);
00297 
00298   (void) __random_r (&unsafe_state, &retval);
00299 
00300   __libc_lock_unlock (lock);
00301 
00302   return retval;
00303 }
00304 
00305 weak_alias (__random, random)