Debian Codegraph @

src/main/org/h2/util/MathUtils.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.util;
7
8 import java.io.ByteArrayOutputStream;
9 import java.io.DataOutputStream;
10 import java.io.IOException;
11 import java.lang.reflect.Method;
12 import java.nio.charset.StandardCharsets;
13 import java.security.SecureRandom;
14 import java.util.concurrent.ThreadLocalRandom;
15
16 /**
17 * This is a utility class with mathematical helper functions.
18 */
19 public class MathUtils {
20
21 /**
22 * The secure random object.
23 */
24 static SecureRandom secureRandom;
25
26 /**
27 * True if the secure random object is seeded.
28 */
29 static volatile boolean seeded;
30
31 private MathUtils() {
32 // utility class
33 }
34
35
36 /**
37 * Round the value up to the next block size. The block size must be a power
38 * of two. As an example, using the block size of 8, the following rounding
39 * operations are done: 0 stays 0; values 1..8 results in 8, 9..16 results
40 * in 16, and so on.
41 *
42 * @param x the value to be rounded
43 * @param blockSizePowerOf2 the block size
44 * @return the rounded value
45 */
46 public static int roundUpInt(int x, int blockSizePowerOf2) {
47 return (x + blockSizePowerOf2 - 1) & -blockSizePowerOf2;
48 }
49
50 /**
51 * Round the value up to the next block size. The block size must be a power
52 * of two. As an example, using the block size of 8, the following rounding
53 * operations are done: 0 stays 0; values 1..8 results in 8, 9..16 results
54 * in 16, and so on.
55 *
56 * @param x the value to be rounded
57 * @param blockSizePowerOf2 the block size
58 * @return the rounded value
59 */
60 public static long roundUpLong(long x, long blockSizePowerOf2) {
61 return (x + blockSizePowerOf2 - 1) & -blockSizePowerOf2;
62 }
63
64 private static synchronized SecureRandom getSecureRandom() {
65 if (secureRandom != null) {
66 return secureRandom;
67 }
68 // Workaround for SecureRandom problem as described in
69 // https://bugs.openjdk.java.net/browse/JDK-6202721
70 // Can not do that in a static initializer block, because
71 // threads are not started until after the initializer block exits
72 try {
73 secureRandom = SecureRandom.getInstance("SHA1PRNG");
74 // On some systems, secureRandom.generateSeed() is very slow.
75 // In this case it is initialized using our own seed implementation
76 // and afterwards (in the thread) using the regular algorithm.
77 Runnable runnable = () -> {
78 try {
79 SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
80 byte[] seed = sr.generateSeed(20);
81 synchronized (secureRandom) {
82 secureRandom.setSeed(seed);
83 seeded = true;
84 }
85 } catch (Exception e) {
86 // NoSuchAlgorithmException
87 warn("SecureRandom", e);
88 }
89 };
90
91 try {
92 Thread t = new Thread(runnable, "Generate Seed");
93 // let the process terminate even if generating the seed is
94 // really slow
95 t.setDaemon(true);
96 t.start();
97 Thread.yield();
98 try {
99 // normally, generateSeed takes less than 200 ms
100 t.join(400);
101 } catch (InterruptedException e) {
102 warn("InterruptedException", e);
103 }
104 if (!seeded) {
105 byte[] seed = generateAlternativeSeed();
106 // this never reduces randomness
107 synchronized (secureRandom) {
108 secureRandom.setSeed(seed);
109 }
110 }
111 } catch (SecurityException e) {
112 // workaround for the Google App Engine: don't use a thread
113 runnable.run();
114 generateAlternativeSeed();
115 }
116
117 } catch (Exception e) {
118 // NoSuchAlgorithmException
119 warn("SecureRandom", e);
120 secureRandom = new SecureRandom();
121 }
122 return secureRandom;
123 }
124
125 /**
126 * Generate a seed value, using as much unpredictable data as possible.
127 *
128 * @return the seed
129 */
130 public static byte[] generateAlternativeSeed() {
131 try {
132 ByteArrayOutputStream bout = new ByteArrayOutputStream();
133 DataOutputStream out = new DataOutputStream(bout);
134
135 // milliseconds and nanoseconds
136 out.writeLong(System.currentTimeMillis());
137 out.writeLong(System.nanoTime());
138
139 // memory
140 out.writeInt(new Object().hashCode());
141 Runtime runtime = Runtime.getRuntime();
142 out.writeLong(runtime.freeMemory());
143 out.writeLong(runtime.maxMemory());
144 out.writeLong(runtime.totalMemory());
145
146 // environment
147 try {
148 String s = System.getProperties().toString();
149 // can't use writeUTF, as the string
150 // might be larger than 64 KB
151 out.writeInt(s.length());
152 out.write(s.getBytes(StandardCharsets.UTF_8));
153 } catch (Exception e) {
154 warn("generateAlternativeSeed", e);
155 }
156
157 // host name and ip addresses (if any)
158 try {
159 // workaround for the Google App Engine: don't use InetAddress
160 Class<?> inetAddressClass = Class.forName(
161 "java.net.InetAddress");
162 Object localHost = inetAddressClass.getMethod(
163 "getLocalHost").invoke(null);
164 String hostName = inetAddressClass.getMethod(
165 "getHostName").invoke(localHost).toString();
166 out.writeUTF(hostName);
167 Object[] list = (Object[]) inetAddressClass.getMethod(
168 "getAllByName", String.class).invoke(null, hostName);
169 Method getAddress = inetAddressClass.getMethod(
170 "getAddress");
171 for (Object o : list) {
172 out.write((byte[]) getAddress.invoke(o));
173 }
174 } catch (Throwable e) {
175 // on some system, InetAddress is not supported
176 // on some system, InetAddress.getLocalHost() doesn't work
177 // for some reason (incorrect configuration)
178 }
179
180 // timing (a second thread is already running usually)
181 for (int j = 0; j < 16; j++) {
182 int i = 0;
183 long end = System.currentTimeMillis();
184 while (end == System.currentTimeMillis()) {
185 i++;
186 }
187 out.writeInt(i);
188 }
189
190 out.close();
191 return bout.toByteArray();
192 } catch (IOException e) {
193 warn("generateAlternativeSeed", e);
194 return new byte[1];
195 }
196 }
197
198 /**
199 * Print a message to system output if there was a problem initializing the
200 * random number generator.
201 *
202 * @param s the message to print
203 * @param t the stack trace
204 */
205 static void warn(String s, Throwable t) {
206 // not a fatal problem, but maybe reduced security
207 System.out.println("Warning: " + s);
208 if (t != null) {
209 t.printStackTrace();
210 }
211 }
212
213 /**
214 * Get the value that is equal to or higher than this value, and that is a
215 * power of two.
216 *
217 * @param x the original value
218 * @return the next power of two value
219 * @throws IllegalArgumentException if x &lt; 0 or x &gt; 0x40000000
220 */
221 public static int nextPowerOf2(int x) throws IllegalArgumentException {
222 if (x + Integer.MIN_VALUE > (0x4000_0000 + Integer.MIN_VALUE)) {
223 throw new IllegalArgumentException("Argument out of range"
224 + " [0x0-0x40000000]. Argument was: " + x);
225 }
226 return x <= 1 ? 1 : (-1 >>> Integer.numberOfLeadingZeros(x - 1)) + 1;
227 }
228
229 /**
230 * Convert a long value to an int value. Values larger than the biggest int
231 * value are converted to the biggest int value, and values smaller than the
232 * smallest int value are converted to the smallest int value.
233 *
234 * @param l the value to convert
235 * @return the converted int value
236 */
237 public static int convertLongToInt(long l) {
238 if (l <= Integer.MIN_VALUE) {
239 return Integer.MIN_VALUE;
240 } else if (l >= Integer.MAX_VALUE) {
241 return Integer.MAX_VALUE;
242 } else {
243 return (int) l;
244 }
245 }
246
247 /**
248 * Convert an int value to a short value. Values larger than the biggest
249 * short value are converted to the biggest short value, and values smaller
250 * than the smallest short value are converted to the smallest short value.
251 *
252 * @param i the value to convert
253 * @return the converted short value
254 */
255 public static short convertIntToShort(int i) {
256 if (i <= Short.MIN_VALUE) {
257 return Short.MIN_VALUE;
258 } else if (i >= Short.MAX_VALUE) {
259 return Short.MAX_VALUE;
260 } else {
261 return (short) i;
262 }
263 }
264
265 /**
266 * Get a cryptographically secure pseudo random long value.
267 *
268 * @return the random long value
269 */
270 public static long secureRandomLong() {
271 return getSecureRandom().nextLong();
272 }
273
274 /**
275 * Get a number of pseudo random bytes.
276 *
277 * @param bytes the target array
278 */
279 public static void randomBytes(byte[] bytes) {
280 ThreadLocalRandom.current().nextBytes(bytes);
281 }
282
283 /**
284 * Get a number of cryptographically secure pseudo random bytes.
285 *
286 * @param len the number of bytes
287 * @return the random bytes
288 */
289 public static byte[] secureRandomBytes(int len) {
290 if (len <= 0) {
291 len = 1;
292 }
293 byte[] buff = new byte[len];
294 getSecureRandom().nextBytes(buff);
295 return buff;
296 }
297
298 /**
299 * Get a pseudo random int value between 0 (including and the given value
300 * (excluding). The value is not cryptographically secure.
301 *
302 * @param lowerThan the value returned will be lower than this value
303 * @return the random long value
304 */
305 public static int randomInt(int lowerThan) {
306 return ThreadLocalRandom.current().nextInt(lowerThan);
307 }
308
309 /**
310 * Get a cryptographically secure pseudo random int value between 0
311 * (including and the given value (excluding).
312 *
313 * @param lowerThan the value returned will be lower than this value
314 * @return the random long value
315 */
316 public static int secureRandomInt(int lowerThan) {
317 return getSecureRandom().nextInt(lowerThan);
318 }
319
320 }