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         // Calling malloc with capacity of 0 may return a null ptr or a memory address that can be used.
431         // Just use 1 to make it safe to use in all cases:
432         // See: http://pubs.opengroup.org/onlinepubs/009695399/functions/malloc.html
433         return newDirectBuffer(UNSAFE.allocateMemory(Math.max(1, capacity)), capacity);
434     }
435 
436     static boolean hasAllocateArrayMethod() {
437         return ALLOCATE_ARRAY_METHOD != null;
438     }
439 
440     static byte[] allocateUninitializedArray(int size) {
441         try {
442             return (byte[]) ALLOCATE_ARRAY_METHOD.invoke(INTERNAL_UNSAFE, byte.class, size);
443         } catch (IllegalAccessException e) {
444             throw new Error(e);
445         } catch (InvocationTargetException e) {
446             throw new Error(e);
447         }
448     }
449 
450     static ByteBuffer newDirectBuffer(long address, int capacity) {
451         ObjectUtil.checkPositiveOrZero(capacity, "capacity");
452 
453         try {
454             return (ByteBuffer) DIRECT_BUFFER_CONSTRUCTOR.newInstance(address, capacity);
455         } catch (Throwable cause) {
456             // Not expected to ever throw!
457             if (cause instanceof Error) {
458                 throw (Error) cause;
459             }
460             throw new Error(cause);
461         }
462     }
463 
464     static long directBufferAddress(ByteBuffer buffer) {
465         return getLong(buffer, ADDRESS_FIELD_OFFSET);
466     }
467 
468     static long byteArrayBaseOffset() {
469         return BYTE_ARRAY_BASE_OFFSET;
470     }
471 
472     static Object getObject(Object object, long fieldOffset) {
473         return UNSAFE.getObject(object, fieldOffset);
474     }
475 
476     static int getInt(Object object, long fieldOffset) {
477         return UNSAFE.getInt(object, fieldOffset);
478     }
479 
480     private static long getLong(Object object, long fieldOffset) {
481         return UNSAFE.getLong(object, fieldOffset);
482     }
483 
484     static long objectFieldOffset(Field field) {
485         return UNSAFE.objectFieldOffset(field);
486     }
487 
488     static byte getByte(long address) {
489         return UNSAFE.getByte(address);
490     }
491 
492     static short getShort(long address) {
493         return UNSAFE.getShort(address);
494     }
495 
496     static int getInt(long address) {
497         return UNSAFE.getInt(address);
498     }
499 
500     static long getLong(long address) {
501         return UNSAFE.getLong(address);
502     }
503 
504     static byte getByte(byte[] data, int index) {
505         return UNSAFE.getByte(data, BYTE_ARRAY_BASE_OFFSET + index);
506     }
507 
508     static short getShort(byte[] data, int index) {
509         return UNSAFE.getShort(data, BYTE_ARRAY_BASE_OFFSET + index);
510     }
511 
512     static int getInt(byte[] data, int index) {
513         return UNSAFE.getInt(data, BYTE_ARRAY_BASE_OFFSET + index);
514     }
515 
516     static long getLong(byte[] data, int index) {
517         return UNSAFE.getLong(data, BYTE_ARRAY_BASE_OFFSET + index);
518     }
519 
520     static void putByte(long address, byte value) {
521         UNSAFE.putByte(address, value);
522     }
523 
524     static void putShort(long address, short value) {
525         UNSAFE.putShort(address, value);
526     }
527 
528     static void putInt(long address, int value) {
529         UNSAFE.putInt(address, value);
530     }
531 
532     static void putLong(long address, long value) {
533         UNSAFE.putLong(address, value);
534     }
535 
536     static void putByte(byte[] data, int index, byte value) {
537         UNSAFE.putByte(data, BYTE_ARRAY_BASE_OFFSET + index, value);
538     }
539 
540     static void putShort(byte[] data, int index, short value) {
541         UNSAFE.putShort(data, BYTE_ARRAY_BASE_OFFSET + index, value);
542     }
543 
544     static void putInt(byte[] data, int index, int value) {
545         UNSAFE.putInt(data, BYTE_ARRAY_BASE_OFFSET + index, value);
546     }
547 
548     static void putLong(byte[] data, int index, long value) {
549         UNSAFE.putLong(data, BYTE_ARRAY_BASE_OFFSET + index, value);
550     }
551 
552     static void copyMemory(long srcAddr, long dstAddr, long length) {
553         //UNSAFE.copyMemory(srcAddr, dstAddr, length);
554         while (length > 0) {
555             long size = Math.min(length, UNSAFE_COPY_THRESHOLD);
556             UNSAFE.copyMemory(srcAddr, dstAddr, size);
557             length -= size;
558             srcAddr += size;
559             dstAddr += size;
560         }
561     }
562 
563     static void copyMemory(Object src, long srcOffset, Object dst, long dstOffset, long length) {
564         //UNSAFE.copyMemory(src, srcOffset, dst, dstOffset, length);
565         while (length > 0) {
566             long size = Math.min(length, UNSAFE_COPY_THRESHOLD);
567             UNSAFE.copyMemory(src, srcOffset, dst, dstOffset, size);
568             length -= size;
569             srcOffset += size;
570             dstOffset += size;
571         }
572     }
573 
574     static void setMemory(long address, long bytes, byte value) {
575         UNSAFE.setMemory(address, bytes, value);
576     }
577 
578     static void setMemory(Object o, long offset, long bytes, byte value) {
579         UNSAFE.setMemory(o, offset, bytes, value);
580     }
581 
582     static boolean equals(byte[] bytes1, int startPos1, byte[] bytes2, int startPos2, int length) {
583         if (length <= 0) {
584             return true;
585         }
586         final long baseOffset1 = BYTE_ARRAY_BASE_OFFSET + startPos1;
587         final long baseOffset2 = BYTE_ARRAY_BASE_OFFSET + startPos2;
588         int remainingBytes = length & 7;
589         final long end = baseOffset1 + remainingBytes;
590         for (long i = baseOffset1 - 8 + length, j = baseOffset2 - 8 + length; i >= end; i -= 8, j -= 8) {
591             if (UNSAFE.getLong(bytes1, i) != UNSAFE.getLong(bytes2, j)) {
592                 return false;
593             }
594         }
595 
596         if (remainingBytes >= 4) {
597             remainingBytes -= 4;
598             if (UNSAFE.getInt(bytes1, baseOffset1 + remainingBytes) !=
599                 UNSAFE.getInt(bytes2, baseOffset2 + remainingBytes)) {
600                 return false;
601             }
602         }
603         if (remainingBytes >= 2) {
604             return UNSAFE.getChar(bytes1, baseOffset1) == UNSAFE.getChar(bytes2, baseOffset2) &&
605                    (remainingBytes == 2 || bytes1[startPos1 + 2] == bytes2[startPos2 + 2]);
606         }
607         return bytes1[startPos1] == bytes2[startPos2];
608     }
609 
610     static int equalsConstantTime(byte[] bytes1, int startPos1, byte[] bytes2, int startPos2, int length) {
611         long result = 0;
612         final long baseOffset1 = BYTE_ARRAY_BASE_OFFSET + startPos1;
613         final long baseOffset2 = BYTE_ARRAY_BASE_OFFSET + startPos2;
614         final int remainingBytes = length & 7;
615         final long end = baseOffset1 + remainingBytes;
616         for (long i = baseOffset1 - 8 + length, j = baseOffset2 - 8 + length; i >= end; i -= 8, j -= 8) {
617             result |= UNSAFE.getLong(bytes1, i) ^ UNSAFE.getLong(bytes2, j);
618         }
619         switch (remainingBytes) {
620             case 7:
621                 return ConstantTimeUtils.equalsConstantTime(result |
622                         (UNSAFE.getInt(bytes1, baseOffset1 + 3) ^ UNSAFE.getInt(bytes2, baseOffset2 + 3)) |
623                         (UNSAFE.getChar(bytes1, baseOffset1 + 1) ^ UNSAFE.getChar(bytes2, baseOffset2 + 1)) |
624                         (UNSAFE.getByte(bytes1, baseOffset1) ^ UNSAFE.getByte(bytes2, baseOffset2)), 0);
625             case 6:
626                 return ConstantTimeUtils.equalsConstantTime(result |
627                         (UNSAFE.getInt(bytes1, baseOffset1 + 2) ^ UNSAFE.getInt(bytes2, baseOffset2 + 2)) |
628                         (UNSAFE.getChar(bytes1, baseOffset1) ^ UNSAFE.getChar(bytes2, baseOffset2)), 0);
629             case 5:
630                 return ConstantTimeUtils.equalsConstantTime(result |
631                         (UNSAFE.getInt(bytes1, baseOffset1 + 1) ^ UNSAFE.getInt(bytes2, baseOffset2 + 1)) |
632                         (UNSAFE.getByte(bytes1, baseOffset1) ^ UNSAFE.getByte(bytes2, baseOffset2)), 0);
633             case 4:
634                 return ConstantTimeUtils.equalsConstantTime(result |
635                         (UNSAFE.getInt(bytes1, baseOffset1) ^ UNSAFE.getInt(bytes2, baseOffset2)), 0);
636             case 3:
637                 return ConstantTimeUtils.equalsConstantTime(result |
638                         (UNSAFE.getChar(bytes1, baseOffset1 + 1) ^ UNSAFE.getChar(bytes2, baseOffset2 + 1)) |
639                         (UNSAFE.getByte(bytes1, baseOffset1) ^ UNSAFE.getByte(bytes2, baseOffset2)), 0);
640             case 2:
641                 return ConstantTimeUtils.equalsConstantTime(result |
642                         (UNSAFE.getChar(bytes1, baseOffset1) ^ UNSAFE.getChar(bytes2, baseOffset2)), 0);
643             case 1:
644                 return ConstantTimeUtils.equalsConstantTime(result |
645                         (UNSAFE.getByte(bytes1, baseOffset1) ^ UNSAFE.getByte(bytes2, baseOffset2)), 0);
646             default:
647                 return ConstantTimeUtils.equalsConstantTime(result, 0);
648         }
649     }
650 
651     static boolean isZero(byte[] bytes, int startPos, int length) {
652         if (length <= 0) {
653             return true;
654         }
655         final long baseOffset = BYTE_ARRAY_BASE_OFFSET + startPos;
656         int remainingBytes = length & 7;
657         final long end = baseOffset + remainingBytes;
658         for (long i = baseOffset - 8 + length; i >= end; i -= 8) {
659             if (UNSAFE.getLong(bytes, i) != 0) {
660                 return false;
661             }
662         }
663 
664         if (remainingBytes >= 4) {
665             remainingBytes -= 4;
666             if (UNSAFE.getInt(bytes, baseOffset + remainingBytes) != 0) {
667                 return false;
668             }
669         }
670         if (remainingBytes >= 2) {
671             return UNSAFE.getChar(bytes, baseOffset) == 0 &&
672                     (remainingBytes == 2 || bytes[startPos + 2] == 0);
673         }
674         return bytes[startPos] == 0;
675     }
676 
677     static int hashCodeAscii(byte[] bytes, int startPos, int length) {
678         int hash = HASH_CODE_ASCII_SEED;
679         final long baseOffset = BYTE_ARRAY_BASE_OFFSET + startPos;
680         final int remainingBytes = length & 7;
681         final long end = baseOffset + remainingBytes;
682         for (long i = baseOffset - 8 + length; i >= end; i -= 8) {
683             hash = hashCodeAsciiCompute(UNSAFE.getLong(bytes, i), hash);
684         }
685         switch(remainingBytes) {
686         case 7:
687             return ((hash * HASH_CODE_C1 + hashCodeAsciiSanitize(UNSAFE.getByte(bytes, baseOffset)))
688                           * HASH_CODE_C2 + hashCodeAsciiSanitize(UNSAFE.getShort(bytes, baseOffset + 1)))
689                           * HASH_CODE_C1 + hashCodeAsciiSanitize(UNSAFE.getInt(bytes, baseOffset + 3));
690         case 6:
691             return (hash * HASH_CODE_C1 + hashCodeAsciiSanitize(UNSAFE.getShort(bytes, baseOffset)))
692                          * HASH_CODE_C2 + hashCodeAsciiSanitize(UNSAFE.getInt(bytes, baseOffset + 2));
693         case 5:
694             return (hash * HASH_CODE_C1 + hashCodeAsciiSanitize(UNSAFE.getByte(bytes, baseOffset)))
695                          * HASH_CODE_C2 + hashCodeAsciiSanitize(UNSAFE.getInt(bytes, baseOffset + 1));
696         case 4:
697             return hash * HASH_CODE_C1 + hashCodeAsciiSanitize(UNSAFE.getInt(bytes, baseOffset));
698         case 3:
699             return (hash * HASH_CODE_C1 + hashCodeAsciiSanitize(UNSAFE.getByte(bytes, baseOffset)))
700                          * HASH_CODE_C2 + hashCodeAsciiSanitize(UNSAFE.getShort(bytes, baseOffset + 1));
701         case 2:
702             return hash * HASH_CODE_C1 + hashCodeAsciiSanitize(UNSAFE.getShort(bytes, baseOffset));
703         case 1:
704             return hash * HASH_CODE_C1 + hashCodeAsciiSanitize(UNSAFE.getByte(bytes, baseOffset));
705         default:
706             return hash;
707         }
708     }
709 
710     static int hashCodeAsciiCompute(long value, int hash) {
711         // masking with 0x1f reduces the number of overall bits that impact the hash code but makes the hash
712         // code the same regardless of character case (upper case or lower case hash is the same).
713         return hash * HASH_CODE_C1 +
714                 // Low order int
715                 hashCodeAsciiSanitize((int) value) * HASH_CODE_C2 +
716                 // High order int
717                 (int) ((value & 0x1f1f1f1f00000000L) >>> 32);
718     }
719 
720     static int hashCodeAsciiSanitize(int value) {
721         return value & 0x1f1f1f1f;
722     }
723 
724     static int hashCodeAsciiSanitize(short value) {
725         return value & 0x1f1f;
726     }
727 
728     static int hashCodeAsciiSanitize(byte value) {
729         return value & 0x1f;
730     }
731 
732     static ClassLoader getClassLoader(final Class<?> clazz) {
733         if (System.getSecurityManager() == null) {
734             return clazz.getClassLoader();
735         } else {
736             return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
737                 @Override
738                 public ClassLoader run() {
739                     return clazz.getClassLoader();
740                 }
741             });
742         }
743     }
744 
745     static ClassLoader getContextClassLoader() {
746         if (System.getSecurityManager() == null) {
747             return Thread.currentThread().getContextClassLoader();
748         } else {
749             return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
750                 @Override
751                 public ClassLoader run() {
752                     return Thread.currentThread().getContextClassLoader();
753                 }
754             });
755         }
756     }
757 
758     static ClassLoader getSystemClassLoader() {
759         if (System.getSecurityManager() == null) {
760             return ClassLoader.getSystemClassLoader();
761         } else {
762             return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
763                 @Override
764                 public ClassLoader run() {
765                     return ClassLoader.getSystemClassLoader();
766                 }
767             });
768         }
769     }
770 
771     static int addressSize() {
772         return UNSAFE.addressSize();
773     }
774 
775     static long allocateMemory(long size) {
776         return UNSAFE.allocateMemory(size);
777     }
778 
779     static void freeMemory(long address) {
780         UNSAFE.freeMemory(address);
781     }
782 
783     static long reallocateMemory(long address, long newSize) {
784         return UNSAFE.reallocateMemory(address, newSize);
785     }
786 
787     static boolean isAndroid() {
788         return IS_ANDROID;
789     }
790 
791     private static boolean isAndroid0() {
792         // Idea: Sometimes java binaries include Android classes on the classpath, even if it isn't actually Android.
793         // Rather than check if certain classes are present, just check the VM, which is tied to the JDK.
794 
795         // Optional improvement: check if `android.os.Build.VERSION` is >= 24. On later versions of Android, the
796         // OpenJDK is used, which means `Unsafe` will actually work as expected.
797 
798         // Android sets this property to Dalvik, regardless of whether it actually is.
799         String vmName = SystemPropertyUtil.get("java.vm.name");
800         boolean isAndroid = "Dalvik".equals(vmName);
801         if (isAndroid) {
802             logger.debug("Platform: Android");
803         }
804         return isAndroid;
805     }
806 
807     private static boolean explicitTryReflectionSetAccessible0() {
808         // we disable reflective access
809         return SystemPropertyUtil.getBoolean("io.netty.tryReflectionSetAccessible", javaVersion() < 9);
810     }
811 
812     static boolean isExplicitTryReflectionSetAccessible() {
813         return IS_EXPLICIT_TRY_REFLECTION_SET_ACCESSIBLE;
814     }
815 
816     static int javaVersion() {
817         return JAVA_VERSION;
818     }
819 
820     private static int javaVersion0() {
821         final int majorVersion;
822 
823         if (isAndroid0()) {
824             majorVersion = 6;
825         } else {
826             majorVersion = majorVersionFromJavaSpecificationVersion();
827         }
828 
829         logger.debug("Java version: {}", majorVersion);
830 
831         return majorVersion;
832     }
833 
834     // Package-private for testing only
835     static int majorVersionFromJavaSpecificationVersion() {
836         return majorVersion(SystemPropertyUtil.get("java.specification.version", "1.6"));
837     }
838 
839     // Package-private for testing only
840     static int majorVersion(final String javaSpecVersion) {
841         final String[] components = javaSpecVersion.split("\\.");
842         final int[] version = new int[components.length];
843         for (int i = 0; i < components.length; i++) {
844             version[i] = Integer.parseInt(components[i]);
845         }
846 
847         if (version[0] == 1) {
848             assert version[1] >= 6;
849             return version[1];
850         } else {
851             return version[0];
852         }
853     }
854 
855     private PlatformDependent0() {
856     }
857 }