View Javadoc
1   /*
2    * Copyright 2013 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    *   http://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 sun.misc.Unsafe;
21  
22  import java.lang.reflect.Constructor;
23  import java.lang.reflect.Field;
24  import java.lang.reflect.InvocationTargetException;
25  import java.lang.reflect.Method;
26  import java.nio.Buffer;
27  import java.nio.ByteBuffer;
28  import java.security.AccessController;
29  import java.security.PrivilegedAction;
30  
31  import static io.netty.util.internal.ObjectUtil.checkNotNull;
32  
33  /**
34   * The {@link PlatformDependent} operations which requires access to {@code sun.misc.*}.
35   */
36  final class PlatformDependent0 {
37  
38      private static final InternalLogger logger = InternalLoggerFactory.getInstance(PlatformDependent0.class);
39      private static final long ADDRESS_FIELD_OFFSET;
40      private static final long BYTE_ARRAY_BASE_OFFSET;
41      private static final Constructor<?> DIRECT_BUFFER_CONSTRUCTOR;
42      private static final Throwable EXPLICIT_NO_UNSAFE_CAUSE = explicitNoUnsafeCause0();
43      private static final Method ALLOCATE_ARRAY_METHOD;
44      private static final int JAVA_VERSION = javaVersion0();
45      private static final boolean IS_ANDROID = isAndroid0();
46  
47      private static final Throwable UNSAFE_UNAVAILABILITY_CAUSE;
48      private static final Object INTERNAL_UNSAFE;
49      private static final boolean IS_EXPLICIT_TRY_REFLECTION_SET_ACCESSIBLE = explicitTryReflectionSetAccessible0();
50  
51      static final Unsafe UNSAFE;
52  
53      // constants borrowed from murmur3
54      static final int HASH_CODE_ASCII_SEED = 0xc2b2ae35;
55      static final int HASH_CODE_C1 = 0xcc9e2d51;
56      static final int HASH_CODE_C2 = 0x1b873593;
57  
58      /**
59       * Limits the number of bytes to copy per {@link Unsafe#copyMemory(long, long, long)} to allow safepoint polling
60       * during a large copy.
61       */
62      private static final long UNSAFE_COPY_THRESHOLD = 1024L * 1024L;
63  
64      private static final boolean UNALIGNED;
65  
66      static {
67          final ByteBuffer direct;
68          Field addressField = null;
69          Method allocateArrayMethod = null;
70          Throwable unsafeUnavailabilityCause = null;
71          Unsafe unsafe;
72          Object internalUnsafe = null;
73  
74          if ((unsafeUnavailabilityCause = EXPLICIT_NO_UNSAFE_CAUSE) != null) {
75              direct = null;
76              addressField = null;
77              unsafe = null;
78              internalUnsafe = null;
79          } else {
80              direct = ByteBuffer.allocateDirect(1);
81  
82              // attempt to access field Unsafe#theUnsafe
83              final Object maybeUnsafe = AccessController.doPrivileged(new PrivilegedAction<Object>() {
84                  @Override
85                  public Object run() {
86                      try {
87                          final Field unsafeField = Unsafe.class.getDeclaredField("theUnsafe");
88                          // We always want to try using Unsafe as the access still works on java9 as well and
89                          // we need it for out native-transports and many optimizations.
90                          Throwable cause = ReflectionUtil.trySetAccessible(unsafeField, false);
91                          if (cause != null) {
92                              return cause;
93                          }
94                          // the unsafe instance
95                          return unsafeField.get(null);
96                      } catch (NoSuchFieldException e) {
97                          return e;
98                      } catch (SecurityException e) {
99                          return e;
100                     } catch (IllegalAccessException e) {
101                         return e;
102                     } catch (NoClassDefFoundError e) {
103                         // Also catch NoClassDefFoundError in case someone uses for example OSGI and it made
104                         // Unsafe unloadable.
105                         return e;
106                     }
107                 }
108             });
109 
110             // the conditional check here can not be replaced with checking that maybeUnsafe
111             // is an instanceof Unsafe and reversing the if and else blocks; this is because an
112             // instanceof check against Unsafe will trigger a class load and we might not have
113             // the runtime permission accessClassInPackage.sun.misc
114             if (maybeUnsafe instanceof Throwable) {
115                 unsafe = null;
116                 unsafeUnavailabilityCause = (Throwable) maybeUnsafe;
117                 logger.debug("sun.misc.Unsafe.theUnsafe: unavailable", (Throwable) maybeUnsafe);
118             } else {
119                 unsafe = (Unsafe) maybeUnsafe;
120                 logger.debug("sun.misc.Unsafe.theUnsafe: available");
121             }
122 
123             // ensure the unsafe supports all necessary methods to work around the mistake in the latest OpenJDK
124             // https://github.com/netty/netty/issues/1061
125             // http://www.mail-archive.com/[email protected]/msg00698.html
126             if (unsafe != null) {
127                 final Unsafe finalUnsafe = unsafe;
128                 final Object maybeException = AccessController.doPrivileged(new PrivilegedAction<Object>() {
129                     @Override
130                     public Object run() {
131                         try {
132                             finalUnsafe.getClass().getDeclaredMethod(
133                                     "copyMemory", Object.class, long.class, Object.class, long.class, long.class);
134                             return null;
135                         } catch (NoSuchMethodException e) {
136                             return e;
137                         } catch (SecurityException e) {
138                             return e;
139                         }
140                     }
141                 });
142 
143                 if (maybeException == null) {
144                     logger.debug("sun.misc.Unsafe.copyMemory: available");
145                 } else {
146                     // Unsafe.copyMemory(Object, long, Object, long, long) unavailable.
147                     unsafe = null;
148                     unsafeUnavailabilityCause = (Throwable) maybeException;
149                     logger.debug("sun.misc.Unsafe.copyMemory: unavailable", (Throwable) maybeException);
150                 }
151             }
152 
153             if (unsafe != null) {
154                 final Unsafe finalUnsafe = unsafe;
155 
156                 // attempt to access field Buffer#address
157                 final Object maybeAddressField = AccessController.doPrivileged(new PrivilegedAction<Object>() {
158                     @Override
159                     public Object run() {
160                         try {
161                             final Field field = Buffer.class.getDeclaredField("address");
162                             // Use Unsafe to read value of the address field. This way it will not fail on JDK9+ which
163                             // will forbid changing the access level via reflection.
164                             final long offset = finalUnsafe.objectFieldOffset(field);
165                             final long address = finalUnsafe.getLong(direct, offset);
166 
167                             // if direct really is a direct buffer, address will be non-zero
168                             if (address == 0) {
169                                 return null;
170                             }
171                             return field;
172                         } catch (NoSuchFieldException e) {
173                             return e;
174                         } catch (SecurityException e) {
175                             return e;
176                         }
177                     }
178                 });
179 
180                 if (maybeAddressField instanceof Field) {
181                     addressField = (Field) maybeAddressField;
182                     logger.debug("java.nio.Buffer.address: available");
183                 } else {
184                     unsafeUnavailabilityCause = (Throwable) maybeAddressField;
185                     logger.debug("java.nio.Buffer.address: unavailable", (Throwable) maybeAddressField);
186 
187                     // If we cannot access the address of a direct buffer, there's no point of using unsafe.
188                     // Let's just pretend unsafe is unavailable for overall simplicity.
189                     unsafe = null;
190                 }
191             }
192 
193             if (unsafe != null) {
194                 // There are assumptions made where ever BYTE_ARRAY_BASE_OFFSET is used (equals, hashCodeAscii, and
195                 // primitive accessors) that arrayIndexScale == 1, and results are undefined if this is not the case.
196                 long byteArrayIndexScale = unsafe.arrayIndexScale(byte[].class);
197                 if (byteArrayIndexScale != 1) {
198                     logger.debug("unsafe.arrayIndexScale is {} (expected: 1). Not using unsafe.", byteArrayIndexScale);
199                     unsafeUnavailabilityCause = new UnsupportedOperationException("Unexpected unsafe.arrayIndexScale");
200                     unsafe = null;
201                 }
202             }
203         }
204         UNSAFE_UNAVAILABILITY_CAUSE = unsafeUnavailabilityCause;
205         UNSAFE = unsafe;
206 
207         if (unsafe == null) {
208             ADDRESS_FIELD_OFFSET = -1;
209             BYTE_ARRAY_BASE_OFFSET = -1;
210             UNALIGNED = false;
211             DIRECT_BUFFER_CONSTRUCTOR = null;
212             ALLOCATE_ARRAY_METHOD = null;
213         } else {
214             Constructor<?> directBufferConstructor;
215             long address = -1;
216             try {
217                 final Object maybeDirectBufferConstructor =
218                         AccessController.doPrivileged(new PrivilegedAction<Object>() {
219                             @Override
220                             public Object run() {
221                                 try {
222                                     final Constructor<?> constructor =
223                                             direct.getClass().getDeclaredConstructor(long.class, int.class);
224                                     Throwable cause = ReflectionUtil.trySetAccessible(constructor, true);
225                                     if (cause != null) {
226                                         return cause;
227                                     }
228                                     return constructor;
229                                 } catch (NoSuchMethodException e) {
230                                     return e;
231                                 } catch (SecurityException e) {
232                                     return e;
233                                 }
234                             }
235                         });
236 
237                 if (maybeDirectBufferConstructor instanceof Constructor<?>) {
238                     address = UNSAFE.allocateMemory(1);
239                     // try to use the constructor now
240                     try {
241                         ((Constructor<?>) maybeDirectBufferConstructor).newInstance(address, 1);
242                         directBufferConstructor = (Constructor<?>) maybeDirectBufferConstructor;
243                         logger.debug("direct buffer constructor: available");
244                     } catch (InstantiationException e) {
245                         directBufferConstructor = null;
246                     } catch (IllegalAccessException e) {
247                         directBufferConstructor = null;
248                     } catch (InvocationTargetException e) {
249                         directBufferConstructor = null;
250                     }
251                 } else {
252                     logger.debug(
253                             "direct buffer constructor: unavailable",
254                             (Throwable) maybeDirectBufferConstructor);
255                     directBufferConstructor = null;
256                 }
257             } finally {
258                 if (address != -1) {
259                     UNSAFE.freeMemory(address);
260                 }
261             }
262             DIRECT_BUFFER_CONSTRUCTOR = directBufferConstructor;
263             ADDRESS_FIELD_OFFSET = objectFieldOffset(addressField);
264             BYTE_ARRAY_BASE_OFFSET = UNSAFE.arrayBaseOffset(byte[].class);
265             boolean unaligned;
266             Object maybeUnaligned = AccessController.doPrivileged(new PrivilegedAction<Object>() {
267                 @Override
268                 public Object run() {
269                     try {
270                         Class<?> bitsClass =
271                                 Class.forName("java.nio.Bits", false, getSystemClassLoader());
272                         Method unalignedMethod = bitsClass.getDeclaredMethod("unaligned");
273                         Throwable cause = ReflectionUtil.trySetAccessible(unalignedMethod, true);
274                         if (cause != null) {
275                             return cause;
276                         }
277                         return unalignedMethod.invoke(null);
278                     } catch (NoSuchMethodException e) {
279                         return e;
280                     } catch (SecurityException e) {
281                         return e;
282                     } catch (IllegalAccessException e) {
283                         return e;
284                     } catch (ClassNotFoundException e) {
285                         return e;
286                     } catch (InvocationTargetException e) {
287                         return e;
288                     }
289                 }
290             });
291 
292             if (maybeUnaligned instanceof Boolean) {
293                 unaligned = (Boolean) maybeUnaligned;
294                 logger.debug("java.nio.Bits.unaligned: available, {}", unaligned);
295             } else {
296                 String arch = SystemPropertyUtil.get("os.arch", "");
297                 //noinspection DynamicRegexReplaceableByCompiledPattern
298                 unaligned = arch.matches("^(i[3-6]86|x86(_64)?|x64|amd64)$");
299                 Throwable t = (Throwable) maybeUnaligned;
300                 logger.debug("java.nio.Bits.unaligned: unavailable {}", unaligned, t);
301             }
302 
303             UNALIGNED = unaligned;
304 
305             if (javaVersion() >= 9) {
306                 Object maybeException = AccessController.doPrivileged(new PrivilegedAction<Object>() {
307                     @Override
308                     public Object run() {
309                         try {
310                             // Java9 has jdk.internal.misc.Unsafe and not all methods are propagated to
311                             // sun.misc.Unsafe
312                             Class<?> internalUnsafeClass = getClassLoader(PlatformDependent0.class)
313                                     .loadClass("jdk.internal.misc.Unsafe");
314                             Method method = internalUnsafeClass.getDeclaredMethod("getUnsafe");
315                             return method.invoke(null);
316                         } catch (Throwable e) {
317                             return e;
318                         }
319                     }
320                 });
321                 if (!(maybeException instanceof Throwable)) {
322                     internalUnsafe = maybeException;
323                     final Object finalInternalUnsafe = internalUnsafe;
324                     maybeException = AccessController.doPrivileged(new PrivilegedAction<Object>() {
325                         @Override
326                         public Object run() {
327                             try {
328                                 return finalInternalUnsafe.getClass().getDeclaredMethod(
329                                         "allocateUninitializedArray", Class.class, int.class);
330                             } catch (NoSuchMethodException e) {
331                                 return e;
332                             } catch (SecurityException e) {
333                                 return e;
334                             }
335                         }
336                     });
337 
338                     if (maybeException instanceof Method) {
339                         try {
340                             Method m = (Method) maybeException;
341                             byte[] bytes = (byte[]) m.invoke(finalInternalUnsafe, byte.class, 8);
342                             assert bytes.length == 8;
343                             allocateArrayMethod = m;
344                         } catch (IllegalAccessException e) {
345                             maybeException = e;
346                         } catch (InvocationTargetException e) {
347                             maybeException = e;
348                         }
349                     }
350                 }
351 
352                 if (maybeException instanceof Throwable) {
353                     logger.debug("jdk.internal.misc.Unsafe.allocateUninitializedArray(int): unavailable",
354                             (Throwable) maybeException);
355                 } else {
356                     logger.debug("jdk.internal.misc.Unsafe.allocateUninitializedArray(int): available");
357                 }
358             } else {
359                 logger.debug("jdk.internal.misc.Unsafe.allocateUninitializedArray(int): unavailable prior to Java9");
360             }
361             ALLOCATE_ARRAY_METHOD = allocateArrayMethod;
362         }
363 
364         INTERNAL_UNSAFE = internalUnsafe;
365 
366         logger.debug("java.nio.DirectByteBuffer.<init>(long, int): {}",
367                 DIRECT_BUFFER_CONSTRUCTOR != null ? "available" : "unavailable");
368     }
369 
370     static boolean isExplicitNoUnsafe() {
371         return EXPLICIT_NO_UNSAFE_CAUSE == null;
372     }
373 
374     private static Throwable explicitNoUnsafeCause0() {
375         final boolean noUnsafe = SystemPropertyUtil.getBoolean("io.netty.noUnsafe", false);
376         logger.debug("-Dio.netty.noUnsafe: {}", noUnsafe);
377 
378         if (noUnsafe) {
379             logger.debug("sun.misc.Unsafe: unavailable (io.netty.noUnsafe)");
380             return new UnsupportedOperationException("sun.misc.Unsafe: unavailable (io.netty.noUnsafe)");
381         }
382 
383         // Legacy properties
384         String unsafePropName;
385         if (SystemPropertyUtil.contains("io.netty.tryUnsafe")) {
386             unsafePropName = "io.netty.tryUnsafe";
387         } else {
388             unsafePropName = "org.jboss.netty.tryUnsafe";
389         }
390 
391         if (!SystemPropertyUtil.getBoolean(unsafePropName, true)) {
392             String msg = "sun.misc.Unsafe: unavailable (" + unsafePropName + ")";
393             logger.debug(msg);
394             return new UnsupportedOperationException(msg);
395         }
396 
397         return null;
398     }
399 
400     static boolean isUnaligned() {
401         return UNALIGNED;
402     }
403 
404     static boolean hasUnsafe() {
405         return UNSAFE != null;
406     }
407 
408     static Throwable getUnsafeUnavailabilityCause() {
409         return UNSAFE_UNAVAILABILITY_CAUSE;
410     }
411 
412     static boolean unalignedAccess() {
413         return UNALIGNED;
414     }
415 
416     static void throwException(Throwable cause) {
417         // JVM has been observed to crash when passing a null argument. See https://github.com/netty/netty/issues/4131.
418         UNSAFE.throwException(checkNotNull(cause, "cause"));
419     }
420 
421     static boolean hasDirectBufferNoCleanerConstructor() {
422         return DIRECT_BUFFER_CONSTRUCTOR != null;
423     }
424 
425     static ByteBuffer reallocateDirectNoCleaner(ByteBuffer buffer, int capacity) {
426         return newDirectBuffer(UNSAFE.reallocateMemory(directBufferAddress(buffer), capacity), capacity);
427     }
428 
429     static ByteBuffer allocateDirectNoCleaner(int capacity) {
430         return newDirectBuffer(UNSAFE.allocateMemory(capacity), capacity);
431     }
432 
433     static boolean hasAllocateArrayMethod() {
434         return ALLOCATE_ARRAY_METHOD != null;
435     }
436 
437     static byte[] allocateUninitializedArray(int size) {
438         try {
439             return (byte[]) ALLOCATE_ARRAY_METHOD.invoke(INTERNAL_UNSAFE, byte.class, size);
440         } catch (IllegalAccessException e) {
441             throw new Error(e);
442         } catch (InvocationTargetException e) {
443             throw new Error(e);
444         }
445     }
446 
447     static ByteBuffer newDirectBuffer(long address, int capacity) {
448         ObjectUtil.checkPositiveOrZero(capacity, "capacity");
449 
450         try {
451             return (ByteBuffer) DIRECT_BUFFER_CONSTRUCTOR.newInstance(address, capacity);
452         } catch (Throwable cause) {
453             // Not expected to ever throw!
454             if (cause instanceof Error) {
455                 throw (Error) cause;
456             }
457             throw new Error(cause);
458         }
459     }
460 
461     static long directBufferAddress(ByteBuffer buffer) {
462         return getLong(buffer, ADDRESS_FIELD_OFFSET);
463     }
464 
465     static long byteArrayBaseOffset() {
466         return BYTE_ARRAY_BASE_OFFSET;
467     }
468 
469     static Object getObject(Object object, long fieldOffset) {
470         return UNSAFE.getObject(object, fieldOffset);
471     }
472 
473     static int getInt(Object object, long fieldOffset) {
474         return UNSAFE.getInt(object, fieldOffset);
475     }
476 
477     private static long getLong(Object object, long fieldOffset) {
478         return UNSAFE.getLong(object, fieldOffset);
479     }
480 
481     static long objectFieldOffset(Field field) {
482         return UNSAFE.objectFieldOffset(field);
483     }
484 
485     static byte getByte(long address) {
486         return UNSAFE.getByte(address);
487     }
488 
489     static short getShort(long address) {
490         return UNSAFE.getShort(address);
491     }
492 
493     static int getInt(long address) {
494         return UNSAFE.getInt(address);
495     }
496 
497     static long getLong(long address) {
498         return UNSAFE.getLong(address);
499     }
500 
501     static byte getByte(byte[] data, int index) {
502         return UNSAFE.getByte(data, BYTE_ARRAY_BASE_OFFSET + index);
503     }
504 
505     static short getShort(byte[] data, int index) {
506         return UNSAFE.getShort(data, BYTE_ARRAY_BASE_OFFSET + index);
507     }
508 
509     static int getInt(byte[] data, int index) {
510         return UNSAFE.getInt(data, BYTE_ARRAY_BASE_OFFSET + index);
511     }
512 
513     static long getLong(byte[] data, int index) {
514         return UNSAFE.getLong(data, BYTE_ARRAY_BASE_OFFSET + index);
515     }
516 
517     static void putByte(long address, byte value) {
518         UNSAFE.putByte(address, value);
519     }
520 
521     static void putShort(long address, short value) {
522         UNSAFE.putShort(address, value);
523     }
524 
525     static void putInt(long address, int value) {
526         UNSAFE.putInt(address, value);
527     }
528 
529     static void putLong(long address, long value) {
530         UNSAFE.putLong(address, value);
531     }
532 
533     static void putByte(byte[] data, int index, byte value) {
534         UNSAFE.putByte(data, BYTE_ARRAY_BASE_OFFSET + index, value);
535     }
536 
537     static void putShort(byte[] data, int index, short value) {
538         UNSAFE.putShort(data, BYTE_ARRAY_BASE_OFFSET + index, value);
539     }
540 
541     static void putInt(byte[] data, int index, int value) {
542         UNSAFE.putInt(data, BYTE_ARRAY_BASE_OFFSET + index, value);
543     }
544 
545     static void putLong(byte[] data, int index, long value) {
546         UNSAFE.putLong(data, BYTE_ARRAY_BASE_OFFSET + index, value);
547     }
548 
549     static void copyMemory(long srcAddr, long dstAddr, long length) {
550         //UNSAFE.copyMemory(srcAddr, dstAddr, length);
551         while (length > 0) {
552             long size = Math.min(length, UNSAFE_COPY_THRESHOLD);
553             UNSAFE.copyMemory(srcAddr, dstAddr, size);
554             length -= size;
555             srcAddr += size;
556             dstAddr += size;
557         }
558     }
559 
560     static void copyMemory(Object src, long srcOffset, Object dst, long dstOffset, long length) {
561         //UNSAFE.copyMemory(src, srcOffset, dst, dstOffset, length);
562         while (length > 0) {
563             long size = Math.min(length, UNSAFE_COPY_THRESHOLD);
564             UNSAFE.copyMemory(src, srcOffset, dst, dstOffset, size);
565             length -= size;
566             srcOffset += size;
567             dstOffset += size;
568         }
569     }
570 
571     static void setMemory(long address, long bytes, byte value) {
572         UNSAFE.setMemory(address, bytes, value);
573     }
574 
575     static void setMemory(Object o, long offset, long bytes, byte value) {
576         UNSAFE.setMemory(o, offset, bytes, value);
577     }
578 
579     static boolean equals(byte[] bytes1, int startPos1, byte[] bytes2, int startPos2, int length) {
580         if (length <= 0) {
581             return true;
582         }
583         final long baseOffset1 = BYTE_ARRAY_BASE_OFFSET + startPos1;
584         final long baseOffset2 = BYTE_ARRAY_BASE_OFFSET + startPos2;
585         int remainingBytes = length & 7;
586         final long end = baseOffset1 + remainingBytes;
587         for (long i = baseOffset1 - 8 + length, j = baseOffset2 - 8 + length; i >= end; i -= 8, j -= 8) {
588             if (UNSAFE.getLong(bytes1, i) != UNSAFE.getLong(bytes2, j)) {
589                 return false;
590             }
591         }
592 
593         if (remainingBytes >= 4) {
594             remainingBytes -= 4;
595             if (UNSAFE.getInt(bytes1, baseOffset1 + remainingBytes) !=
596                 UNSAFE.getInt(bytes2, baseOffset2 + remainingBytes)) {
597                 return false;
598             }
599         }
600         if (remainingBytes >= 2) {
601             return UNSAFE.getChar(bytes1, baseOffset1) == UNSAFE.getChar(bytes2, baseOffset2) &&
602                    (remainingBytes == 2 || bytes1[startPos1 + 2] == bytes2[startPos2 + 2]);
603         }
604         return bytes1[startPos1] == bytes2[startPos2];
605     }
606 
607     static int equalsConstantTime(byte[] bytes1, int startPos1, byte[] bytes2, int startPos2, int length) {
608         long result = 0;
609         final long baseOffset1 = BYTE_ARRAY_BASE_OFFSET + startPos1;
610         final long baseOffset2 = BYTE_ARRAY_BASE_OFFSET + startPos2;
611         final int remainingBytes = length & 7;
612         final long end = baseOffset1 + remainingBytes;
613         for (long i = baseOffset1 - 8 + length, j = baseOffset2 - 8 + length; i >= end; i -= 8, j -= 8) {
614             result |= UNSAFE.getLong(bytes1, i) ^ UNSAFE.getLong(bytes2, j);
615         }
616         switch (remainingBytes) {
617             case 7:
618                 return ConstantTimeUtils.equalsConstantTime(result |
619                         (UNSAFE.getInt(bytes1, baseOffset1 + 3) ^ UNSAFE.getInt(bytes2, baseOffset2 + 3)) |
620                         (UNSAFE.getChar(bytes1, baseOffset1 + 1) ^ UNSAFE.getChar(bytes2, baseOffset2 + 1)) |
621                         (UNSAFE.getByte(bytes1, baseOffset1) ^ UNSAFE.getByte(bytes2, baseOffset2)), 0);
622             case 6:
623                 return ConstantTimeUtils.equalsConstantTime(result |
624                         (UNSAFE.getInt(bytes1, baseOffset1 + 2) ^ UNSAFE.getInt(bytes2, baseOffset2 + 2)) |
625                         (UNSAFE.getChar(bytes1, baseOffset1) ^ UNSAFE.getChar(bytes2, baseOffset2)), 0);
626             case 5:
627                 return ConstantTimeUtils.equalsConstantTime(result |
628                         (UNSAFE.getInt(bytes1, baseOffset1 + 1) ^ UNSAFE.getInt(bytes2, baseOffset2 + 1)) |
629                         (UNSAFE.getByte(bytes1, baseOffset1) ^ UNSAFE.getByte(bytes2, baseOffset2)), 0);
630             case 4:
631                 return ConstantTimeUtils.equalsConstantTime(result |
632                         (UNSAFE.getInt(bytes1, baseOffset1) ^ UNSAFE.getInt(bytes2, baseOffset2)), 0);
633             case 3:
634                 return ConstantTimeUtils.equalsConstantTime(result |
635                         (UNSAFE.getChar(bytes1, baseOffset1 + 1) ^ UNSAFE.getChar(bytes2, baseOffset2 + 1)) |
636                         (UNSAFE.getByte(bytes1, baseOffset1) ^ UNSAFE.getByte(bytes2, baseOffset2)), 0);
637             case 2:
638                 return ConstantTimeUtils.equalsConstantTime(result |
639                         (UNSAFE.getChar(bytes1, baseOffset1) ^ UNSAFE.getChar(bytes2, baseOffset2)), 0);
640             case 1:
641                 return ConstantTimeUtils.equalsConstantTime(result |
642                         (UNSAFE.getByte(bytes1, baseOffset1) ^ UNSAFE.getByte(bytes2, baseOffset2)), 0);
643             default:
644                 return ConstantTimeUtils.equalsConstantTime(result, 0);
645         }
646     }
647 
648     static boolean isZero(byte[] bytes, int startPos, int length) {
649         if (length <= 0) {
650             return true;
651         }
652         final long baseOffset = BYTE_ARRAY_BASE_OFFSET + startPos;
653         int remainingBytes = length & 7;
654         final long end = baseOffset + remainingBytes;
655         for (long i = baseOffset - 8 + length; i >= end; i -= 8) {
656             if (UNSAFE.getLong(bytes, i) != 0) {
657                 return false;
658             }
659         }
660 
661         if (remainingBytes >= 4) {
662             remainingBytes -= 4;
663             if (UNSAFE.getInt(bytes, baseOffset + remainingBytes) != 0) {
664                 return false;
665             }
666         }
667         if (remainingBytes >= 2) {
668             return UNSAFE.getChar(bytes, baseOffset) == 0 &&
669                     (remainingBytes == 2 || bytes[startPos + 2] == 0);
670         }
671         return bytes[startPos] == 0;
672     }
673 
674     static int hashCodeAscii(byte[] bytes, int startPos, int length) {
675         int hash = HASH_CODE_ASCII_SEED;
676         final long baseOffset = BYTE_ARRAY_BASE_OFFSET + startPos;
677         final int remainingBytes = length & 7;
678         final long end = baseOffset + remainingBytes;
679         for (long i = baseOffset - 8 + length; i >= end; i -= 8) {
680             hash = hashCodeAsciiCompute(UNSAFE.getLong(bytes, i), hash);
681         }
682         switch(remainingBytes) {
683         case 7:
684             return ((hash * HASH_CODE_C1 + hashCodeAsciiSanitize(UNSAFE.getByte(bytes, baseOffset)))
685                           * HASH_CODE_C2 + hashCodeAsciiSanitize(UNSAFE.getShort(bytes, baseOffset + 1)))
686                           * HASH_CODE_C1 + hashCodeAsciiSanitize(UNSAFE.getInt(bytes, baseOffset + 3));
687         case 6:
688             return (hash * HASH_CODE_C1 + hashCodeAsciiSanitize(UNSAFE.getShort(bytes, baseOffset)))
689                          * HASH_CODE_C2 + hashCodeAsciiSanitize(UNSAFE.getInt(bytes, baseOffset + 2));
690         case 5:
691             return (hash * HASH_CODE_C1 + hashCodeAsciiSanitize(UNSAFE.getByte(bytes, baseOffset)))
692                          * HASH_CODE_C2 + hashCodeAsciiSanitize(UNSAFE.getInt(bytes, baseOffset + 1));
693         case 4:
694             return hash * HASH_CODE_C1 + hashCodeAsciiSanitize(UNSAFE.getInt(bytes, baseOffset));
695         case 3:
696             return (hash * HASH_CODE_C1 + hashCodeAsciiSanitize(UNSAFE.getByte(bytes, baseOffset)))
697                          * HASH_CODE_C2 + hashCodeAsciiSanitize(UNSAFE.getShort(bytes, baseOffset + 1));
698         case 2:
699             return hash * HASH_CODE_C1 + hashCodeAsciiSanitize(UNSAFE.getShort(bytes, baseOffset));
700         case 1:
701             return hash * HASH_CODE_C1 + hashCodeAsciiSanitize(UNSAFE.getByte(bytes, baseOffset));
702         default:
703             return hash;
704         }
705     }
706 
707     static int hashCodeAsciiCompute(long value, int hash) {
708         // masking with 0x1f reduces the number of overall bits that impact the hash code but makes the hash
709         // code the same regardless of character case (upper case or lower case hash is the same).
710         return hash * HASH_CODE_C1 +
711                 // Low order int
712                 hashCodeAsciiSanitize((int) value) * HASH_CODE_C2 +
713                 // High order int
714                 (int) ((value & 0x1f1f1f1f00000000L) >>> 32);
715     }
716 
717     static int hashCodeAsciiSanitize(int value) {
718         return value & 0x1f1f1f1f;
719     }
720 
721     static int hashCodeAsciiSanitize(short value) {
722         return value & 0x1f1f;
723     }
724 
725     static int hashCodeAsciiSanitize(byte value) {
726         return value & 0x1f;
727     }
728 
729     static ClassLoader getClassLoader(final Class<?> clazz) {
730         if (System.getSecurityManager() == null) {
731             return clazz.getClassLoader();
732         } else {
733             return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
734                 @Override
735                 public ClassLoader run() {
736                     return clazz.getClassLoader();
737                 }
738             });
739         }
740     }
741 
742     static ClassLoader getContextClassLoader() {
743         if (System.getSecurityManager() == null) {
744             return Thread.currentThread().getContextClassLoader();
745         } else {
746             return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
747                 @Override
748                 public ClassLoader run() {
749                     return Thread.currentThread().getContextClassLoader();
750                 }
751             });
752         }
753     }
754 
755     static ClassLoader getSystemClassLoader() {
756         if (System.getSecurityManager() == null) {
757             return ClassLoader.getSystemClassLoader();
758         } else {
759             return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
760                 @Override
761                 public ClassLoader run() {
762                     return ClassLoader.getSystemClassLoader();
763                 }
764             });
765         }
766     }
767 
768     static int addressSize() {
769         return UNSAFE.addressSize();
770     }
771 
772     static long allocateMemory(long size) {
773         return UNSAFE.allocateMemory(size);
774     }
775 
776     static void freeMemory(long address) {
777         UNSAFE.freeMemory(address);
778     }
779 
780     static long reallocateMemory(long address, long newSize) {
781         return UNSAFE.reallocateMemory(address, newSize);
782     }
783 
784     static boolean isAndroid() {
785         return IS_ANDROID;
786     }
787 
788     private static boolean isAndroid0() {
789         // Idea: Sometimes java binaries include Android classes on the classpath, even if it isn't actually Android.
790         // Rather than check if certain classes are present, just check the VM, which is tied to the JDK.
791 
792         // Optional improvement: check if `android.os.Build.VERSION` is >= 24. On later versions of Android, the
793         // OpenJDK is used, which means `Unsafe` will actually work as expected.
794 
795         // Android sets this property to Dalvik, regardless of whether it actually is.
796         String vmName = SystemPropertyUtil.get("java.vm.name");
797         boolean isAndroid = "Dalvik".equals(vmName);
798         if (isAndroid) {
799             logger.debug("Platform: Android");
800         }
801         return isAndroid;
802     }
803 
804     private static boolean explicitTryReflectionSetAccessible0() {
805         // we disable reflective access
806         return SystemPropertyUtil.getBoolean("io.netty.tryReflectionSetAccessible", javaVersion() < 9);
807     }
808 
809     static boolean isExplicitTryReflectionSetAccessible() {
810         return IS_EXPLICIT_TRY_REFLECTION_SET_ACCESSIBLE;
811     }
812 
813     static int javaVersion() {
814         return JAVA_VERSION;
815     }
816 
817     private static int javaVersion0() {
818         final int majorVersion;
819 
820         if (isAndroid0()) {
821             majorVersion = 6;
822         } else {
823             majorVersion = majorVersionFromJavaSpecificationVersion();
824         }
825 
826         logger.debug("Java version: {}", majorVersion);
827 
828         return majorVersion;
829     }
830 
831     // Package-private for testing only
832     static int majorVersionFromJavaSpecificationVersion() {
833         return majorVersion(SystemPropertyUtil.get("java.specification.version", "1.6"));
834     }
835 
836     // Package-private for testing only
837     static int majorVersion(final String javaSpecVersion) {
838         final String[] components = javaSpecVersion.split("\\.");
839         final int[] version = new int[components.length];
840         for (int i = 0; i < components.length; i++) {
841             version[i] = Integer.parseInt(components[i]);
842         }
843 
844         if (version[0] == 1) {
845             assert version[1] >= 6;
846             return version[1];
847         } else {
848             return version[0];
849         }
850     }
851 
852     private PlatformDependent0() {
853     }
854 }