aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/com/code_intelligence/jazzer/mutation/engine/SeededPseudoRandom.java
blob: 515f345bbcfeebe62823e4212b347b85f0997ae6 (plain)
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
/*
 * Copyright 2023 Code Intelligence GmbH
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.code_intelligence.jazzer.mutation.engine;

import static com.code_intelligence.jazzer.mutation.support.Preconditions.require;

import com.code_intelligence.jazzer.mutation.api.PseudoRandom;
import com.code_intelligence.jazzer.mutation.support.Preconditions;
import com.code_intelligence.jazzer.mutation.support.RandomSupport;
import java.util.List;
import java.util.SplittableRandom;
import java.util.function.Supplier;

public final class SeededPseudoRandom implements PseudoRandom {
  // We use SplittableRandom instead of Random since it doesn't incur unnecessary synchronization
  // overhead and uses a much better RNG under the hood that can generate all long values.
  private final SplittableRandom random;

  public SeededPseudoRandom(long seed) {
    this.random = new SplittableRandom(seed);
  }

  @Override
  public boolean choice() {
    return random.nextBoolean();
  }

  @Override
  public boolean trueInOneOutOf(int inverseFrequencyTrue) {
    // Ensure that the outcome of the choice isn't fixed.
    require(inverseFrequencyTrue >= 2);
    return indexIn(inverseFrequencyTrue) == 0;
  }

  @Override
  public <T> T pickIn(T[] array) {
    return array[indexIn(array.length)];
  }

  @Override
  public <T> T pickIn(List<T> list) {
    return list.get(indexIn(list.size()));
  }

  @Override
  public <T> int indexIn(T[] array) {
    return indexIn(array.length);
  }

  @Override
  public <T> int indexIn(List<T> list) {
    return indexIn(list.size());
  }

  @Override
  public int indexIn(int range) {
    require(range >= 1);
    // TODO: Replace random.nextInt(length) with the fast version of
    //  https://lemire.me/blog/2016/06/30/fast-random-shuffling/, which avoids a modulo operation.
    //  It's slightly more biased for large bounds, but indices and choices tend to be small and
    //  are generated frequently (e.g. when picking a submutator).
    return random.nextInt(range);
  }

  @Override
  public <T> int otherIndexIn(T[] array, int currentIndex) {
    return otherIndexIn(array.length, currentIndex);
  }

  @Override
  public int otherIndexIn(int range, int currentIndex) {
    int otherIndex = currentIndex + closedRange(1, range - 1);
    if (otherIndex < range) {
      return otherIndex;
    } else {
      return otherIndex - range;
    }
  }

  @Override
  public int closedRange(int lowerInclusive, int upperInclusive) {
    require(lowerInclusive <= upperInclusive);
    int range = upperInclusive - lowerInclusive + 1;
    if (range > 0) {
      return lowerInclusive + random.nextInt(range);
    } else {
      // The interval [lowerInclusive, upperInclusive] covers at least half of the
      // [Integer.MIN_VALUE, Integer.MAX_VALUE] range, fall back to rejection sampling with an
      // expected number of samples <= 2.
      int r;
      do {
        r = random.nextInt();
      } while (r < lowerInclusive);
      return r;
    }
  }

  @Override
  public long closedRange(long lowerInclusive, long upperInclusive) {
    require(lowerInclusive <= upperInclusive);
    if (upperInclusive < Long.MAX_VALUE) {
      // upperInclusive + 1 <= Long.MAX_VALUE
      return random.nextLong(lowerInclusive, upperInclusive + 1);
    } else if (lowerInclusive > 0) {
      // upperInclusive + 1 - lowerInclusive <= Long.MAX_VALUE
      return lowerInclusive + random.nextLong(upperInclusive + 1 - lowerInclusive);
    } else {
      // The interval [lowerInclusive, Long.MAX_VALUE] covers at least half of the
      // [Long.MIN_VALUE, Long.MAX_VALUE] range, fall back to rejection sampling with an expected
      // number of samples <= 2.
      long r;
      do {
        r = random.nextLong();
      } while (r < lowerInclusive);
      return r;
    }
  }

  // This function always returns a finite value
  @Override
  public float closedRange(float lowerInclusive, float upperInclusive) {
    require(lowerInclusive <= upperInclusive);
    if (lowerInclusive == upperInclusive) {
      require(Double.isFinite(lowerInclusive));
      return lowerInclusive;
    }
    // Special case: [Float.NEGATIVE_INFINITY, -Float.MAX_VALUE]
    if (lowerInclusive == Float.NEGATIVE_INFINITY && upperInclusive == -Float.MAX_VALUE)
      return -Float.MAX_VALUE;
    // Special case: [Float.MAX_VALUE, Float.POSITIVE_INFINITY]
    if (lowerInclusive == Float.MAX_VALUE && upperInclusive == Float.POSITIVE_INFINITY)
      return Float.MAX_VALUE;
    float limitedLower =
        lowerInclusive == Float.NEGATIVE_INFINITY ? -Float.MAX_VALUE : lowerInclusive;
    float limitedUpper =
        upperInclusive == Float.POSITIVE_INFINITY ? Float.MAX_VALUE : upperInclusive;

    // nextDouble(start, bound) is exclusive of bound, so we use Math.nextUp to extend the bound to
    // the next representable double. The maximal possible range of a float is always finite when
    // represented as a double. Therefore, we can safely use nextDouble and convert it to a float.
    return (float) random.nextDouble((double) limitedLower, Math.nextUp((double) limitedUpper));
  }

  // This function always returns a finite value
  @Override
  public double closedRange(double lowerInclusive, double upperInclusive) {
    require(lowerInclusive <= upperInclusive);
    if (lowerInclusive == upperInclusive) {
      require(Double.isFinite(lowerInclusive));
      return lowerInclusive;
    }
    // Special case: [Double.NEGATIVE_INFINITY, -Double.MAX_VALUE]
    if (lowerInclusive == Double.NEGATIVE_INFINITY && upperInclusive == -Double.MAX_VALUE)
      return -Double.MAX_VALUE;
    // Special case: [Double.MAX_VALUE, Double.POSITIVE_INFINITY)
    if (lowerInclusive == Double.MAX_VALUE && upperInclusive == Double.POSITIVE_INFINITY)
      return Double.MAX_VALUE;

    // nextDouble(start, bound) cannot deal with infinite values, so we need to limit them
    double limitedLower =
        lowerInclusive == Double.NEGATIVE_INFINITY ? -Double.MAX_VALUE : lowerInclusive;
    double limitedUpper =
        upperInclusive == Double.POSITIVE_INFINITY ? Double.MAX_VALUE : upperInclusive;

    // After limiting, the range may contain only a single value: return that
    if (limitedLower == limitedUpper)
      return limitedLower;

    // random.nextDouble() is exclusive of the upper bound. To include the upper bound,
    // we extend the bound to the next double value by using Math.nextUp(limitedUpper).
    double nextUpper =
        (limitedUpper == Double.MAX_VALUE) ? limitedUpper : Math.nextUp(limitedUpper);

    // This, however, leads to a problem when the upper bound is Double.MAX_VALUE, because the next
    // double after that is Double.POSITIVE_INFINITY. This case is treated the same as infinite
    // range case, in the else branch.
    boolean couldExtendRange = nextUpper != limitedUpper;

    // nextDouble(start, bound) can only deal with finite ranges
    if (Double.isFinite(nextUpper - limitedLower) && couldExtendRange) {
      double result = random.nextDouble(limitedLower, nextUpper);
      // Clamp random.nextDouble() to the upper bound.
      // This is a workaround for RandomSupport.nextDouble() that causes it to
      // return values greater than upper bound.
      // See https://bugs.openjdk.org/browse/JDK-8281183 for a list of affected JDK versions.
      if (result > limitedUpper)
        result = limitedUpper;
      return result;
    } else {
      // Ranges that exceeds the maximum representable double value, or ranges that could not be
      // extended scale a random n from range [0; 1] onto the range [limitLower, limitUpper]
      // limitedLower * (1 - n) + limitedUpper * n            - is the same as:
      // limitedLower + (limitedUpper - limitedLower) * n
      // limitedLower + range * n
      double n = random.nextDouble(0.0, Math.nextUp(1.0));
      return limitedLower * (1 - n) + limitedUpper * n;
    }
  }

  @Override
  public void bytes(byte[] bytes) {
    RandomSupport.nextBytes(random, bytes);
  }

  @Override
  public int closedRangeBiasedTowardsSmall(int upperInclusive) {
    if (upperInclusive == 0) {
      return 0;
    }
    Preconditions.require(upperInclusive > 0);
    // Modified from (Apache-2.0)
    // https://github.com/abseil/abseil-cpp/blob/2927340217c37328319b5869285a6dcdbc13e7a7/absl/random/zipf_distribution.h
    // by inlining the values v = 1 and q = 2.
    final double kd = upperInclusive;
    final double hxm = zipf_h(kd + 0.5);
    final double h0x5 = -1.0 / 1.5;
    final double elogv_q = 1.0;
    final double hx0_minus_hxm = (h0x5 - elogv_q) - hxm;
    final double s = 0.46153846153846123;
    double k;
    while (true) {
      final double v = random.nextDouble();
      final double u = hxm + v * hx0_minus_hxm;
      final double x = zipf_hinv(u);
      k = Math.floor(x + 0.5);
      if (k > kd) {
        continue;
      }
      if (k - x <= s) {
        break;
      }
      final double h = zipf_h(k + 0.5);
      final double r = zipf_pow_negative_q(1.0 + k);
      if (u >= h - r) {
        break;
      }
    }
    return (int) k;
  }

  @Override
  public int closedRangeBiasedTowardsSmall(int lowerInclusive, int upperInclusive) {
    return lowerInclusive + closedRangeBiasedTowardsSmall(upperInclusive - lowerInclusive);
  }

  private static double zipf_h(double x) {
    return -1.0 / (x + 1.0);
  }

  private static double zipf_hinv(double x) {
    return -1.0 + -1.0 / x;
  }

  private static double zipf_pow_negative_q(double x) {
    return 1.0 / (x * x);
  }

  @Override
  public <T> T pickValue(
      T value, T otherValue, Supplier<T> supplier, int inverseSupplierFrequency) {
    if (trueInOneOutOf(inverseSupplierFrequency)) {
      return supplier.get();
    } else if (choice()) {
      return value;
    } else {
      return otherValue;
    }
  }

  @Override
  public long nextLong() {
    return random.nextLong();
  }
}