View Javadoc
1   /*
2    * Copyright 2012 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.util.internal;
17  
18  import io.netty.util.internal.logging.InternalLogger;
19  import io.netty.util.internal.logging.InternalLoggerFactory;
20  import org.jctools.queues.MpmcArrayQueue;
21  import org.jctools.queues.MpscArrayQueue;
22  import org.jctools.queues.MpscChunkedArrayQueue;
23  import org.jctools.queues.MpscUnboundedArrayQueue;
24  import org.jctools.queues.SpscLinkedQueue;
25  import org.jctools.queues.atomic.MpmcAtomicArrayQueue;
26  import org.jctools.queues.atomic.MpscAtomicArrayQueue;
27  import org.jctools.queues.atomic.MpscChunkedAtomicArrayQueue;
28  import org.jctools.queues.atomic.MpscUnboundedAtomicArrayQueue;
29  import org.jctools.queues.atomic.SpscLinkedAtomicQueue;
30  import org.jctools.queues.atomic.unpadded.MpscAtomicUnpaddedArrayQueue;
31  import org.jctools.queues.unpadded.MpscUnpaddedArrayQueue;
32  import org.jctools.util.Pow2;
33  import org.jctools.util.UnsafeAccess;
34  
35  import java.io.BufferedReader;
36  import java.io.File;
37  import java.io.IOException;
38  import java.io.InputStreamReader;
39  import java.lang.invoke.MethodHandle;
40  import java.lang.invoke.MethodHandles;
41  import java.lang.reflect.Field;
42  import java.nio.ByteBuffer;
43  import java.nio.ByteOrder;
44  import java.nio.charset.StandardCharsets;
45  import java.nio.file.Files;
46  import java.nio.file.Path;
47  import java.nio.file.Paths;
48  import java.security.AccessController;
49  import java.security.PrivilegedAction;
50  import java.util.Arrays;
51  import java.util.Collections;
52  import java.util.Deque;
53  import java.util.HashSet;
54  import java.util.LinkedHashSet;
55  import java.util.List;
56  import java.util.Locale;
57  import java.util.Map;
58  import java.util.Queue;
59  import java.util.Random;
60  import java.util.Set;
61  import java.util.concurrent.ConcurrentHashMap;
62  import java.util.concurrent.ConcurrentLinkedDeque;
63  import java.util.concurrent.ConcurrentMap;
64  import java.util.concurrent.ThreadLocalRandom;
65  import java.util.concurrent.atomic.AtomicLong;
66  import java.util.regex.Matcher;
67  import java.util.regex.Pattern;
68  
69  import static io.netty.util.internal.PlatformDependent0.HASH_CODE_ASCII_SEED;
70  import static io.netty.util.internal.PlatformDependent0.HASH_CODE_C1;
71  import static io.netty.util.internal.PlatformDependent0.HASH_CODE_C2;
72  import static io.netty.util.internal.PlatformDependent0.hashCodeAsciiSanitize;
73  import static io.netty.util.internal.PlatformDependent0.unalignedAccess;
74  import static java.lang.Math.max;
75  import static java.lang.Math.min;
76  import static java.lang.invoke.MethodType.methodType;
77  
78  /**
79   * Utility that detects various properties specific to the current runtime
80   * environment, such as Java version and the availability of the
81   * {@code sun.misc.Unsafe} object.
82   * <p>
83   * You can disable the use of {@code sun.misc.Unsafe} if you specify
84   * the system property <strong>io.netty.noUnsafe</strong>.
85   */
86  public final class PlatformDependent {
87  
88      private static final InternalLogger logger = InternalLoggerFactory.getInstance(PlatformDependent.class);
89  
90      private static Pattern MAX_DIRECT_MEMORY_SIZE_ARG_PATTERN;
91      private static final boolean MAYBE_SUPER_USER;
92  
93      private static final boolean CAN_ENABLE_TCP_NODELAY_BY_DEFAULT = !isAndroid();
94  
95      private static final Throwable UNSAFE_UNAVAILABILITY_CAUSE = unsafeUnavailabilityCause0();
96      private static final boolean DIRECT_BUFFER_PREFERRED;
97      private static final long MAX_DIRECT_MEMORY = estimateMaxDirectMemory();
98  
99      private static final int MPSC_CHUNK_SIZE =  1024;
100     private static final int MIN_MAX_MPSC_CAPACITY =  MPSC_CHUNK_SIZE * 2;
101     private static final int MAX_ALLOWED_MPSC_CAPACITY = Pow2.MAX_POW2;
102 
103     private static final long BYTE_ARRAY_BASE_OFFSET = byteArrayBaseOffset0();
104 
105     private static final File TMPDIR = tmpdir0();
106 
107     private static final int BIT_MODE = bitMode0();
108     private static final String NORMALIZED_ARCH = normalizeArch(SystemPropertyUtil.get("os.arch", ""));
109     private static final String NORMALIZED_OS = normalizeOs(SystemPropertyUtil.get("os.name", ""));
110 
111     // keep in sync with maven's pom.xml via os.detection.classifierWithLikes!
112     private static final String[] ALLOWED_LINUX_OS_CLASSIFIERS = {"fedora", "suse", "arch"};
113     private static final Set<String> LINUX_OS_CLASSIFIERS;
114 
115     private static final boolean IS_WINDOWS = isWindows0();
116     private static final boolean IS_OSX = isOsx0();
117     private static final boolean IS_J9_JVM = isJ9Jvm0();
118     private static final boolean IS_IVKVM_DOT_NET = isIkvmDotNet0();
119 
120     private static final int ADDRESS_SIZE = addressSize0();
121     private static final boolean USE_DIRECT_BUFFER_NO_CLEANER;
122     private static final AtomicLong DIRECT_MEMORY_COUNTER;
123     private static final long DIRECT_MEMORY_LIMIT;
124     private static final Cleaner CLEANER;
125     private static final boolean HAS_ALLOCATE_UNINIT_ARRAY;
126     // For specifications, see https://www.freedesktop.org/software/systemd/man/os-release.html
127     private static final String[] OS_RELEASE_FILES = {"/etc/os-release", "/usr/lib/os-release"};
128     private static final String LINUX_ID_PREFIX = "ID=";
129     private static final String LINUX_ID_LIKE_PREFIX = "ID_LIKE=";
130     public static final boolean BIG_ENDIAN_NATIVE_ORDER = ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN;
131 
132     private static final Cleaner NOOP = new Cleaner() {
133         @Override
134         public void freeDirectBuffer(ByteBuffer buffer) {
135             // NOOP
136         }
137     };
138 
139     static {
140         // Here is how the system property is used:
141         //
142         // * <  0  - Don't use cleaner, and inherit max direct memory from java. In this case the
143         //           "practical max direct memory" would be 2 * max memory as defined by the JDK.
144         // * == 0  - Use cleaner, Netty will not enforce max memory, and instead will defer to JDK.
145         // * >  0  - Don't use cleaner. This will limit Netty's total direct memory
146         //           (note: that JDK's direct memory limit is independent of this).
147         long maxDirectMemory = SystemPropertyUtil.getLong("io.netty.maxDirectMemory", -1);
148 
149         if (maxDirectMemory == 0 || !hasUnsafe() || !PlatformDependent0.hasDirectBufferNoCleanerConstructor()) {
150             USE_DIRECT_BUFFER_NO_CLEANER = false;
151             DIRECT_MEMORY_COUNTER = null;
152         } else {
153             USE_DIRECT_BUFFER_NO_CLEANER = true;
154             if (maxDirectMemory < 0) {
155                 maxDirectMemory = MAX_DIRECT_MEMORY;
156                 if (maxDirectMemory <= 0) {
157                     DIRECT_MEMORY_COUNTER = null;
158                 } else {
159                     DIRECT_MEMORY_COUNTER = new AtomicLong();
160                 }
161             } else {
162                 DIRECT_MEMORY_COUNTER = new AtomicLong();
163             }
164         }
165         logger.debug("-Dio.netty.maxDirectMemory: {} bytes", maxDirectMemory);
166         DIRECT_MEMORY_LIMIT = maxDirectMemory >= 1 ? maxDirectMemory : MAX_DIRECT_MEMORY;
167         HAS_ALLOCATE_UNINIT_ARRAY = javaVersion() >= 9 && PlatformDependent0.hasAllocateArrayMethod();
168 
169         MAYBE_SUPER_USER = maybeSuperUser0();
170 
171         if (!isAndroid()) {
172             // only direct to method if we are not running on android.
173             // See https://github.com/netty/netty/issues/2604
174             if (javaVersion() >= 9) {
175                 CLEANER = CleanerJava9.isSupported() ? new CleanerJava9() : NOOP;
176             } else {
177                 CLEANER = CleanerJava6.isSupported() ? new CleanerJava6() : NOOP;
178             }
179         } else {
180             CLEANER = NOOP;
181         }
182 
183         // We should always prefer direct buffers by default if we can use a Cleaner to release direct buffers.
184         DIRECT_BUFFER_PREFERRED = CLEANER != NOOP
185                                   && !SystemPropertyUtil.getBoolean("io.netty.noPreferDirect", false);
186         if (logger.isDebugEnabled()) {
187             logger.debug("-Dio.netty.noPreferDirect: {}", !DIRECT_BUFFER_PREFERRED);
188         }
189 
190         /*
191          * We do not want to log this message if unsafe is explicitly disabled. Do not remove the explicit no unsafe
192          * guard.
193          */
194         if (CLEANER == NOOP && !PlatformDependent0.isExplicitNoUnsafe()) {
195             logger.info(
196                     "Your platform does not provide complete low-level API for accessing direct buffers reliably. " +
197                     "Unless explicitly requested, heap buffer will always be preferred to avoid potential system " +
198                     "instability.");
199         }
200 
201         final Set<String> allowedClassifiers = Collections.unmodifiableSet(
202                 new HashSet<String>(Arrays.asList(ALLOWED_LINUX_OS_CLASSIFIERS)));
203         final Set<String> availableClassifiers = new LinkedHashSet<String>();
204 
205         if (!addPropertyOsClassifiers(allowedClassifiers, availableClassifiers)) {
206             addFilesystemOsClassifiers(allowedClassifiers, availableClassifiers);
207         }
208         LINUX_OS_CLASSIFIERS = Collections.unmodifiableSet(availableClassifiers);
209     }
210 
211     static void addFilesystemOsClassifiers(final Set<String> allowedClassifiers,
212                                            final Set<String> availableClassifiers) {
213         for (final String osReleaseFileName : OS_RELEASE_FILES) {
214             final Path file = Paths.get(osReleaseFileName);
215             boolean found = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
216                 @Override
217                 public Boolean run() {
218                     Pattern lineSplitPattern = Pattern.compile("[ ]+");
219                     try {
220                         if (Files.exists(file)) {
221                             BufferedReader reader = null;
222                             try {
223                                 reader = new BufferedReader(new InputStreamReader(
224                                         new BoundedInputStream(Files.newInputStream(file)), StandardCharsets.UTF_8));
225 
226                                 String line;
227                                 while ((line = reader.readLine()) != null) {
228                                     if (line.startsWith(LINUX_ID_PREFIX)) {
229                                         String id = normalizeOsReleaseVariableValue(
230                                                 line.substring(LINUX_ID_PREFIX.length()));
231                                         addClassifier(allowedClassifiers, availableClassifiers, id);
232                                     } else if (line.startsWith(LINUX_ID_LIKE_PREFIX)) {
233                                         line = normalizeOsReleaseVariableValue(
234                                                 line.substring(LINUX_ID_LIKE_PREFIX.length()));
235                                         addClassifier(allowedClassifiers, availableClassifiers,
236                                                 lineSplitPattern.split(line));
237                                     }
238                                 }
239                             } catch (SecurityException e) {
240                                 logger.debug("Unable to read {}", osReleaseFileName, e);
241                             } catch (IOException e) {
242                                 logger.debug("Error while reading content of {}", osReleaseFileName, e);
243                             }
244                             // specification states we should only fall back if /etc/os-release does not exist
245                             return true;
246                         }
247                     } catch (SecurityException e) {
248                         logger.debug("Unable to check if {} exists", osReleaseFileName, e);
249                     }
250                     return false;
251                 }
252             });
253 
254             if (found) {
255                 break;
256             }
257         }
258     }
259 
260     static boolean addPropertyOsClassifiers(Set<String> allowedClassifiers, Set<String> availableClassifiers) {
261         // empty: -Dio.netty.osClassifiers (no distro specific classifiers for native libs)
262         // single ID: -Dio.netty.osClassifiers=ubuntu
263         // pair ID, ID_LIKE: -Dio.netty.osClassifiers=ubuntu,debian
264         // illegal otherwise
265         String osClassifiersPropertyName = "io.netty.osClassifiers";
266         String osClassifiers = SystemPropertyUtil.get(osClassifiersPropertyName);
267         if (osClassifiers == null) {
268             return false;
269         }
270         if (osClassifiers.isEmpty()) {
271             // let users omit classifiers with just -Dio.netty.osClassifiers
272             return true;
273         }
274         String[] classifiers = osClassifiers.split(",");
275         if (classifiers.length == 0) {
276             throw new IllegalArgumentException(
277                     osClassifiersPropertyName + " property is not empty, but contains no classifiers: "
278                             + osClassifiers);
279         }
280         // at most ID, ID_LIKE classifiers
281         if (classifiers.length > 2) {
282             throw new IllegalArgumentException(
283                     osClassifiersPropertyName + " property contains more than 2 classifiers: " + osClassifiers);
284         }
285         for (String classifier : classifiers) {
286             addClassifier(allowedClassifiers, availableClassifiers, classifier);
287         }
288         return true;
289     }
290 
291     public static long byteArrayBaseOffset() {
292         return BYTE_ARRAY_BASE_OFFSET;
293     }
294 
295     public static boolean hasDirectBufferNoCleanerConstructor() {
296         return PlatformDependent0.hasDirectBufferNoCleanerConstructor();
297     }
298 
299     public static byte[] allocateUninitializedArray(int size) {
300         return HAS_ALLOCATE_UNINIT_ARRAY ?  PlatformDependent0.allocateUninitializedArray(size) : new byte[size];
301     }
302 
303     /**
304      * Returns {@code true} if and only if the current platform is Android
305      */
306     public static boolean isAndroid() {
307         return PlatformDependent0.isAndroid();
308     }
309 
310     /**
311      * Return {@code true} if the JVM is running on Windows
312      */
313     public static boolean isWindows() {
314         return IS_WINDOWS;
315     }
316 
317     /**
318      * Return {@code true} if the JVM is running on OSX / MacOS
319      */
320     public static boolean isOsx() {
321         return IS_OSX;
322     }
323 
324     /**
325      * Return {@code true} if the current user may be a super-user. Be aware that this is just an hint and so it may
326      * return false-positives.
327      */
328     public static boolean maybeSuperUser() {
329         return MAYBE_SUPER_USER;
330     }
331 
332     /**
333      * Return the version of Java under which this library is used.
334      */
335     public static int javaVersion() {
336         return PlatformDependent0.javaVersion();
337     }
338 
339     /**
340      * @param thread The thread to be checked.
341      * @return {@code true} if this {@link Thread} is a virtual thread, {@code false} otherwise.
342      */
343     public static boolean isVirtualThread(Thread thread) {
344         return PlatformDependent0.isVirtualThread(thread);
345     }
346 
347     /**
348      * Returns {@code true} if and only if it is fine to enable TCP_NODELAY socket option by default.
349      */
350     public static boolean canEnableTcpNoDelayByDefault() {
351         return CAN_ENABLE_TCP_NODELAY_BY_DEFAULT;
352     }
353 
354     /**
355      * Return {@code true} if {@code sun.misc.Unsafe} was found on the classpath and can be used for accelerated
356      * direct memory access.
357      */
358     public static boolean hasUnsafe() {
359         return UNSAFE_UNAVAILABILITY_CAUSE == null;
360     }
361 
362     /**
363      * Return the reason (if any) why {@code sun.misc.Unsafe} was not available.
364      */
365     public static Throwable getUnsafeUnavailabilityCause() {
366         return UNSAFE_UNAVAILABILITY_CAUSE;
367     }
368 
369     /**
370      * {@code true} if and only if the platform supports unaligned access.
371      *
372      * @see <a href="https://en.wikipedia.org/wiki/Segmentation_fault#Bus_error">Wikipedia on segfault</a>
373      */
374     public static boolean isUnaligned() {
375         return PlatformDependent0.isUnaligned();
376     }
377 
378     /**
379      * Returns {@code true} if the platform has reliable low-level direct buffer access API and a user has not specified
380      * {@code -Dio.netty.noPreferDirect} option.
381      */
382     public static boolean directBufferPreferred() {
383         return DIRECT_BUFFER_PREFERRED;
384     }
385 
386     /**
387      * Returns the maximum memory reserved for direct buffer allocation.
388      */
389     public static long maxDirectMemory() {
390         return DIRECT_MEMORY_LIMIT;
391     }
392 
393     /**
394      * Returns the current memory reserved for direct buffer allocation.
395      * This method returns -1 in case that a value is not available.
396      *
397      * @see #maxDirectMemory()
398      */
399     public static long usedDirectMemory() {
400         return DIRECT_MEMORY_COUNTER != null ? DIRECT_MEMORY_COUNTER.get() : -1;
401     }
402 
403     /**
404      * Returns the temporary directory.
405      */
406     public static File tmpdir() {
407         return TMPDIR;
408     }
409 
410     /**
411      * Returns the bit mode of the current VM (usually 32 or 64.)
412      */
413     public static int bitMode() {
414         return BIT_MODE;
415     }
416 
417     /**
418      * Return the address size of the OS.
419      * 4 (for 32 bits systems ) and 8 (for 64 bits systems).
420      */
421     public static int addressSize() {
422         return ADDRESS_SIZE;
423     }
424 
425     public static long allocateMemory(long size) {
426         return PlatformDependent0.allocateMemory(size);
427     }
428 
429     public static void freeMemory(long address) {
430         PlatformDependent0.freeMemory(address);
431     }
432 
433     public static long reallocateMemory(long address, long newSize) {
434         return PlatformDependent0.reallocateMemory(address, newSize);
435     }
436 
437     /**
438      * Raises an exception bypassing compiler checks for checked exceptions.
439      */
440     public static void throwException(Throwable t) {
441         PlatformDependent0.throwException(t);
442     }
443 
444     /**
445      * Creates a new fastest {@link ConcurrentMap} implementation for the current platform.
446      */
447     public static <K, V> ConcurrentMap<K, V> newConcurrentHashMap() {
448         return new ConcurrentHashMap<K, V>();
449     }
450 
451     /**
452      * Creates a new fastest {@link LongCounter} implementation for the current platform.
453      */
454     public static LongCounter newLongCounter() {
455         return new LongAdderCounter();
456     }
457 
458     /**
459      * Creates a new fastest {@link ConcurrentMap} implementation for the current platform.
460      */
461     public static <K, V> ConcurrentMap<K, V> newConcurrentHashMap(int initialCapacity) {
462         return new ConcurrentHashMap<K, V>(initialCapacity);
463     }
464 
465     /**
466      * Creates a new fastest {@link ConcurrentMap} implementation for the current platform.
467      */
468     public static <K, V> ConcurrentMap<K, V> newConcurrentHashMap(int initialCapacity, float loadFactor) {
469         return new ConcurrentHashMap<K, V>(initialCapacity, loadFactor);
470     }
471 
472     /**
473      * Creates a new fastest {@link ConcurrentMap} implementation for the current platform.
474      */
475     public static <K, V> ConcurrentMap<K, V> newConcurrentHashMap(
476             int initialCapacity, float loadFactor, int concurrencyLevel) {
477         return new ConcurrentHashMap<K, V>(initialCapacity, loadFactor, concurrencyLevel);
478     }
479 
480     /**
481      * Creates a new fastest {@link ConcurrentMap} implementation for the current platform.
482      */
483     public static <K, V> ConcurrentMap<K, V> newConcurrentHashMap(Map<? extends K, ? extends V> map) {
484         return new ConcurrentHashMap<K, V>(map);
485     }
486 
487     /**
488      * Try to deallocate the specified direct {@link ByteBuffer}. Please note this method does nothing if
489      * the current platform does not support this operation or the specified buffer is not a direct buffer.
490      */
491     public static void freeDirectBuffer(ByteBuffer buffer) {
492         CLEANER.freeDirectBuffer(buffer);
493     }
494 
495     public static long directBufferAddress(ByteBuffer buffer) {
496         return PlatformDependent0.directBufferAddress(buffer);
497     }
498 
499     public static ByteBuffer directBuffer(long memoryAddress, int size) {
500         if (PlatformDependent0.hasDirectBufferNoCleanerConstructor()) {
501             return PlatformDependent0.newDirectBuffer(memoryAddress, size);
502         }
503         throw new UnsupportedOperationException(
504                 "sun.misc.Unsafe or java.nio.DirectByteBuffer.<init>(long, int) not available");
505     }
506 
507     public static Object getObject(Object object, long fieldOffset) {
508         return PlatformDependent0.getObject(object, fieldOffset);
509     }
510 
511     public static int getInt(Object object, long fieldOffset) {
512         return PlatformDependent0.getInt(object, fieldOffset);
513     }
514 
515     static void safeConstructPutInt(Object object, long fieldOffset, int value) {
516         PlatformDependent0.safeConstructPutInt(object, fieldOffset, value);
517     }
518 
519     public static void putShortOrdered(long adddress, short newValue) {
520         PlatformDependent0.putShortOrdered(adddress, newValue);
521     }
522 
523     public static int getIntVolatile(long address) {
524         return PlatformDependent0.getIntVolatile(address);
525     }
526 
527     public static void putIntOrdered(long adddress, int newValue) {
528         PlatformDependent0.putIntOrdered(adddress, newValue);
529     }
530 
531     public static byte getByte(long address) {
532         return PlatformDependent0.getByte(address);
533     }
534 
535     public static short getShort(long address) {
536         return PlatformDependent0.getShort(address);
537     }
538 
539     public static int getInt(long address) {
540         return PlatformDependent0.getInt(address);
541     }
542 
543     public static long getLong(long address) {
544         return PlatformDependent0.getLong(address);
545     }
546 
547     public static byte getByte(byte[] data, int index) {
548         return hasUnsafe() ? PlatformDependent0.getByte(data, index) : data[index];
549     }
550 
551     public static byte getByte(byte[] data, long index) {
552         return hasUnsafe() ? PlatformDependent0.getByte(data, index) : data[toIntExact(index)];
553     }
554 
555     public static short getShort(byte[] data, int index) {
556         return hasUnsafe() ? PlatformDependent0.getShort(data, index) : data[index];
557     }
558 
559     public static int getInt(byte[] data, int index) {
560         return hasUnsafe() ? PlatformDependent0.getInt(data, index) : data[index];
561     }
562 
563     public static int getInt(int[] data, long index) {
564         return hasUnsafe() ? PlatformDependent0.getInt(data, index) : data[toIntExact(index)];
565     }
566 
567     public static long getLong(byte[] data, int index) {
568         return hasUnsafe() ? PlatformDependent0.getLong(data, index) : data[index];
569     }
570 
571     public static long getLong(long[] data, long index) {
572         return hasUnsafe() ? PlatformDependent0.getLong(data, index) : data[toIntExact(index)];
573     }
574 
575     private static int toIntExact(long value) {
576         return Math.toIntExact(value);
577     }
578 
579     private static long getLongSafe(byte[] bytes, int offset) {
580         if (BIG_ENDIAN_NATIVE_ORDER) {
581             return (long) bytes[offset] << 56 |
582                     ((long) bytes[offset + 1] & 0xff) << 48 |
583                     ((long) bytes[offset + 2] & 0xff) << 40 |
584                     ((long) bytes[offset + 3] & 0xff) << 32 |
585                     ((long) bytes[offset + 4] & 0xff) << 24 |
586                     ((long) bytes[offset + 5] & 0xff) << 16 |
587                     ((long) bytes[offset + 6] & 0xff) <<  8 |
588                     (long) bytes[offset + 7] & 0xff;
589         }
590         return (long) bytes[offset] & 0xff |
591                 ((long) bytes[offset + 1] & 0xff) << 8 |
592                 ((long) bytes[offset + 2] & 0xff) << 16 |
593                 ((long) bytes[offset + 3] & 0xff) << 24 |
594                 ((long) bytes[offset + 4] & 0xff) << 32 |
595                 ((long) bytes[offset + 5] & 0xff) << 40 |
596                 ((long) bytes[offset + 6] & 0xff) << 48 |
597                 (long) bytes[offset + 7] << 56;
598     }
599 
600     private static int getIntSafe(byte[] bytes, int offset) {
601         if (BIG_ENDIAN_NATIVE_ORDER) {
602             return bytes[offset] << 24 |
603                     (bytes[offset + 1] & 0xff) << 16 |
604                     (bytes[offset + 2] & 0xff) << 8 |
605                     bytes[offset + 3] & 0xff;
606         }
607         return bytes[offset] & 0xff |
608                 (bytes[offset + 1] & 0xff) << 8 |
609                 (bytes[offset + 2] & 0xff) << 16 |
610                 bytes[offset + 3] << 24;
611     }
612 
613     private static short getShortSafe(byte[] bytes, int offset) {
614         if (BIG_ENDIAN_NATIVE_ORDER) {
615             return (short) (bytes[offset] << 8 | (bytes[offset + 1] & 0xff));
616         }
617         return (short) (bytes[offset] & 0xff | (bytes[offset + 1] << 8));
618     }
619 
620     /**
621      * Identical to {@link PlatformDependent0#hashCodeAsciiCompute(long, int)} but for {@link CharSequence}.
622      */
623     private static int hashCodeAsciiCompute(CharSequence value, int offset, int hash) {
624         if (BIG_ENDIAN_NATIVE_ORDER) {
625             return hash * HASH_CODE_C1 +
626                     // Low order int
627                     hashCodeAsciiSanitizeInt(value, offset + 4) * HASH_CODE_C2 +
628                     // High order int
629                     hashCodeAsciiSanitizeInt(value, offset);
630         }
631         return hash * HASH_CODE_C1 +
632                 // Low order int
633                 hashCodeAsciiSanitizeInt(value, offset) * HASH_CODE_C2 +
634                 // High order int
635                 hashCodeAsciiSanitizeInt(value, offset + 4);
636     }
637 
638     /**
639      * Identical to {@link PlatformDependent0#hashCodeAsciiSanitize(int)} but for {@link CharSequence}.
640      */
641     private static int hashCodeAsciiSanitizeInt(CharSequence value, int offset) {
642         if (BIG_ENDIAN_NATIVE_ORDER) {
643             // mimic a unsafe.getInt call on a big endian machine
644             return (value.charAt(offset + 3) & 0x1f) |
645                    (value.charAt(offset + 2) & 0x1f) << 8 |
646                    (value.charAt(offset + 1) & 0x1f) << 16 |
647                    (value.charAt(offset) & 0x1f) << 24;
648         }
649         return (value.charAt(offset + 3) & 0x1f) << 24 |
650                (value.charAt(offset + 2) & 0x1f) << 16 |
651                (value.charAt(offset + 1) & 0x1f) << 8 |
652                (value.charAt(offset) & 0x1f);
653     }
654 
655     /**
656      * Identical to {@link PlatformDependent0#hashCodeAsciiSanitize(short)} but for {@link CharSequence}.
657      */
658     private static int hashCodeAsciiSanitizeShort(CharSequence value, int offset) {
659         if (BIG_ENDIAN_NATIVE_ORDER) {
660             // mimic a unsafe.getShort call on a big endian machine
661             return (value.charAt(offset + 1) & 0x1f) |
662                     (value.charAt(offset) & 0x1f) << 8;
663         }
664         return (value.charAt(offset + 1) & 0x1f) << 8 |
665                 (value.charAt(offset) & 0x1f);
666     }
667 
668     /**
669      * Identical to {@link PlatformDependent0#hashCodeAsciiSanitize(byte)} but for {@link CharSequence}.
670      */
671     private static int hashCodeAsciiSanitizeByte(char value) {
672         return value & 0x1f;
673     }
674 
675     public static void putByte(long address, byte value) {
676         PlatformDependent0.putByte(address, value);
677     }
678 
679     public static void putShort(long address, short value) {
680         PlatformDependent0.putShort(address, value);
681     }
682 
683     public static void putInt(long address, int value) {
684         PlatformDependent0.putInt(address, value);
685     }
686 
687     public static void putLong(long address, long value) {
688         PlatformDependent0.putLong(address, value);
689     }
690 
691     public static void putByte(byte[] data, int index, byte value) {
692         PlatformDependent0.putByte(data, index, value);
693     }
694 
695     public static void putByte(Object data, long offset, byte value) {
696         PlatformDependent0.putByte(data, offset, value);
697     }
698 
699     public static void putShort(byte[] data, int index, short value) {
700         PlatformDependent0.putShort(data, index, value);
701     }
702 
703     public static void putInt(byte[] data, int index, int value) {
704         PlatformDependent0.putInt(data, index, value);
705     }
706 
707     public static void putLong(byte[] data, int index, long value) {
708         PlatformDependent0.putLong(data, index, value);
709     }
710 
711     public static void putObject(Object o, long offset, Object x) {
712         PlatformDependent0.putObject(o, offset, x);
713     }
714 
715     public static long objectFieldOffset(Field field) {
716         return PlatformDependent0.objectFieldOffset(field);
717     }
718 
719     public static void copyMemory(long srcAddr, long dstAddr, long length) {
720         PlatformDependent0.copyMemory(srcAddr, dstAddr, length);
721     }
722 
723     public static void copyMemory(byte[] src, int srcIndex, long dstAddr, long length) {
724         PlatformDependent0.copyMemory(src, BYTE_ARRAY_BASE_OFFSET + srcIndex, null, dstAddr, length);
725     }
726 
727     public static void copyMemory(byte[] src, int srcIndex, byte[] dst, int dstIndex, long length) {
728         PlatformDependent0.copyMemory(src, BYTE_ARRAY_BASE_OFFSET + srcIndex,
729                                       dst, BYTE_ARRAY_BASE_OFFSET + dstIndex, length);
730     }
731 
732     public static void copyMemory(long srcAddr, byte[] dst, int dstIndex, long length) {
733         PlatformDependent0.copyMemory(null, srcAddr, dst, BYTE_ARRAY_BASE_OFFSET + dstIndex, length);
734     }
735 
736     public static void setMemory(byte[] dst, int dstIndex, long bytes, byte value) {
737         PlatformDependent0.setMemory(dst, BYTE_ARRAY_BASE_OFFSET + dstIndex, bytes, value);
738     }
739 
740     public static void setMemory(long address, long bytes, byte value) {
741         PlatformDependent0.setMemory(address, bytes, value);
742     }
743 
744     /**
745      * Allocate a new {@link ByteBuffer} with the given {@code capacity}. {@link ByteBuffer}s allocated with
746      * this method <strong>MUST</strong> be deallocated via {@link #freeDirectNoCleaner(ByteBuffer)}.
747      */
748     public static ByteBuffer allocateDirectNoCleaner(int capacity) {
749         assert USE_DIRECT_BUFFER_NO_CLEANER;
750 
751         incrementMemoryCounter(capacity);
752         try {
753             return PlatformDependent0.allocateDirectNoCleaner(capacity);
754         } catch (Throwable e) {
755             decrementMemoryCounter(capacity);
756             throwException(e);
757             return null;
758         }
759     }
760 
761     /**
762      * Reallocate a new {@link ByteBuffer} with the given {@code capacity}. {@link ByteBuffer}s reallocated with
763      * this method <strong>MUST</strong> be deallocated via {@link #freeDirectNoCleaner(ByteBuffer)}.
764      */
765     public static ByteBuffer reallocateDirectNoCleaner(ByteBuffer buffer, int capacity) {
766         assert USE_DIRECT_BUFFER_NO_CLEANER;
767 
768         int len = capacity - buffer.capacity();
769         incrementMemoryCounter(len);
770         try {
771             return PlatformDependent0.reallocateDirectNoCleaner(buffer, capacity);
772         } catch (Throwable e) {
773             decrementMemoryCounter(len);
774             throwException(e);
775             return null;
776         }
777     }
778 
779     /**
780      * This method <strong>MUST</strong> only be called for {@link ByteBuffer}s that were allocated via
781      * {@link #allocateDirectNoCleaner(int)}.
782      */
783     public static void freeDirectNoCleaner(ByteBuffer buffer) {
784         assert USE_DIRECT_BUFFER_NO_CLEANER;
785 
786         int capacity = buffer.capacity();
787         PlatformDependent0.freeMemory(PlatformDependent0.directBufferAddress(buffer));
788         decrementMemoryCounter(capacity);
789     }
790 
791     public static boolean hasAlignDirectByteBuffer() {
792         return hasUnsafe() || PlatformDependent0.hasAlignSliceMethod();
793     }
794 
795     public static ByteBuffer alignDirectBuffer(ByteBuffer buffer, int alignment) {
796         if (!buffer.isDirect()) {
797             throw new IllegalArgumentException("Cannot get aligned slice of non-direct byte buffer.");
798         }
799         if (PlatformDependent0.hasAlignSliceMethod()) {
800             return PlatformDependent0.alignSlice(buffer, alignment);
801         }
802         if (hasUnsafe()) {
803             long address = directBufferAddress(buffer);
804             long aligned = align(address, alignment);
805             buffer.position((int) (aligned - address));
806             return buffer.slice();
807         }
808         // We don't have enough information to be able to align any buffers.
809         throw new UnsupportedOperationException("Cannot align direct buffer. " +
810                 "Needs either Unsafe or ByteBuffer.alignSlice method available.");
811     }
812 
813     public static long align(long value, int alignment) {
814         return Pow2.align(value, alignment);
815     }
816 
817     private static void incrementMemoryCounter(int capacity) {
818         if (DIRECT_MEMORY_COUNTER != null) {
819             long newUsedMemory = DIRECT_MEMORY_COUNTER.addAndGet(capacity);
820             if (newUsedMemory > DIRECT_MEMORY_LIMIT) {
821                 DIRECT_MEMORY_COUNTER.addAndGet(-capacity);
822                 throw new OutOfDirectMemoryError("failed to allocate " + capacity
823                         + " byte(s) of direct memory (used: " + (newUsedMemory - capacity)
824                         + ", max: " + DIRECT_MEMORY_LIMIT + ')');
825             }
826         }
827     }
828 
829     private static void decrementMemoryCounter(int capacity) {
830         if (DIRECT_MEMORY_COUNTER != null) {
831             long usedMemory = DIRECT_MEMORY_COUNTER.addAndGet(-capacity);
832             assert usedMemory >= 0;
833         }
834     }
835 
836     public static boolean useDirectBufferNoCleaner() {
837         return USE_DIRECT_BUFFER_NO_CLEANER;
838     }
839 
840     /**
841      * Compare two {@code byte} arrays for equality. For performance reasons no bounds checking on the
842      * parameters is performed.
843      *
844      * @param bytes1 the first byte array.
845      * @param startPos1 the position (inclusive) to start comparing in {@code bytes1}.
846      * @param bytes2 the second byte array.
847      * @param startPos2 the position (inclusive) to start comparing in {@code bytes2}.
848      * @param length the amount of bytes to compare. This is assumed to be validated as not going out of bounds
849      * by the caller.
850      */
851     public static boolean equals(byte[] bytes1, int startPos1, byte[] bytes2, int startPos2, int length) {
852         if (javaVersion() > 8 && (startPos2 | startPos1 | (bytes1.length - length) | bytes2.length - length) == 0) {
853             return Arrays.equals(bytes1, bytes2);
854         }
855         return !hasUnsafe() || !unalignedAccess() ?
856                   equalsSafe(bytes1, startPos1, bytes2, startPos2, length) :
857                   PlatformDependent0.equals(bytes1, startPos1, bytes2, startPos2, length);
858     }
859 
860     /**
861      * Determine if a subsection of an array is zero.
862      * @param bytes The byte array.
863      * @param startPos The starting index (inclusive) in {@code bytes}.
864      * @param length The amount of bytes to check for zero.
865      * @return {@code false} if {@code bytes[startPos:startsPos+length)} contains a value other than zero.
866      */
867     public static boolean isZero(byte[] bytes, int startPos, int length) {
868         return !hasUnsafe() || !unalignedAccess() ?
869                 isZeroSafe(bytes, startPos, length) :
870                 PlatformDependent0.isZero(bytes, startPos, length);
871     }
872 
873     /**
874      * Compare two {@code byte} arrays for equality without leaking timing information.
875      * For performance reasons no bounds checking on the parameters is performed.
876      * <p>
877      * The {@code int} return type is intentional and is designed to allow cascading of constant time operations:
878      * <pre>
879      *     byte[] s1 = new {1, 2, 3};
880      *     byte[] s2 = new {1, 2, 3};
881      *     byte[] s3 = new {1, 2, 3};
882      *     byte[] s4 = new {4, 5, 6};
883      *     boolean equals = (equalsConstantTime(s1, 0, s2, 0, s1.length) &
884      *                       equalsConstantTime(s3, 0, s4, 0, s3.length)) != 0;
885      * </pre>
886      * @param bytes1 the first byte array.
887      * @param startPos1 the position (inclusive) to start comparing in {@code bytes1}.
888      * @param bytes2 the second byte array.
889      * @param startPos2 the position (inclusive) to start comparing in {@code bytes2}.
890      * @param length the amount of bytes to compare. This is assumed to be validated as not going out of bounds
891      * by the caller.
892      * @return {@code 0} if not equal. {@code 1} if equal.
893      */
894     public static int equalsConstantTime(byte[] bytes1, int startPos1, byte[] bytes2, int startPos2, int length) {
895         return !hasUnsafe() || !unalignedAccess() ?
896                   ConstantTimeUtils.equalsConstantTime(bytes1, startPos1, bytes2, startPos2, length) :
897                   PlatformDependent0.equalsConstantTime(bytes1, startPos1, bytes2, startPos2, length);
898     }
899 
900     /**
901      * Calculate a hash code of a byte array assuming ASCII character encoding.
902      * The resulting hash code will be case insensitive.
903      * @param bytes The array which contains the data to hash.
904      * @param startPos What index to start generating a hash code in {@code bytes}
905      * @param length The amount of bytes that should be accounted for in the computation.
906      * @return The hash code of {@code bytes} assuming ASCII character encoding.
907      * The resulting hash code will be case insensitive.
908      */
909     public static int hashCodeAscii(byte[] bytes, int startPos, int length) {
910         return !hasUnsafe() || !unalignedAccess() ?
911                 hashCodeAsciiSafe(bytes, startPos, length) :
912                 PlatformDependent0.hashCodeAscii(bytes, startPos, length);
913     }
914 
915     /**
916      * Calculate a hash code of a byte array assuming ASCII character encoding.
917      * The resulting hash code will be case insensitive.
918      * <p>
919      * This method assumes that {@code bytes} is equivalent to a {@code byte[]} but just using {@link CharSequence}
920      * for storage. The upper most byte of each {@code char} from {@code bytes} is ignored.
921      * @param bytes The array which contains the data to hash (assumed to be equivalent to a {@code byte[]}).
922      * @return The hash code of {@code bytes} assuming ASCII character encoding.
923      * The resulting hash code will be case insensitive.
924      */
925     public static int hashCodeAscii(CharSequence bytes) {
926         final int length = bytes.length();
927         final int remainingBytes = length & 7;
928         int hash = HASH_CODE_ASCII_SEED;
929         // Benchmarking shows that by just naively looping for inputs 8~31 bytes long we incur a relatively large
930         // performance penalty (only achieve about 60% performance of loop which iterates over each char). So because
931         // of this we take special provisions to unroll the looping for these conditions.
932         if (length >= 32) {
933             for (int i = length - 8; i >= remainingBytes; i -= 8) {
934                 hash = hashCodeAsciiCompute(bytes, i, hash);
935             }
936         } else if (length >= 8) {
937             hash = hashCodeAsciiCompute(bytes, length - 8, hash);
938             if (length >= 16) {
939                 hash = hashCodeAsciiCompute(bytes, length - 16, hash);
940                 if (length >= 24) {
941                     hash = hashCodeAsciiCompute(bytes, length - 24, hash);
942                 }
943             }
944         }
945         if (remainingBytes == 0) {
946             return hash;
947         }
948         int offset = 0;
949         if (remainingBytes != 2 & remainingBytes != 4 & remainingBytes != 6) { // 1, 3, 5, 7
950             hash = hash * HASH_CODE_C1 + hashCodeAsciiSanitizeByte(bytes.charAt(0));
951             offset = 1;
952         }
953         if (remainingBytes != 1 & remainingBytes != 4 & remainingBytes != 5) { // 2, 3, 6, 7
954             hash = hash * (offset == 0 ? HASH_CODE_C1 : HASH_CODE_C2)
955                     + hashCodeAsciiSanitize(hashCodeAsciiSanitizeShort(bytes, offset));
956             offset += 2;
957         }
958         if (remainingBytes >= 4) { // 4, 5, 6, 7
959             return hash * ((offset == 0 | offset == 3) ? HASH_CODE_C1 : HASH_CODE_C2)
960                     + hashCodeAsciiSanitizeInt(bytes, offset);
961         }
962         return hash;
963     }
964 
965     private static final class Mpsc {
966         private static final boolean USE_MPSC_CHUNKED_ARRAY_QUEUE;
967 
968         static {
969             Object unsafe = null;
970             if (hasUnsafe()) {
971                 // jctools goes through its own process of initializing unsafe; of
972                 // course, this requires permissions which might not be granted to calling code, so we
973                 // must mark this block as privileged too
974                 unsafe = AccessController.doPrivileged(new PrivilegedAction<Object>() {
975                     @Override
976                     public Object run() {
977                         // force JCTools to initialize unsafe
978                         return UnsafeAccess.UNSAFE;
979                     }
980                 });
981             }
982 
983             if (unsafe == null) {
984                 logger.debug("org.jctools-core.MpscChunkedArrayQueue: unavailable");
985                 USE_MPSC_CHUNKED_ARRAY_QUEUE = false;
986             } else {
987                 logger.debug("org.jctools-core.MpscChunkedArrayQueue: available");
988                 USE_MPSC_CHUNKED_ARRAY_QUEUE = true;
989             }
990         }
991 
992         static <T> Queue<T> newMpscQueue(final int maxCapacity) {
993             // Calculate the max capacity which can not be bigger than MAX_ALLOWED_MPSC_CAPACITY.
994             // This is forced by the MpscChunkedArrayQueue implementation as will try to round it
995             // up to the next power of two and so will overflow otherwise.
996             final int capacity = max(min(maxCapacity, MAX_ALLOWED_MPSC_CAPACITY), MIN_MAX_MPSC_CAPACITY);
997             return newChunkedMpscQueue(MPSC_CHUNK_SIZE, capacity);
998         }
999 
1000         static <T> Queue<T> newChunkedMpscQueue(final int chunkSize, final int capacity) {
1001             return USE_MPSC_CHUNKED_ARRAY_QUEUE ? new MpscChunkedArrayQueue<T>(chunkSize, capacity)
1002                     : new MpscChunkedAtomicArrayQueue<T>(chunkSize, capacity);
1003         }
1004 
1005         static <T> Queue<T> newMpscQueue() {
1006             return USE_MPSC_CHUNKED_ARRAY_QUEUE ? new MpscUnboundedArrayQueue<T>(MPSC_CHUNK_SIZE)
1007                                                 : new MpscUnboundedAtomicArrayQueue<T>(MPSC_CHUNK_SIZE);
1008         }
1009     }
1010 
1011     /**
1012      * Create a new {@link Queue} which is safe to use for multiple producers (different threads) and a single
1013      * consumer (one thread!).
1014      * @return A MPSC queue which may be unbounded.
1015      */
1016     public static <T> Queue<T> newMpscQueue() {
1017         return Mpsc.newMpscQueue();
1018     }
1019 
1020     /**
1021      * Create a new {@link Queue} which is safe to use for multiple producers (different threads) and a single
1022      * consumer (one thread!).
1023      */
1024     public static <T> Queue<T> newMpscQueue(final int maxCapacity) {
1025         return Mpsc.newMpscQueue(maxCapacity);
1026     }
1027 
1028     /**
1029      * Create a new {@link Queue} which is safe to use for multiple producers (different threads) and a single
1030      * consumer (one thread!).
1031      * The queue will grow and shrink its capacity in units of the given chunk size.
1032      */
1033     public static <T> Queue<T> newMpscQueue(final int chunkSize, final int maxCapacity) {
1034         return Mpsc.newChunkedMpscQueue(chunkSize, maxCapacity);
1035     }
1036 
1037     /**
1038      * Create a new {@link Queue} which is safe to use for single producer (one thread!) and a single
1039      * consumer (one thread!).
1040      */
1041     public static <T> Queue<T> newSpscQueue() {
1042         return hasUnsafe() ? new SpscLinkedQueue<T>() : new SpscLinkedAtomicQueue<T>();
1043     }
1044 
1045     /**
1046      * Create a new {@link Queue} which is safe to use for multiple producers (different threads) and a single
1047      * consumer (one thread!) with the given fixes {@code capacity}.
1048      */
1049     public static <T> Queue<T> newFixedMpscQueue(int capacity) {
1050         return hasUnsafe() ? new MpscArrayQueue<T>(capacity) : new MpscAtomicArrayQueue<T>(capacity);
1051     }
1052 
1053     /**
1054      * Create a new un-padded {@link Queue} which is safe to use for multiple producers (different threads) and a single
1055      * consumer (one thread!) with the given fixes {@code capacity}.<br>
1056      * This should be preferred to {@link #newFixedMpscQueue(int)} when the queue is not to be heavily contended.
1057      */
1058     public static <T> Queue<T> newFixedMpscUnpaddedQueue(int capacity) {
1059         return hasUnsafe() ? new MpscUnpaddedArrayQueue<T>(capacity) : new MpscAtomicUnpaddedArrayQueue<T>(capacity);
1060     }
1061 
1062     /**
1063      * Create a new {@link Queue} which is safe to use for multiple producers (different threads) and multiple
1064      * consumers with the given fixes {@code capacity}.
1065      */
1066     public static <T> Queue<T> newFixedMpmcQueue(int capacity) {
1067         return hasUnsafe() ? new MpmcArrayQueue<T>(capacity) : new MpmcAtomicArrayQueue<T>(capacity);
1068     }
1069 
1070     /**
1071      * Return the {@link ClassLoader} for the given {@link Class}.
1072      */
1073     public static ClassLoader getClassLoader(final Class<?> clazz) {
1074         return PlatformDependent0.getClassLoader(clazz);
1075     }
1076 
1077     /**
1078      * Return the context {@link ClassLoader} for the current {@link Thread}.
1079      */
1080     public static ClassLoader getContextClassLoader() {
1081         return PlatformDependent0.getContextClassLoader();
1082     }
1083 
1084     /**
1085      * Return the system {@link ClassLoader}.
1086      */
1087     public static ClassLoader getSystemClassLoader() {
1088         return PlatformDependent0.getSystemClassLoader();
1089     }
1090 
1091     /**
1092      * Returns a new concurrent {@link Deque}.
1093      */
1094     public static <C> Deque<C> newConcurrentDeque() {
1095         return new ConcurrentLinkedDeque<C>();
1096     }
1097 
1098     /**
1099      * Return a {@link Random} which is not-threadsafe and so can only be used from the same thread.
1100      */
1101     public static Random threadLocalRandom() {
1102         return ThreadLocalRandom.current();
1103     }
1104 
1105     private static boolean isWindows0() {
1106         boolean windows = "windows".equals(NORMALIZED_OS);
1107         if (windows) {
1108             logger.debug("Platform: Windows");
1109         }
1110         return windows;
1111     }
1112 
1113     private static boolean isOsx0() {
1114         boolean osx = "osx".equals(NORMALIZED_OS);
1115         if (osx) {
1116             logger.debug("Platform: MacOS");
1117         }
1118         return osx;
1119     }
1120 
1121     private static boolean maybeSuperUser0() {
1122         String username = SystemPropertyUtil.get("user.name");
1123         if (isWindows()) {
1124             return "Administrator".equals(username);
1125         }
1126         // Check for root and toor as some BSDs have a toor user that is basically the same as root.
1127         return "root".equals(username) || "toor".equals(username);
1128     }
1129 
1130     private static Throwable unsafeUnavailabilityCause0() {
1131         if (isAndroid()) {
1132             logger.debug("sun.misc.Unsafe: unavailable (Android)");
1133             return new UnsupportedOperationException("sun.misc.Unsafe: unavailable (Android)");
1134         }
1135 
1136         if (isIkvmDotNet()) {
1137             logger.debug("sun.misc.Unsafe: unavailable (IKVM.NET)");
1138             return new UnsupportedOperationException("sun.misc.Unsafe: unavailable (IKVM.NET)");
1139         }
1140 
1141         Throwable cause = PlatformDependent0.getUnsafeUnavailabilityCause();
1142         if (cause != null) {
1143             return cause;
1144         }
1145 
1146         try {
1147             boolean hasUnsafe = PlatformDependent0.hasUnsafe();
1148             logger.debug("sun.misc.Unsafe: {}", hasUnsafe ? "available" : "unavailable");
1149             return hasUnsafe ? null : PlatformDependent0.getUnsafeUnavailabilityCause();
1150         } catch (Throwable t) {
1151             logger.trace("Could not determine if Unsafe is available", t);
1152             // Probably failed to initialize PlatformDependent0.
1153             return new UnsupportedOperationException("Could not determine if Unsafe is available", t);
1154         }
1155     }
1156 
1157     /**
1158      * Returns {@code true} if the running JVM is either <a href="https://developer.ibm.com/javasdk/">IBM J9</a> or
1159      * <a href="https://www.eclipse.org/openj9/">Eclipse OpenJ9</a>, {@code false} otherwise.
1160      */
1161     public static boolean isJ9Jvm() {
1162         return IS_J9_JVM;
1163     }
1164 
1165     private static boolean isJ9Jvm0() {
1166         String vmName = SystemPropertyUtil.get("java.vm.name", "").toLowerCase();
1167         return vmName.startsWith("ibm j9") || vmName.startsWith("eclipse openj9");
1168     }
1169 
1170     /**
1171      * Returns {@code true} if the running JVM is <a href="https://www.ikvm.net">IKVM.NET</a>, {@code false} otherwise.
1172      */
1173     public static boolean isIkvmDotNet() {
1174         return IS_IVKVM_DOT_NET;
1175     }
1176 
1177     private static boolean isIkvmDotNet0() {
1178         String vmName = SystemPropertyUtil.get("java.vm.name", "").toUpperCase(Locale.US);
1179         return vmName.equals("IKVM.NET");
1180     }
1181 
1182     private static Pattern getMaxDirectMemorySizeArgPattern() {
1183         // Pattern's is immutable so it's always safe published
1184         Pattern pattern = MAX_DIRECT_MEMORY_SIZE_ARG_PATTERN;
1185         if (pattern == null) {
1186             pattern = Pattern.compile("\\s*-XX:MaxDirectMemorySize\\s*=\\s*([0-9]+)\\s*([kKmMgG]?)\\s*$");
1187             MAX_DIRECT_MEMORY_SIZE_ARG_PATTERN =  pattern;
1188         }
1189         return pattern;
1190     }
1191 
1192     /**
1193      * Compute an estimate of the maximum amount of direct memory available to this JVM.
1194      * <p>
1195      * The computation is not cached, so you probably want to use {@link #maxDirectMemory()} instead.
1196      * <p>
1197      * This will produce debug log output when called.
1198      *
1199      * @return The estimated max direct memory, in bytes.
1200      */
1201     @SuppressWarnings("unchecked")
1202     public static long estimateMaxDirectMemory() {
1203         long maxDirectMemory = PlatformDependent0.bitsMaxDirectMemory();
1204         if (maxDirectMemory > 0) {
1205             return maxDirectMemory;
1206         }
1207 
1208         try {
1209             // Now try to get the JVM option (-XX:MaxDirectMemorySize) and parse it.
1210             // Note that we are using reflection because Android doesn't have these classes.
1211             ClassLoader systemClassLoader = getSystemClassLoader();
1212             Class<?> mgmtFactoryClass = Class.forName(
1213                     "java.lang.management.ManagementFactory", true, systemClassLoader);
1214             Class<?> runtimeClass = Class.forName(
1215                     "java.lang.management.RuntimeMXBean", true, systemClassLoader);
1216 
1217             MethodHandles.Lookup lookup = MethodHandles.publicLookup();
1218             MethodHandle getRuntime = lookup.findStatic(
1219                     mgmtFactoryClass, "getRuntimeMXBean", methodType(runtimeClass));
1220             MethodHandle getInputArguments = lookup.findVirtual(
1221                     runtimeClass, "getInputArguments", methodType(List.class));
1222             List<String> vmArgs = (List<String>) getInputArguments.invoke(getRuntime.invoke());
1223 
1224             Pattern maxDirectMemorySizeArgPattern = getMaxDirectMemorySizeArgPattern();
1225 
1226             for (int i = vmArgs.size() - 1; i >= 0; i --) {
1227                 Matcher m = maxDirectMemorySizeArgPattern.matcher(vmArgs.get(i));
1228                 if (!m.matches()) {
1229                     continue;
1230                 }
1231 
1232                 maxDirectMemory = Long.parseLong(m.group(1));
1233                 switch (m.group(2).charAt(0)) {
1234                     case 'k': case 'K':
1235                         maxDirectMemory *= 1024;
1236                         break;
1237                     case 'm': case 'M':
1238                         maxDirectMemory *= 1024 * 1024;
1239                         break;
1240                     case 'g': case 'G':
1241                         maxDirectMemory *= 1024 * 1024 * 1024;
1242                         break;
1243                     default:
1244                         break;
1245                 }
1246                 break;
1247             }
1248         } catch (Throwable ignored) {
1249             // Ignore
1250         }
1251 
1252         if (maxDirectMemory <= 0) {
1253             maxDirectMemory = Runtime.getRuntime().maxMemory();
1254             logger.debug("maxDirectMemory: {} bytes (maybe)", maxDirectMemory);
1255         } else {
1256             logger.debug("maxDirectMemory: {} bytes", maxDirectMemory);
1257         }
1258 
1259         return maxDirectMemory;
1260     }
1261 
1262     private static File tmpdir0() {
1263         File f;
1264         try {
1265             f = toDirectory(SystemPropertyUtil.get("io.netty.tmpdir"));
1266             if (f != null) {
1267                 logger.debug("-Dio.netty.tmpdir: {}", f);
1268                 return f;
1269             }
1270 
1271             f = toDirectory(SystemPropertyUtil.get("java.io.tmpdir"));
1272             if (f != null) {
1273                 logger.debug("-Dio.netty.tmpdir: {} (java.io.tmpdir)", f);
1274                 return f;
1275             }
1276 
1277             // This shouldn't happen, but just in case ..
1278             if (isWindows()) {
1279                 f = toDirectory(System.getenv("TEMP"));
1280                 if (f != null) {
1281                     logger.debug("-Dio.netty.tmpdir: {} (%TEMP%)", f);
1282                     return f;
1283                 }
1284 
1285                 String userprofile = System.getenv("USERPROFILE");
1286                 if (userprofile != null) {
1287                     f = toDirectory(userprofile + "\\AppData\\Local\\Temp");
1288                     if (f != null) {
1289                         logger.debug("-Dio.netty.tmpdir: {} (%USERPROFILE%\\AppData\\Local\\Temp)", f);
1290                         return f;
1291                     }
1292 
1293                     f = toDirectory(userprofile + "\\Local Settings\\Temp");
1294                     if (f != null) {
1295                         logger.debug("-Dio.netty.tmpdir: {} (%USERPROFILE%\\Local Settings\\Temp)", f);
1296                         return f;
1297                     }
1298                 }
1299             } else {
1300                 f = toDirectory(System.getenv("TMPDIR"));
1301                 if (f != null) {
1302                     logger.debug("-Dio.netty.tmpdir: {} ($TMPDIR)", f);
1303                     return f;
1304                 }
1305             }
1306         } catch (Throwable ignored) {
1307             // Environment variable inaccessible
1308         }
1309 
1310         // Last resort.
1311         if (isWindows()) {
1312             f = new File("C:\\Windows\\Temp");
1313         } else {
1314             f = new File("/tmp");
1315         }
1316 
1317         logger.warn("Failed to get the temporary directory; falling back to: {}", f);
1318         return f;
1319     }
1320 
1321     @SuppressWarnings("ResultOfMethodCallIgnored")
1322     private static File toDirectory(String path) {
1323         if (path == null) {
1324             return null;
1325         }
1326 
1327         File f = new File(path);
1328         f.mkdirs();
1329 
1330         if (!f.isDirectory()) {
1331             return null;
1332         }
1333 
1334         try {
1335             return f.getAbsoluteFile();
1336         } catch (Exception ignored) {
1337             return f;
1338         }
1339     }
1340 
1341     private static int bitMode0() {
1342         // Check user-specified bit mode first.
1343         int bitMode = SystemPropertyUtil.getInt("io.netty.bitMode", 0);
1344         if (bitMode > 0) {
1345             logger.debug("-Dio.netty.bitMode: {}", bitMode);
1346             return bitMode;
1347         }
1348 
1349         // And then the vendor specific ones which is probably most reliable.
1350         bitMode = SystemPropertyUtil.getInt("sun.arch.data.model", 0);
1351         if (bitMode > 0) {
1352             logger.debug("-Dio.netty.bitMode: {} (sun.arch.data.model)", bitMode);
1353             return bitMode;
1354         }
1355         bitMode = SystemPropertyUtil.getInt("com.ibm.vm.bitmode", 0);
1356         if (bitMode > 0) {
1357             logger.debug("-Dio.netty.bitMode: {} (com.ibm.vm.bitmode)", bitMode);
1358             return bitMode;
1359         }
1360 
1361         // os.arch also gives us a good hint.
1362         String arch = SystemPropertyUtil.get("os.arch", "").toLowerCase(Locale.US).trim();
1363         if ("amd64".equals(arch) || "x86_64".equals(arch)) {
1364             bitMode = 64;
1365         } else if ("i386".equals(arch) || "i486".equals(arch) || "i586".equals(arch) || "i686".equals(arch)) {
1366             bitMode = 32;
1367         }
1368 
1369         if (bitMode > 0) {
1370             logger.debug("-Dio.netty.bitMode: {} (os.arch: {})", bitMode, arch);
1371         }
1372 
1373         // Last resort: guess from VM name and then fall back to most common 64-bit mode.
1374         String vm = SystemPropertyUtil.get("java.vm.name", "").toLowerCase(Locale.US);
1375         Pattern bitPattern = Pattern.compile("([1-9][0-9]+)-?bit");
1376         Matcher m = bitPattern.matcher(vm);
1377         if (m.find()) {
1378             return Integer.parseInt(m.group(1));
1379         } else {
1380             return 64;
1381         }
1382     }
1383 
1384     private static int addressSize0() {
1385         if (!hasUnsafe()) {
1386             return -1;
1387         }
1388         return PlatformDependent0.addressSize();
1389     }
1390 
1391     private static long byteArrayBaseOffset0() {
1392         if (!hasUnsafe()) {
1393             return -1;
1394         }
1395         return PlatformDependent0.byteArrayBaseOffset();
1396     }
1397 
1398     private static boolean equalsSafe(byte[] bytes1, int startPos1, byte[] bytes2, int startPos2, int length) {
1399         final int end = startPos1 + length;
1400         for (; startPos1 < end; ++startPos1, ++startPos2) {
1401             if (bytes1[startPos1] != bytes2[startPos2]) {
1402                 return false;
1403             }
1404         }
1405         return true;
1406     }
1407 
1408     private static boolean isZeroSafe(byte[] bytes, int startPos, int length) {
1409         final int end = startPos + length;
1410         for (; startPos < end; ++startPos) {
1411             if (bytes[startPos] != 0) {
1412                 return false;
1413             }
1414         }
1415         return true;
1416     }
1417 
1418     /**
1419      * Package private for testing purposes only!
1420      */
1421     static int hashCodeAsciiSafe(byte[] bytes, int startPos, int length) {
1422         int hash = HASH_CODE_ASCII_SEED;
1423         final int remainingBytes = length & 7;
1424         final int end = startPos + remainingBytes;
1425         for (int i = startPos - 8 + length; i >= end; i -= 8) {
1426             hash = PlatformDependent0.hashCodeAsciiCompute(getLongSafe(bytes, i), hash);
1427         }
1428         switch(remainingBytes) {
1429         case 7:
1430             return ((hash * HASH_CODE_C1 + hashCodeAsciiSanitize(bytes[startPos]))
1431                           * HASH_CODE_C2 + hashCodeAsciiSanitize(getShortSafe(bytes, startPos + 1)))
1432                           * HASH_CODE_C1 + hashCodeAsciiSanitize(getIntSafe(bytes, startPos + 3));
1433         case 6:
1434             return (hash * HASH_CODE_C1 + hashCodeAsciiSanitize(getShortSafe(bytes, startPos)))
1435                          * HASH_CODE_C2 + hashCodeAsciiSanitize(getIntSafe(bytes, startPos + 2));
1436         case 5:
1437             return (hash * HASH_CODE_C1 + hashCodeAsciiSanitize(bytes[startPos]))
1438                          * HASH_CODE_C2 + hashCodeAsciiSanitize(getIntSafe(bytes, startPos + 1));
1439         case 4:
1440             return hash * HASH_CODE_C1 + hashCodeAsciiSanitize(getIntSafe(bytes, startPos));
1441         case 3:
1442             return (hash * HASH_CODE_C1 + hashCodeAsciiSanitize(bytes[startPos]))
1443                          * HASH_CODE_C2 + hashCodeAsciiSanitize(getShortSafe(bytes, startPos + 1));
1444         case 2:
1445             return hash * HASH_CODE_C1 + hashCodeAsciiSanitize(getShortSafe(bytes, startPos));
1446         case 1:
1447             return hash * HASH_CODE_C1 + hashCodeAsciiSanitize(bytes[startPos]);
1448         default:
1449             return hash;
1450         }
1451     }
1452 
1453     public static String normalizedArch() {
1454         return NORMALIZED_ARCH;
1455     }
1456 
1457     public static String normalizedOs() {
1458         return NORMALIZED_OS;
1459     }
1460 
1461     public static Set<String> normalizedLinuxClassifiers() {
1462         return LINUX_OS_CLASSIFIERS;
1463     }
1464 
1465     public static File createTempFile(String prefix, String suffix, File directory) throws IOException {
1466         if (directory == null) {
1467             return Files.createTempFile(prefix, suffix).toFile();
1468         }
1469         return Files.createTempFile(directory.toPath(), prefix, suffix).toFile();
1470     }
1471 
1472     /**
1473      * Adds only those classifier strings to <tt>dest</tt> which are present in <tt>allowed</tt>.
1474      *
1475      * @param allowed          allowed classifiers
1476      * @param dest             destination set
1477      * @param maybeClassifiers potential classifiers to add
1478      */
1479     private static void addClassifier(Set<String> allowed, Set<String> dest, String... maybeClassifiers) {
1480         for (String id : maybeClassifiers) {
1481             if (allowed.contains(id)) {
1482                 dest.add(id);
1483             }
1484         }
1485     }
1486 
1487     private static String normalizeOsReleaseVariableValue(String value) {
1488         // Variable assignment values may be enclosed in double or single quotes.
1489         return value.trim().replaceAll("[\"']", "");
1490     }
1491 
1492     private static String normalize(String value) {
1493         return value.toLowerCase(Locale.US).replaceAll("[^a-z0-9]+", "");
1494     }
1495 
1496     private static String normalizeArch(String value) {
1497         value = normalize(value);
1498         if (value.matches("^(x8664|amd64|ia32e|em64t|x64)$")) {
1499             return "x86_64";
1500         }
1501         if (value.matches("^(x8632|x86|i[3-6]86|ia32|x32)$")) {
1502             return "x86_32";
1503         }
1504         if (value.matches("^(ia64|itanium64)$")) {
1505             return "itanium_64";
1506         }
1507         if (value.matches("^(sparc|sparc32)$")) {
1508             return "sparc_32";
1509         }
1510         if (value.matches("^(sparcv9|sparc64)$")) {
1511             return "sparc_64";
1512         }
1513         if (value.matches("^(arm|arm32)$")) {
1514             return "arm_32";
1515         }
1516         if ("aarch64".equals(value)) {
1517             return "aarch_64";
1518         }
1519         if ("riscv64".equals(value)) {
1520             // os.detected.arch is riscv64 for RISC-V, no underscore
1521             return "riscv64";
1522         }
1523         if (value.matches("^(ppc|ppc32)$")) {
1524             return "ppc_32";
1525         }
1526         if ("ppc64".equals(value)) {
1527             return "ppc_64";
1528         }
1529         if ("ppc64le".equals(value)) {
1530             return "ppcle_64";
1531         }
1532         if ("s390".equals(value)) {
1533             return "s390_32";
1534         }
1535         if ("s390x".equals(value)) {
1536             return "s390_64";
1537         }
1538         if ("loongarch64".equals(value)) {
1539             return "loongarch_64";
1540         }
1541 
1542         return "unknown";
1543     }
1544 
1545     private static String normalizeOs(String value) {
1546         value = normalize(value);
1547         if (value.startsWith("aix")) {
1548             return "aix";
1549         }
1550         if (value.startsWith("hpux")) {
1551             return "hpux";
1552         }
1553         if (value.startsWith("os400")) {
1554             // Avoid the names such as os4000
1555             if (value.length() <= 5 || !Character.isDigit(value.charAt(5))) {
1556                 return "os400";
1557             }
1558         }
1559         if (value.startsWith("linux")) {
1560             return "linux";
1561         }
1562         if (value.startsWith("macosx") || value.startsWith("osx") || value.startsWith("darwin")) {
1563             return "osx";
1564         }
1565         if (value.startsWith("freebsd")) {
1566             return "freebsd";
1567         }
1568         if (value.startsWith("openbsd")) {
1569             return "openbsd";
1570         }
1571         if (value.startsWith("netbsd")) {
1572             return "netbsd";
1573         }
1574         if (value.startsWith("solaris") || value.startsWith("sunos")) {
1575             return "sunos";
1576         }
1577         if (value.startsWith("windows")) {
1578             return "windows";
1579         }
1580 
1581         return "unknown";
1582     }
1583 
1584     private PlatformDependent() {
1585         // only static method supported
1586     }
1587 }