1 /*
   2  * Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package jdk.internal.misc;
  27 
  28 import java.lang.reflect.Field;
  29 import java.security.ProtectionDomain;
  30 
  31 import jdk.internal.reflect.CallerSensitive;
  32 import jdk.internal.reflect.Reflection;
  33 import jdk.internal.misc.VM;
  34 
  35 import jdk.internal.HotSpotIntrinsicCandidate;
  36 import jdk.internal.vm.annotation.ForceInline;
  37 
  38 
  39 /**
  40  * A collection of methods for performing low-level, unsafe operations.
  41  * Although the class and all methods are public, use of this class is
  42  * limited because only trusted code can obtain instances of it.
  43  *
  44  * <em>Note:</em> It is the resposibility of the caller to make sure
  45  * arguments are checked before methods of this class are
  46  * called. While some rudimentary checks are performed on the input,
  47  * the checks are best effort and when performance is an overriding
  48  * priority, as when methods of this class are optimized by the
  49  * runtime compiler, some or all checks (if any) may be elided. Hence,
  50  * the caller must not rely on the checks and corresponding
  51  * exceptions!
  52  *
  53  * @author John R. Rose
  54  * @see #getUnsafe
  55  */
  56 
  57 public final class Unsafe {
  58 
  59     private static native void registerNatives();
  60     static {
  61         registerNatives();
  62         Reflection.registerMethodsToFilter(Unsafe.class, "getUnsafe");
  63     }
  64 
  65     private Unsafe() {}
  66 
  67     private static final Unsafe theUnsafe = new Unsafe();
  68 
  69     /**
  70      * Provides the caller with the capability of performing unsafe
  71      * operations.
  72      *
  73      * <p>The returned {@code Unsafe} object should be carefully guarded
  74      * by the caller, since it can be used to read and write data at arbitrary
  75      * memory addresses.  It must never be passed to untrusted code.
  76      *
  77      * <p>Most methods in this class are very low-level, and correspond to a
  78      * small number of hardware instructions (on typical machines).  Compilers
  79      * are encouraged to optimize these methods accordingly.
  80      *
  81      * <p>Here is a suggested idiom for using unsafe operations:
  82      *
  83      * <pre> {@code
  84      * class MyTrustedClass {
  85      *   private static final Unsafe unsafe = Unsafe.getUnsafe();
  86      *   ...
  87      *   private long myCountAddress = ...;
  88      *   public int getCount() { return unsafe.getByte(myCountAddress); }
  89      * }}</pre>
  90      *
  91      * (It may assist compilers to make the local variable {@code final}.)
  92      *
  93      * @throws  SecurityException  if a security manager exists and its
  94      *          {@code checkPropertiesAccess} method doesn't allow
  95      *          access to the system properties.
  96      */
  97     @CallerSensitive
  98     public static Unsafe getUnsafe() {
  99         Class<?> caller = Reflection.getCallerClass();
 100         if (!VM.isSystemDomainLoader(caller.getClassLoader()))
 101             throw new SecurityException("Unsafe");
 102         return theUnsafe;
 103     }
 104 
 105     /// peek and poke operations
 106     /// (compilers should optimize these to memory ops)
 107 
 108     // These work on object fields in the Java heap.
 109     // They will not work on elements of packed arrays.
 110 
 111     /**
 112      * Fetches a value from a given Java variable.
 113      * More specifically, fetches a field or array element within the given
 114      * object {@code o} at the given offset, or (if {@code o} is null)
 115      * from the memory address whose numerical value is the given offset.
 116      * <p>
 117      * The results are undefined unless one of the following cases is true:
 118      * <ul>
 119      * <li>The offset was obtained from {@link #objectFieldOffset} on
 120      * the {@link java.lang.reflect.Field} of some Java field and the object
 121      * referred to by {@code o} is of a class compatible with that
 122      * field's class.
 123      *
 124      * <li>The offset and object reference {@code o} (either null or
 125      * non-null) were both obtained via {@link #staticFieldOffset}
 126      * and {@link #staticFieldBase} (respectively) from the
 127      * reflective {@link Field} representation of some Java field.
 128      *
 129      * <li>The object referred to by {@code o} is an array, and the offset
 130      * is an integer of the form {@code B+N*S}, where {@code N} is
 131      * a valid index into the array, and {@code B} and {@code S} are
 132      * the values obtained by {@link #arrayBaseOffset} and {@link
 133      * #arrayIndexScale} (respectively) from the array's class.  The value
 134      * referred to is the {@code N}<em>th</em> element of the array.
 135      *
 136      * </ul>
 137      * <p>
 138      * If one of the above cases is true, the call references a specific Java
 139      * variable (field or array element).  However, the results are undefined
 140      * if that variable is not in fact of the type returned by this method.
 141      * <p>
 142      * This method refers to a variable by means of two parameters, and so
 143      * it provides (in effect) a <em>double-register</em> addressing mode
 144      * for Java variables.  When the object reference is null, this method
 145      * uses its offset as an absolute address.  This is similar in operation
 146      * to methods such as {@link #getInt(long)}, which provide (in effect) a
 147      * <em>single-register</em> addressing mode for non-Java variables.
 148      * However, because Java variables may have a different layout in memory
 149      * from non-Java variables, programmers should not assume that these
 150      * two addressing modes are ever equivalent.  Also, programmers should
 151      * remember that offsets from the double-register addressing mode cannot
 152      * be portably confused with longs used in the single-register addressing
 153      * mode.
 154      *
 155      * @param o Java heap object in which the variable resides, if any, else
 156      *        null
 157      * @param offset indication of where the variable resides in a Java heap
 158      *        object, if any, else a memory address locating the variable
 159      *        statically
 160      * @return the value fetched from the indicated Java variable
 161      * @throws RuntimeException No defined exceptions are thrown, not even
 162      *         {@link NullPointerException}
 163      */
 164     @HotSpotIntrinsicCandidate
 165     public native int getInt(Object o, long offset);
 166 
 167     /**
 168      * Stores a value into a given Java variable.
 169      * <p>
 170      * The first two parameters are interpreted exactly as with
 171      * {@link #getInt(Object, long)} to refer to a specific
 172      * Java variable (field or array element).  The given value
 173      * is stored into that variable.
 174      * <p>
 175      * The variable must be of the same type as the method
 176      * parameter {@code x}.
 177      *
 178      * @param o Java heap object in which the variable resides, if any, else
 179      *        null
 180      * @param offset indication of where the variable resides in a Java heap
 181      *        object, if any, else a memory address locating the variable
 182      *        statically
 183      * @param x the value to store into the indicated Java variable
 184      * @throws RuntimeException No defined exceptions are thrown, not even
 185      *         {@link NullPointerException}
 186      */
 187     @HotSpotIntrinsicCandidate
 188     public native void putInt(Object o, long offset, int x);
 189 
 190     /**
 191      * Fetches a reference value from a given Java variable.
 192      * @see #getInt(Object, long)
 193      */
 194     @HotSpotIntrinsicCandidate
 195     public native Object getObject(Object o, long offset);
 196 
 197     /**
 198      * Stores a reference value into a given Java variable.
 199      * <p>
 200      * Unless the reference {@code x} being stored is either null
 201      * or matches the field type, the results are undefined.
 202      * If the reference {@code o} is non-null, card marks or
 203      * other store barriers for that object (if the VM requires them)
 204      * are updated.
 205      * @see #putInt(Object, long, int)
 206      */
 207     @HotSpotIntrinsicCandidate
 208     public native void putObject(Object o, long offset, Object x);
 209 
 210     /** @see #getInt(Object, long) */
 211     @HotSpotIntrinsicCandidate
 212     public native boolean getBoolean(Object o, long offset);
 213 
 214     /** @see #putInt(Object, long, int) */
 215     @HotSpotIntrinsicCandidate
 216     public native void    putBoolean(Object o, long offset, boolean x);
 217 
 218     /** @see #getInt(Object, long) */
 219     @HotSpotIntrinsicCandidate
 220     public native byte    getByte(Object o, long offset);
 221 
 222     /** @see #putInt(Object, long, int) */
 223     @HotSpotIntrinsicCandidate
 224     public native void    putByte(Object o, long offset, byte x);
 225 
 226     /** @see #getInt(Object, long) */
 227     @HotSpotIntrinsicCandidate
 228     public native short   getShort(Object o, long offset);
 229 
 230     /** @see #putInt(Object, long, int) */
 231     @HotSpotIntrinsicCandidate
 232     public native void    putShort(Object o, long offset, short x);
 233 
 234     /** @see #getInt(Object, long) */
 235     @HotSpotIntrinsicCandidate
 236     public native char    getChar(Object o, long offset);
 237 
 238     /** @see #putInt(Object, long, int) */
 239     @HotSpotIntrinsicCandidate
 240     public native void    putChar(Object o, long offset, char x);
 241 
 242     /** @see #getInt(Object, long) */
 243     @HotSpotIntrinsicCandidate
 244     public native long    getLong(Object o, long offset);
 245 
 246     /** @see #putInt(Object, long, int) */
 247     @HotSpotIntrinsicCandidate
 248     public native void    putLong(Object o, long offset, long x);
 249 
 250     /** @see #getInt(Object, long) */
 251     @HotSpotIntrinsicCandidate
 252     public native float   getFloat(Object o, long offset);
 253 
 254     /** @see #putInt(Object, long, int) */
 255     @HotSpotIntrinsicCandidate
 256     public native void    putFloat(Object o, long offset, float x);
 257 
 258     /** @see #getInt(Object, long) */
 259     @HotSpotIntrinsicCandidate
 260     public native double  getDouble(Object o, long offset);
 261 
 262     /** @see #putInt(Object, long, int) */
 263     @HotSpotIntrinsicCandidate
 264     public native void    putDouble(Object o, long offset, double x);
 265 
 266     /**
 267      * Fetches a native pointer from a given memory address.  If the address is
 268      * zero, or does not point into a block obtained from {@link
 269      * #allocateMemory}, the results are undefined.
 270      *
 271      * <p>If the native pointer is less than 64 bits wide, it is extended as
 272      * an unsigned number to a Java long.  The pointer may be indexed by any
 273      * given byte offset, simply by adding that offset (as a simple integer) to
 274      * the long representing the pointer.  The number of bytes actually read
 275      * from the target address may be determined by consulting {@link
 276      * #addressSize}.
 277      *
 278      * @see #allocateMemory
 279      * @see #getInt(Object, long)
 280      */
 281     @ForceInline
 282     public long getAddress(Object o, long offset) {
 283         if (ADDRESS_SIZE == 4) {
 284             return Integer.toUnsignedLong(getInt(o, offset));
 285         } else {
 286             return getLong(o, offset);
 287         }
 288     }
 289 
 290     /**
 291      * Stores a native pointer into a given memory address.  If the address is
 292      * zero, or does not point into a block obtained from {@link
 293      * #allocateMemory}, the results are undefined.
 294      *
 295      * <p>The number of bytes actually written at the target address may be
 296      * determined by consulting {@link #addressSize}.
 297      *
 298      * @see #allocateMemory
 299      * @see #putInt(Object, long, int)
 300      */
 301     @ForceInline
 302     public void putAddress(Object o, long offset, long x) {
 303         if (ADDRESS_SIZE == 4) {
 304             putInt(o, offset, (int)x);
 305         } else {
 306             putLong(o, offset, x);
 307         }
 308     }
 309 
 310     // These read VM internal data.
 311 
 312     /**
 313      * Fetches an uncompressed reference value from a given native variable
 314      * ignoring the VM's compressed references mode.
 315      *
 316      * @param address a memory address locating the variable
 317      * @return the value fetched from the indicated native variable
 318      */
 319     public native Object getUncompressedObject(long address);
 320 
 321     /**
 322      * Fetches the {@link java.lang.Class} Java mirror for the given native
 323      * metaspace {@code Klass} pointer.
 324      *
 325      * @param metaspaceKlass a native metaspace {@code Klass} pointer
 326      * @return the {@link java.lang.Class} Java mirror
 327      */
 328     public native Class<?> getJavaMirror(long metaspaceKlass);
 329 
 330     /**
 331      * Fetches a native metaspace {@code Klass} pointer for the given Java
 332      * object.
 333      *
 334      * @param o Java heap object for which to fetch the class pointer
 335      * @return a native metaspace {@code Klass} pointer
 336      */
 337     public native long getKlassPointer(Object o);
 338 
 339     // These work on values in the C heap.
 340 
 341     /**
 342      * Fetches a value from a given memory address.  If the address is zero, or
 343      * does not point into a block obtained from {@link #allocateMemory}, the
 344      * results are undefined.
 345      *
 346      * @see #allocateMemory
 347      */
 348     @ForceInline
 349     public byte getByte(long address) {
 350         return getByte(null, address);
 351     }
 352 
 353     /**
 354      * Stores a value into a given memory address.  If the address is zero, or
 355      * does not point into a block obtained from {@link #allocateMemory}, the
 356      * results are undefined.
 357      *
 358      * @see #getByte(long)
 359      */
 360     @ForceInline
 361     public void putByte(long address, byte x) {
 362         putByte(null, address, x);
 363     }
 364 
 365     /** @see #getByte(long) */
 366     @ForceInline
 367     public short getShort(long address) {
 368         return getShort(null, address);
 369     }
 370 
 371     /** @see #putByte(long, byte) */
 372     @ForceInline
 373     public void putShort(long address, short x) {
 374         putShort(null, address, x);
 375     }
 376 
 377     /** @see #getByte(long) */
 378     @ForceInline
 379     public char getChar(long address) {
 380         return getChar(null, address);
 381     }
 382 
 383     /** @see #putByte(long, byte) */
 384     @ForceInline
 385     public void putChar(long address, char x) {
 386         putChar(null, address, x);
 387     }
 388 
 389     /** @see #getByte(long) */
 390     @ForceInline
 391     public int getInt(long address) {
 392         return getInt(null, address);
 393     }
 394 
 395     /** @see #putByte(long, byte) */
 396     @ForceInline
 397     public void putInt(long address, int x) {
 398         putInt(null, address, x);
 399     }
 400 
 401     /** @see #getByte(long) */
 402     @ForceInline
 403     public long getLong(long address) {
 404         return getLong(null, address);
 405     }
 406 
 407     /** @see #putByte(long, byte) */
 408     @ForceInline
 409     public void putLong(long address, long x) {
 410         putLong(null, address, x);
 411     }
 412 
 413     /** @see #getByte(long) */
 414     @ForceInline
 415     public float getFloat(long address) {
 416         return getFloat(null, address);
 417     }
 418 
 419     /** @see #putByte(long, byte) */
 420     @ForceInline
 421     public void putFloat(long address, float x) {
 422         putFloat(null, address, x);
 423     }
 424 
 425     /** @see #getByte(long) */
 426     @ForceInline
 427     public double getDouble(long address) {
 428         return getDouble(null, address);
 429     }
 430 
 431     /** @see #putByte(long, byte) */
 432     @ForceInline
 433     public void putDouble(long address, double x) {
 434         putDouble(null, address, x);
 435     }
 436 
 437     /** @see #getAddress(Object, long) */
 438     @ForceInline
 439     public long getAddress(long address) {
 440         return getAddress(null, address);
 441     }
 442 
 443     /** @see #putAddress(Object, long, long) */
 444     @ForceInline
 445     public void putAddress(long address, long x) {
 446         putAddress(null, address, x);
 447     }
 448 
 449 
 450 
 451     /// helper methods for validating various types of objects/values
 452 
 453     /**
 454      * Create an exception reflecting that some of the input was invalid
 455      *
 456      * <em>Note:</em> It is the resposibility of the caller to make
 457      * sure arguments are checked before the methods are called. While
 458      * some rudimentary checks are performed on the input, the checks
 459      * are best effort and when performance is an overriding priority,
 460      * as when methods of this class are optimized by the runtime
 461      * compiler, some or all checks (if any) may be elided. Hence, the
 462      * caller must not rely on the checks and corresponding
 463      * exceptions!
 464      *
 465      * @return an exception object
 466      */
 467     private RuntimeException invalidInput() {
 468         return new IllegalArgumentException();
 469     }
 470 
 471     /**
 472      * Check if a value is 32-bit clean (32 MSB are all zero)
 473      *
 474      * @param value the 64-bit value to check
 475      *
 476      * @return true if the value is 32-bit clean
 477      */
 478     private boolean is32BitClean(long value) {
 479         return value >>> 32 == 0;
 480     }
 481 
 482     /**
 483      * Check the validity of a size (the equivalent of a size_t)
 484      *
 485      * @throws RuntimeException if the size is invalid
 486      *         (<em>Note:</em> after optimization, invalid inputs may
 487      *         go undetected, which will lead to unpredictable
 488      *         behavior)
 489      */
 490     private void checkSize(long size) {
 491         if (ADDRESS_SIZE == 4) {
 492             // Note: this will also check for negative sizes
 493             if (!is32BitClean(size)) {
 494                 throw invalidInput();
 495             }
 496         } else if (size < 0) {
 497             throw invalidInput();
 498         }
 499     }
 500 
 501     /**
 502      * Check the validity of a native address (the equivalent of void*)
 503      *
 504      * @throws RuntimeException if the address is invalid
 505      *         (<em>Note:</em> after optimization, invalid inputs may
 506      *         go undetected, which will lead to unpredictable
 507      *         behavior)
 508      */
 509     private void checkNativeAddress(long address) {
 510         if (ADDRESS_SIZE == 4) {
 511             // Accept both zero and sign extended pointers. A valid
 512             // pointer will, after the +1 below, either have produced
 513             // the value 0x0 or 0x1. Masking off the low bit allows
 514             // for testing against 0.
 515             if ((((address >> 32) + 1) & ~1) != 0) {
 516                 throw invalidInput();
 517             }
 518         }
 519     }
 520 
 521     /**
 522      * Check the validity of an offset, relative to a base object
 523      *
 524      * @param o the base object
 525      * @param offset the offset to check
 526      *
 527      * @throws RuntimeException if the size is invalid
 528      *         (<em>Note:</em> after optimization, invalid inputs may
 529      *         go undetected, which will lead to unpredictable
 530      *         behavior)
 531      */
 532     private void checkOffset(Object o, long offset) {
 533         if (ADDRESS_SIZE == 4) {
 534             // Note: this will also check for negative offsets
 535             if (!is32BitClean(offset)) {
 536                 throw invalidInput();
 537             }
 538         } else if (offset < 0) {
 539             throw invalidInput();
 540         }
 541     }
 542 
 543     /**
 544      * Check the validity of a double-register pointer
 545      *
 546      * Note: This code deliberately does *not* check for NPE for (at
 547      * least) three reasons:
 548      *
 549      * 1) NPE is not just NULL/0 - there is a range of values all
 550      * resulting in an NPE, which is not trivial to check for
 551      *
 552      * 2) It is the responsibility of the callers of Unsafe methods
 553      * to verify the input, so throwing an exception here is not really
 554      * useful - passing in a NULL pointer is a critical error and the
 555      * must not expect an exception to be thrown anyway.
 556      *
 557      * 3) the actual operations will detect NULL pointers anyway by
 558      * means of traps and signals (like SIGSEGV).
 559      *
 560      * @param o Java heap object, or null
 561      * @param offset indication of where the variable resides in a Java heap
 562      *        object, if any, else a memory address locating the variable
 563      *        statically
 564      *
 565      * @throws RuntimeException if the pointer is invalid
 566      *         (<em>Note:</em> after optimization, invalid inputs may
 567      *         go undetected, which will lead to unpredictable
 568      *         behavior)
 569      */
 570     private void checkPointer(Object o, long offset) {
 571         if (o == null) {
 572             checkNativeAddress(offset);
 573         } else {
 574             checkOffset(o, offset);
 575         }
 576     }
 577 
 578     /**
 579      * Check if a type is a primitive array type
 580      *
 581      * @param c the type to check
 582      *
 583      * @return true if the type is a primitive array type
 584      */
 585     private void checkPrimitiveArray(Class<?> c) {
 586         Class<?> componentType = c.getComponentType();
 587         if (componentType == null || !componentType.isPrimitive()) {
 588             throw invalidInput();
 589         }
 590     }
 591 
 592     /**
 593      * Check that a pointer is a valid primitive array type pointer
 594      *
 595      * Note: pointers off-heap are considered to be primitive arrays
 596      *
 597      * @throws RuntimeException if the pointer is invalid
 598      *         (<em>Note:</em> after optimization, invalid inputs may
 599      *         go undetected, which will lead to unpredictable
 600      *         behavior)
 601      */
 602     private void checkPrimitivePointer(Object o, long offset) {
 603         checkPointer(o, offset);
 604 
 605         if (o != null) {
 606             // If on heap, it it must be a primitive array
 607             checkPrimitiveArray(o.getClass());
 608         }
 609     }
 610 
 611 
 612     /// wrappers for malloc, realloc, free:
 613 
 614     /**
 615      * Allocates a new block of native memory, of the given size in bytes.  The
 616      * contents of the memory are uninitialized; they will generally be
 617      * garbage.  The resulting native pointer will never be zero, and will be
 618      * aligned for all value types.  Dispose of this memory by calling {@link
 619      * #freeMemory}, or resize it with {@link #reallocateMemory}.
 620      *
 621      * <em>Note:</em> It is the resposibility of the caller to make
 622      * sure arguments are checked before the methods are called. While
 623      * some rudimentary checks are performed on the input, the checks
 624      * are best effort and when performance is an overriding priority,
 625      * as when methods of this class are optimized by the runtime
 626      * compiler, some or all checks (if any) may be elided. Hence, the
 627      * caller must not rely on the checks and corresponding
 628      * exceptions!
 629      *
 630      * @throws RuntimeException if the size is negative or too large
 631      *         for the native size_t type
 632      *
 633      * @throws OutOfMemoryError if the allocation is refused by the system
 634      *
 635      * @see #getByte(long)
 636      * @see #putByte(long, byte)
 637      */
 638     public long allocateMemory(long bytes) {
 639         allocateMemoryChecks(bytes);
 640 
 641         if (bytes == 0) {
 642             return 0;
 643         }
 644 
 645         long p = allocateMemory0(bytes);
 646         if (p == 0) {
 647             throw new OutOfMemoryError();
 648         }
 649 
 650         return p;
 651     }
 652 
 653     /**
 654      * Validate the arguments to allocateMemory
 655      *
 656      * @throws RuntimeException if the arguments are invalid
 657      *         (<em>Note:</em> after optimization, invalid inputs may
 658      *         go undetected, which will lead to unpredictable
 659      *         behavior)
 660      */
 661     private void allocateMemoryChecks(long bytes) {
 662         checkSize(bytes);
 663     }
 664 
 665     /**
 666      * Resizes a new block of native memory, to the given size in bytes.  The
 667      * contents of the new block past the size of the old block are
 668      * uninitialized; they will generally be garbage.  The resulting native
 669      * pointer will be zero if and only if the requested size is zero.  The
 670      * resulting native pointer will be aligned for all value types.  Dispose
 671      * of this memory by calling {@link #freeMemory}, or resize it with {@link
 672      * #reallocateMemory}.  The address passed to this method may be null, in
 673      * which case an allocation will be performed.
 674      *
 675      * <em>Note:</em> It is the resposibility of the caller to make
 676      * sure arguments are checked before the methods are called. While
 677      * some rudimentary checks are performed on the input, the checks
 678      * are best effort and when performance is an overriding priority,
 679      * as when methods of this class are optimized by the runtime
 680      * compiler, some or all checks (if any) may be elided. Hence, the
 681      * caller must not rely on the checks and corresponding
 682      * exceptions!
 683      *
 684      * @throws RuntimeException if the size is negative or too large
 685      *         for the native size_t type
 686      *
 687      * @throws OutOfMemoryError if the allocation is refused by the system
 688      *
 689      * @see #allocateMemory
 690      */
 691     public long reallocateMemory(long address, long bytes) {
 692         reallocateMemoryChecks(address, bytes);
 693 
 694         if (bytes == 0) {
 695             freeMemory(address);
 696             return 0;
 697         }
 698 
 699         long p = (address == 0) ? allocateMemory0(bytes) : reallocateMemory0(address, bytes);
 700         if (p == 0) {
 701             throw new OutOfMemoryError();
 702         }
 703 
 704         return p;
 705     }
 706 
 707     /**
 708      * Validate the arguments to reallocateMemory
 709      *
 710      * @throws RuntimeException if the arguments are invalid
 711      *         (<em>Note:</em> after optimization, invalid inputs may
 712      *         go undetected, which will lead to unpredictable
 713      *         behavior)
 714      */
 715     private void reallocateMemoryChecks(long address, long bytes) {
 716         checkPointer(null, address);
 717         checkSize(bytes);
 718     }
 719 
 720     /**
 721      * Sets all bytes in a given block of memory to a fixed value
 722      * (usually zero).
 723      *
 724      * <p>This method determines a block's base address by means of two parameters,
 725      * and so it provides (in effect) a <em>double-register</em> addressing mode,
 726      * as discussed in {@link #getInt(Object,long)}.  When the object reference is null,
 727      * the offset supplies an absolute base address.
 728      *
 729      * <p>The stores are in coherent (atomic) units of a size determined
 730      * by the address and length parameters.  If the effective address and
 731      * length are all even modulo 8, the stores take place in 'long' units.
 732      * If the effective address and length are (resp.) even modulo 4 or 2,
 733      * the stores take place in units of 'int' or 'short'.
 734      *
 735      * <em>Note:</em> It is the resposibility of the caller to make
 736      * sure arguments are checked before the methods are called. While
 737      * some rudimentary checks are performed on the input, the checks
 738      * are best effort and when performance is an overriding priority,
 739      * as when methods of this class are optimized by the runtime
 740      * compiler, some or all checks (if any) may be elided. Hence, the
 741      * caller must not rely on the checks and corresponding
 742      * exceptions!
 743      *
 744      * @throws RuntimeException if any of the arguments is invalid
 745      *
 746      * @since 1.7
 747      */
 748     public void setMemory(Object o, long offset, long bytes, byte value) {
 749         setMemoryChecks(o, offset, bytes, value);
 750 
 751         if (bytes == 0) {
 752             return;
 753         }
 754 
 755         setMemory0(o, offset, bytes, value);
 756     }
 757 
 758     /**
 759      * Sets all bytes in a given block of memory to a fixed value
 760      * (usually zero).  This provides a <em>single-register</em> addressing mode,
 761      * as discussed in {@link #getInt(Object,long)}.
 762      *
 763      * <p>Equivalent to {@code setMemory(null, address, bytes, value)}.
 764      */
 765     public void setMemory(long address, long bytes, byte value) {
 766         setMemory(null, address, bytes, value);
 767     }
 768 
 769     /**
 770      * Validate the arguments to setMemory
 771      *
 772      * @throws RuntimeException if the arguments are invalid
 773      *         (<em>Note:</em> after optimization, invalid inputs may
 774      *         go undetected, which will lead to unpredictable
 775      *         behavior)
 776      */
 777     private void setMemoryChecks(Object o, long offset, long bytes, byte value) {
 778         checkPrimitivePointer(o, offset);
 779         checkSize(bytes);
 780     }
 781 
 782     /**
 783      * Sets all bytes in a given block of memory to a copy of another
 784      * block.
 785      *
 786      * <p>This method determines each block's base address by means of two parameters,
 787      * and so it provides (in effect) a <em>double-register</em> addressing mode,
 788      * as discussed in {@link #getInt(Object,long)}.  When the object reference is null,
 789      * the offset supplies an absolute base address.
 790      *
 791      * <p>The transfers are in coherent (atomic) units of a size determined
 792      * by the address and length parameters.  If the effective addresses and
 793      * length are all even modulo 8, the transfer takes place in 'long' units.
 794      * If the effective addresses and length are (resp.) even modulo 4 or 2,
 795      * the transfer takes place in units of 'int' or 'short'.
 796      *
 797      * <em>Note:</em> It is the resposibility of the caller to make
 798      * sure arguments are checked before the methods are called. While
 799      * some rudimentary checks are performed on the input, the checks
 800      * are best effort and when performance is an overriding priority,
 801      * as when methods of this class are optimized by the runtime
 802      * compiler, some or all checks (if any) may be elided. Hence, the
 803      * caller must not rely on the checks and corresponding
 804      * exceptions!
 805      *
 806      * @throws RuntimeException if any of the arguments is invalid
 807      *
 808      * @since 1.7
 809      */
 810     public void copyMemory(Object srcBase, long srcOffset,
 811                            Object destBase, long destOffset,
 812                            long bytes) {
 813         copyMemoryChecks(srcBase, srcOffset, destBase, destOffset, bytes);
 814 
 815         if (bytes == 0) {
 816             return;
 817         }
 818 
 819         copyMemory0(srcBase, srcOffset, destBase, destOffset, bytes);
 820     }
 821 
 822     /**
 823      * Sets all bytes in a given block of memory to a copy of another
 824      * block.  This provides a <em>single-register</em> addressing mode,
 825      * as discussed in {@link #getInt(Object,long)}.
 826      *
 827      * Equivalent to {@code copyMemory(null, srcAddress, null, destAddress, bytes)}.
 828      */
 829     public void copyMemory(long srcAddress, long destAddress, long bytes) {
 830         copyMemory(null, srcAddress, null, destAddress, bytes);
 831     }
 832 
 833     /**
 834      * Validate the arguments to copyMemory
 835      *
 836      * @throws RuntimeException if any of the arguments is invalid
 837      *         (<em>Note:</em> after optimization, invalid inputs may
 838      *         go undetected, which will lead to unpredictable
 839      *         behavior)
 840      */
 841     private void copyMemoryChecks(Object srcBase, long srcOffset,
 842                                   Object destBase, long destOffset,
 843                                   long bytes) {
 844         checkSize(bytes);
 845         checkPrimitivePointer(srcBase, srcOffset);
 846         checkPrimitivePointer(destBase, destOffset);
 847     }
 848 
 849     /**
 850      * Copies all elements from one block of memory to another block,
 851      * *unconditionally* byte swapping the elements on the fly.
 852      *
 853      * <p>This method determines each block's base address by means of two parameters,
 854      * and so it provides (in effect) a <em>double-register</em> addressing mode,
 855      * as discussed in {@link #getInt(Object,long)}.  When the object reference is null,
 856      * the offset supplies an absolute base address.
 857      *
 858      * <em>Note:</em> It is the resposibility of the caller to make
 859      * sure arguments are checked before the methods are called. While
 860      * some rudimentary checks are performed on the input, the checks
 861      * are best effort and when performance is an overriding priority,
 862      * as when methods of this class are optimized by the runtime
 863      * compiler, some or all checks (if any) may be elided. Hence, the
 864      * caller must not rely on the checks and corresponding
 865      * exceptions!
 866      *
 867      * @throws RuntimeException if any of the arguments is invalid
 868      *
 869      * @since 9
 870      */
 871     public void copySwapMemory(Object srcBase, long srcOffset,
 872                                Object destBase, long destOffset,
 873                                long bytes, long elemSize) {
 874         copySwapMemoryChecks(srcBase, srcOffset, destBase, destOffset, bytes, elemSize);
 875 
 876         if (bytes == 0) {
 877             return;
 878         }
 879 
 880         copySwapMemory0(srcBase, srcOffset, destBase, destOffset, bytes, elemSize);
 881     }
 882 
 883     private void copySwapMemoryChecks(Object srcBase, long srcOffset,
 884                                       Object destBase, long destOffset,
 885                                       long bytes, long elemSize) {
 886         checkSize(bytes);
 887 
 888         if (elemSize != 2 && elemSize != 4 && elemSize != 8) {
 889             throw invalidInput();
 890         }
 891         if (bytes % elemSize != 0) {
 892             throw invalidInput();
 893         }
 894 
 895         checkPrimitivePointer(srcBase, srcOffset);
 896         checkPrimitivePointer(destBase, destOffset);
 897     }
 898 
 899    /**
 900      * Copies all elements from one block of memory to another block, byte swapping the
 901      * elements on the fly.
 902      *
 903      * This provides a <em>single-register</em> addressing mode, as
 904      * discussed in {@link #getInt(Object,long)}.
 905      *
 906      * Equivalent to {@code copySwapMemory(null, srcAddress, null, destAddress, bytes, elemSize)}.
 907      */
 908     public void copySwapMemory(long srcAddress, long destAddress, long bytes, long elemSize) {
 909         copySwapMemory(null, srcAddress, null, destAddress, bytes, elemSize);
 910     }
 911 
 912     /**
 913      * Disposes of a block of native memory, as obtained from {@link
 914      * #allocateMemory} or {@link #reallocateMemory}.  The address passed to
 915      * this method may be null, in which case no action is taken.
 916      *
 917      * <em>Note:</em> It is the resposibility of the caller to make
 918      * sure arguments are checked before the methods are called. While
 919      * some rudimentary checks are performed on the input, the checks
 920      * are best effort and when performance is an overriding priority,
 921      * as when methods of this class are optimized by the runtime
 922      * compiler, some or all checks (if any) may be elided. Hence, the
 923      * caller must not rely on the checks and corresponding
 924      * exceptions!
 925      *
 926      * @throws RuntimeException if any of the arguments is invalid
 927      *
 928      * @see #allocateMemory
 929      */
 930     public void freeMemory(long address) {
 931         freeMemoryChecks(address);
 932 
 933         if (address == 0) {
 934             return;
 935         }
 936 
 937         freeMemory0(address);
 938     }
 939 
 940     /**
 941      * Validate the arguments to freeMemory
 942      *
 943      * @throws RuntimeException if the arguments are invalid
 944      *         (<em>Note:</em> after optimization, invalid inputs may
 945      *         go undetected, which will lead to unpredictable
 946      *         behavior)
 947      */
 948     private void freeMemoryChecks(long address) {
 949         checkPointer(null, address);
 950     }
 951 
 952     /// random queries
 953 
 954     /**
 955      * This constant differs from all results that will ever be returned from
 956      * {@link #staticFieldOffset}, {@link #objectFieldOffset},
 957      * or {@link #arrayBaseOffset}.
 958      */
 959     public static final int INVALID_FIELD_OFFSET = -1;
 960 
 961     /**
 962      * Reports the location of a given field in the storage allocation of its
 963      * class.  Do not expect to perform any sort of arithmetic on this offset;
 964      * it is just a cookie which is passed to the unsafe heap memory accessors.
 965      *
 966      * <p>Any given field will always have the same offset and base, and no
 967      * two distinct fields of the same class will ever have the same offset
 968      * and base.
 969      *
 970      * <p>As of 1.4.1, offsets for fields are represented as long values,
 971      * although the Sun JVM does not use the most significant 32 bits.
 972      * However, JVM implementations which store static fields at absolute
 973      * addresses can use long offsets and null base pointers to express
 974      * the field locations in a form usable by {@link #getInt(Object,long)}.
 975      * Therefore, code which will be ported to such JVMs on 64-bit platforms
 976      * must preserve all bits of static field offsets.
 977      * @see #getInt(Object, long)
 978      */
 979     public long objectFieldOffset(Field f) {
 980         if (f == null) {
 981             throw new NullPointerException();
 982         }
 983 
 984         return objectFieldOffset0(f);
 985     }
 986 
 987     /**
 988      * Reports the location of a given static field, in conjunction with {@link
 989      * #staticFieldBase}.
 990      * <p>Do not expect to perform any sort of arithmetic on this offset;
 991      * it is just a cookie which is passed to the unsafe heap memory accessors.
 992      *
 993      * <p>Any given field will always have the same offset, and no two distinct
 994      * fields of the same class will ever have the same offset.
 995      *
 996      * <p>As of 1.4.1, offsets for fields are represented as long values,
 997      * although the Sun JVM does not use the most significant 32 bits.
 998      * It is hard to imagine a JVM technology which needs more than
 999      * a few bits to encode an offset within a non-array object,
1000      * However, for consistency with other methods in this class,
1001      * this method reports its result as a long value.
1002      * @see #getInt(Object, long)
1003      */
1004     public long staticFieldOffset(Field f) {
1005         if (f == null) {
1006             throw new NullPointerException();
1007         }
1008 
1009         return staticFieldOffset0(f);
1010     }
1011 
1012     /**
1013      * Reports the location of a given static field, in conjunction with {@link
1014      * #staticFieldOffset}.
1015      * <p>Fetch the base "Object", if any, with which static fields of the
1016      * given class can be accessed via methods like {@link #getInt(Object,
1017      * long)}.  This value may be null.  This value may refer to an object
1018      * which is a "cookie", not guaranteed to be a real Object, and it should
1019      * not be used in any way except as argument to the get and put routines in
1020      * this class.
1021      */
1022     public Object staticFieldBase(Field f) {
1023         if (f == null) {
1024             throw new NullPointerException();
1025         }
1026 
1027         return staticFieldBase0(f);
1028     }
1029 
1030     /**
1031      * Detects if the given class may need to be initialized. This is often
1032      * needed in conjunction with obtaining the static field base of a
1033      * class.
1034      * @return false only if a call to {@code ensureClassInitialized} would have no effect
1035      */
1036     public boolean shouldBeInitialized(Class<?> c) {
1037         if (c == null) {
1038             throw new NullPointerException();
1039         }
1040 
1041         return shouldBeInitialized0(c);
1042     }
1043 
1044     /**
1045      * Ensures the given class has been initialized. This is often
1046      * needed in conjunction with obtaining the static field base of a
1047      * class.
1048      */
1049     public void ensureClassInitialized(Class<?> c) {
1050         if (c == null) {
1051             throw new NullPointerException();
1052         }
1053 
1054         ensureClassInitialized0(c);
1055     }
1056 
1057     /**
1058      * Reports the offset of the first element in the storage allocation of a
1059      * given array class.  If {@link #arrayIndexScale} returns a non-zero value
1060      * for the same class, you may use that scale factor, together with this
1061      * base offset, to form new offsets to access elements of arrays of the
1062      * given class.
1063      *
1064      * @see #getInt(Object, long)
1065      * @see #putInt(Object, long, int)
1066      */
1067     public int arrayBaseOffset(Class<?> arrayClass) {
1068         if (arrayClass == null) {
1069             throw new NullPointerException();
1070         }
1071 
1072         return arrayBaseOffset0(arrayClass);
1073     }
1074 
1075 
1076     /** The value of {@code arrayBaseOffset(boolean[].class)} */
1077     public static final int ARRAY_BOOLEAN_BASE_OFFSET
1078             = theUnsafe.arrayBaseOffset(boolean[].class);
1079 
1080     /** The value of {@code arrayBaseOffset(byte[].class)} */
1081     public static final int ARRAY_BYTE_BASE_OFFSET
1082             = theUnsafe.arrayBaseOffset(byte[].class);
1083 
1084     /** The value of {@code arrayBaseOffset(short[].class)} */
1085     public static final int ARRAY_SHORT_BASE_OFFSET
1086             = theUnsafe.arrayBaseOffset(short[].class);
1087 
1088     /** The value of {@code arrayBaseOffset(char[].class)} */
1089     public static final int ARRAY_CHAR_BASE_OFFSET
1090             = theUnsafe.arrayBaseOffset(char[].class);
1091 
1092     /** The value of {@code arrayBaseOffset(int[].class)} */
1093     public static final int ARRAY_INT_BASE_OFFSET
1094             = theUnsafe.arrayBaseOffset(int[].class);
1095 
1096     /** The value of {@code arrayBaseOffset(long[].class)} */
1097     public static final int ARRAY_LONG_BASE_OFFSET
1098             = theUnsafe.arrayBaseOffset(long[].class);
1099 
1100     /** The value of {@code arrayBaseOffset(float[].class)} */
1101     public static final int ARRAY_FLOAT_BASE_OFFSET
1102             = theUnsafe.arrayBaseOffset(float[].class);
1103 
1104     /** The value of {@code arrayBaseOffset(double[].class)} */
1105     public static final int ARRAY_DOUBLE_BASE_OFFSET
1106             = theUnsafe.arrayBaseOffset(double[].class);
1107 
1108     /** The value of {@code arrayBaseOffset(Object[].class)} */
1109     public static final int ARRAY_OBJECT_BASE_OFFSET
1110             = theUnsafe.arrayBaseOffset(Object[].class);
1111 
1112     /**
1113      * Reports the scale factor for addressing elements in the storage
1114      * allocation of a given array class.  However, arrays of "narrow" types
1115      * will generally not work properly with accessors like {@link
1116      * #getByte(Object, long)}, so the scale factor for such classes is reported
1117      * as zero.
1118      *
1119      * @see #arrayBaseOffset
1120      * @see #getInt(Object, long)
1121      * @see #putInt(Object, long, int)
1122      */
1123     public int arrayIndexScale(Class<?> arrayClass) {
1124         if (arrayClass == null) {
1125             throw new NullPointerException();
1126         }
1127 
1128         return arrayIndexScale0(arrayClass);
1129     }
1130 
1131 
1132     /** The value of {@code arrayIndexScale(boolean[].class)} */
1133     public static final int ARRAY_BOOLEAN_INDEX_SCALE
1134             = theUnsafe.arrayIndexScale(boolean[].class);
1135 
1136     /** The value of {@code arrayIndexScale(byte[].class)} */
1137     public static final int ARRAY_BYTE_INDEX_SCALE
1138             = theUnsafe.arrayIndexScale(byte[].class);
1139 
1140     /** The value of {@code arrayIndexScale(short[].class)} */
1141     public static final int ARRAY_SHORT_INDEX_SCALE
1142             = theUnsafe.arrayIndexScale(short[].class);
1143 
1144     /** The value of {@code arrayIndexScale(char[].class)} */
1145     public static final int ARRAY_CHAR_INDEX_SCALE
1146             = theUnsafe.arrayIndexScale(char[].class);
1147 
1148     /** The value of {@code arrayIndexScale(int[].class)} */
1149     public static final int ARRAY_INT_INDEX_SCALE
1150             = theUnsafe.arrayIndexScale(int[].class);
1151 
1152     /** The value of {@code arrayIndexScale(long[].class)} */
1153     public static final int ARRAY_LONG_INDEX_SCALE
1154             = theUnsafe.arrayIndexScale(long[].class);
1155 
1156     /** The value of {@code arrayIndexScale(float[].class)} */
1157     public static final int ARRAY_FLOAT_INDEX_SCALE
1158             = theUnsafe.arrayIndexScale(float[].class);
1159 
1160     /** The value of {@code arrayIndexScale(double[].class)} */
1161     public static final int ARRAY_DOUBLE_INDEX_SCALE
1162             = theUnsafe.arrayIndexScale(double[].class);
1163 
1164     /** The value of {@code arrayIndexScale(Object[].class)} */
1165     public static final int ARRAY_OBJECT_INDEX_SCALE
1166             = theUnsafe.arrayIndexScale(Object[].class);
1167 
1168     /**
1169      * Reports the size in bytes of a native pointer, as stored via {@link
1170      * #putAddress}.  This value will be either 4 or 8.  Note that the sizes of
1171      * other primitive types (as stored in native memory blocks) is determined
1172      * fully by their information content.
1173      */
1174     public int addressSize() {
1175         return ADDRESS_SIZE;
1176     }
1177 
1178     /** The value of {@code addressSize()} */
1179     public static final int ADDRESS_SIZE = theUnsafe.addressSize0();
1180 
1181     /**
1182      * Reports the size in bytes of a native memory page (whatever that is).
1183      * This value will always be a power of two.
1184      */
1185     public native int pageSize();
1186 
1187 
1188     /// random trusted operations from JNI:
1189 
1190     /**
1191      * Tells the VM to define a class, without security checks.  By default, the
1192      * class loader and protection domain come from the caller's class.
1193      */
1194     public Class<?> defineClass(String name, byte[] b, int off, int len,
1195                                 ClassLoader loader,
1196                                 ProtectionDomain protectionDomain) {
1197         if (b == null) {
1198             throw new NullPointerException();
1199         }
1200         if (len < 0) {
1201             throw new ArrayIndexOutOfBoundsException();
1202         }
1203 
1204         return defineClass0(name, b, off, len, loader, protectionDomain);
1205     }
1206 
1207     public native Class<?> defineClass0(String name, byte[] b, int off, int len,
1208                                         ClassLoader loader,
1209                                         ProtectionDomain protectionDomain);
1210 
1211     /**
1212      * Defines a class but does not make it known to the class loader or system dictionary.
1213      * <p>
1214      * For each CP entry, the corresponding CP patch must either be null or have
1215      * the a format that matches its tag:
1216      * <ul>
1217      * <li>Integer, Long, Float, Double: the corresponding wrapper object type from java.lang
1218      * <li>Utf8: a string (must have suitable syntax if used as signature or name)
1219      * <li>Class: any java.lang.Class object
1220      * <li>String: any object (not just a java.lang.String)
1221      * <li>InterfaceMethodRef: (NYI) a method handle to invoke on that call site's arguments
1222      * </ul>
1223      * @param hostClass context for linkage, access control, protection domain, and class loader
1224      * @param data      bytes of a class file
1225      * @param cpPatches where non-null entries exist, they replace corresponding CP entries in data
1226      */
1227     public Class<?> defineAnonymousClass(Class<?> hostClass, byte[] data, Object[] cpPatches) {
1228         if (hostClass == null || data == null) {
1229             throw new NullPointerException();
1230         }
1231 
1232         return defineAnonymousClass0(hostClass, data, cpPatches);
1233     }
1234 
1235     /**
1236      * Allocates an instance but does not run any constructor.
1237      * Initializes the class if it has not yet been.
1238      */
1239     @HotSpotIntrinsicCandidate
1240     public native Object allocateInstance(Class<?> cls)
1241         throws InstantiationException;
1242 
1243     /**
1244      * Allocates an array of a given type, but does not do zeroing.
1245      * <p>
1246      * This method should only be used in the very rare cases where a high-performance code
1247      * overwrites the destination array completely, and compilers cannot assist in zeroing elimination.
1248      * In an overwhelming majority of cases, a normal Java allocation should be used instead.
1249      * <p>
1250      * Users of this method are <b>required</b> to overwrite the initial (garbage) array contents
1251      * before allowing untrusted code, or code in other threads, to observe the reference
1252      * to the newly allocated array. In addition, the publication of the array reference must be
1253      * safe according to the Java Memory Model requirements.
1254      * <p>
1255      * The safest approach to deal with an uninitialized array is to keep the reference to it in local
1256      * variable at least until the initialization is complete, and then publish it <b>once</b>, either
1257      * by writing it to a <em>volatile</em> field, or storing it into a <em>final</em> field in constructor,
1258      * or issuing a {@link #storeFence} before publishing the reference.
1259      * <p>
1260      * @implnote This method can only allocate primitive arrays, to avoid garbage reference
1261      * elements that could break heap integrity.
1262      *
1263      * @param componentType array component type to allocate
1264      * @param length array size to allocate
1265      * @throws IllegalArgumentException if component type is null, or not a primitive class;
1266      *                                  or the length is negative
1267      */
1268     public Object allocateUninitializedArray(Class<?> componentType, int length) {
1269        if (componentType == null) {
1270            throw new IllegalArgumentException("Component type is null");
1271        }
1272        if (!componentType.isPrimitive()) {
1273            throw new IllegalArgumentException("Component type is not primitive");
1274        }
1275        if (length < 0) {
1276            throw new IllegalArgumentException("Negative length");
1277        }
1278        return allocateUninitializedArray0(componentType, length);
1279     }
1280 
1281     @HotSpotIntrinsicCandidate
1282     private Object allocateUninitializedArray0(Class<?> componentType, int length) {
1283        // These fallbacks provide zeroed arrays, but intrinsic is not required to
1284        // return the zeroed arrays.
1285        if (componentType == byte.class)    return new byte[length];
1286        if (componentType == boolean.class) return new boolean[length];
1287        if (componentType == short.class)   return new short[length];
1288        if (componentType == char.class)    return new char[length];
1289        if (componentType == int.class)     return new int[length];
1290        if (componentType == float.class)   return new float[length];
1291        if (componentType == long.class)    return new long[length];
1292        if (componentType == double.class)  return new double[length];
1293        return null;
1294     }
1295 
1296     /** Throws the exception without telling the verifier. */
1297     public native void throwException(Throwable ee);
1298 
1299     /**
1300      * Atomically updates Java variable to {@code x} if it is currently
1301      * holding {@code expected}.
1302      *
1303      * <p>This operation has memory semantics of a {@code volatile} read
1304      * and write.  Corresponds to C11 atomic_compare_exchange_strong.
1305      *
1306      * @return {@code true} if successful
1307      */
1308     @HotSpotIntrinsicCandidate
1309     public final native boolean compareAndSwapObject(Object o, long offset,
1310                                                      Object expected,
1311                                                      Object x);
1312 
1313     @HotSpotIntrinsicCandidate
1314     public final native Object compareAndExchangeObjectVolatile(Object o, long offset,
1315                                                                 Object expected,
1316                                                                 Object x);
1317 
1318     @HotSpotIntrinsicCandidate
1319     public final Object compareAndExchangeObjectAcquire(Object o, long offset,
1320                                                                Object expected,
1321                                                                Object x) {
1322         return compareAndExchangeObjectVolatile(o, offset, expected, x);
1323     }
1324 
1325     @HotSpotIntrinsicCandidate
1326     public final Object compareAndExchangeObjectRelease(Object o, long offset,
1327                                                                Object expected,
1328                                                                Object x) {
1329         return compareAndExchangeObjectVolatile(o, offset, expected, x);
1330     }
1331 
1332     @HotSpotIntrinsicCandidate
1333     public final boolean weakCompareAndSwapObject(Object o, long offset,
1334                                                          Object expected,
1335                                                          Object x) {
1336         return compareAndSwapObject(o, offset, expected, x);
1337     }
1338 
1339     @HotSpotIntrinsicCandidate
1340     public final boolean weakCompareAndSwapObjectAcquire(Object o, long offset,
1341                                                                 Object expected,
1342                                                                 Object x) {
1343         return compareAndSwapObject(o, offset, expected, x);
1344     }
1345 
1346     @HotSpotIntrinsicCandidate
1347     public final boolean weakCompareAndSwapObjectRelease(Object o, long offset,
1348                                                                 Object expected,
1349                                                                 Object x) {
1350         return compareAndSwapObject(o, offset, expected, x);
1351     }
1352 
1353     @HotSpotIntrinsicCandidate
1354     public final boolean weakCompareAndSwapObjectVolatile(Object o, long offset,
1355                                                                 Object expected,
1356                                                                 Object x) {
1357         return compareAndSwapObject(o, offset, expected, x);
1358     }
1359 
1360     /**
1361      * Atomically updates Java variable to {@code x} if it is currently
1362      * holding {@code expected}.
1363      *
1364      * <p>This operation has memory semantics of a {@code volatile} read
1365      * and write.  Corresponds to C11 atomic_compare_exchange_strong.
1366      *
1367      * @return {@code true} if successful
1368      */
1369     @HotSpotIntrinsicCandidate
1370     public final native boolean compareAndSwapInt(Object o, long offset,
1371                                                   int expected,
1372                                                   int x);
1373 
1374     @HotSpotIntrinsicCandidate
1375     public final native int compareAndExchangeIntVolatile(Object o, long offset,
1376                                                           int expected,
1377                                                           int x);
1378 
1379     @HotSpotIntrinsicCandidate
1380     public final int compareAndExchangeIntAcquire(Object o, long offset,
1381                                                          int expected,
1382                                                          int x) {
1383         return compareAndExchangeIntVolatile(o, offset, expected, x);
1384     }
1385 
1386     @HotSpotIntrinsicCandidate
1387     public final int compareAndExchangeIntRelease(Object o, long offset,
1388                                                          int expected,
1389                                                          int x) {
1390         return compareAndExchangeIntVolatile(o, offset, expected, x);
1391     }
1392 
1393     @HotSpotIntrinsicCandidate
1394     public final boolean weakCompareAndSwapInt(Object o, long offset,
1395                                                       int expected,
1396                                                       int x) {
1397         return compareAndSwapInt(o, offset, expected, x);
1398     }
1399 
1400     @HotSpotIntrinsicCandidate
1401     public final boolean weakCompareAndSwapIntAcquire(Object o, long offset,
1402                                                              int expected,
1403                                                              int x) {
1404         return compareAndSwapInt(o, offset, expected, x);
1405     }
1406 
1407     @HotSpotIntrinsicCandidate
1408     public final boolean weakCompareAndSwapIntRelease(Object o, long offset,
1409                                                              int expected,
1410                                                              int x) {
1411         return compareAndSwapInt(o, offset, expected, x);
1412     }
1413 
1414     @HotSpotIntrinsicCandidate
1415     public final boolean weakCompareAndSwapIntVolatile(Object o, long offset,
1416                                                              int expected,
1417                                                              int x) {
1418         return compareAndSwapInt(o, offset, expected, x);
1419     }
1420 
1421     /**
1422      * Atomically updates Java variable to {@code x} if it is currently
1423      * holding {@code expected}.
1424      *
1425      * <p>This operation has memory semantics of a {@code volatile} read
1426      * and write.  Corresponds to C11 atomic_compare_exchange_strong.
1427      *
1428      * @return {@code true} if successful
1429      */
1430     @HotSpotIntrinsicCandidate
1431     public final native boolean compareAndSwapLong(Object o, long offset,
1432                                                    long expected,
1433                                                    long x);
1434 
1435     @HotSpotIntrinsicCandidate
1436     public final native long compareAndExchangeLongVolatile(Object o, long offset,
1437                                                             long expected,
1438                                                             long x);
1439 
1440     @HotSpotIntrinsicCandidate
1441     public final long compareAndExchangeLongAcquire(Object o, long offset,
1442                                                            long expected,
1443                                                            long x) {
1444         return compareAndExchangeLongVolatile(o, offset, expected, x);
1445     }
1446 
1447     @HotSpotIntrinsicCandidate
1448     public final long compareAndExchangeLongRelease(Object o, long offset,
1449                                                            long expected,
1450                                                            long x) {
1451         return compareAndExchangeLongVolatile(o, offset, expected, x);
1452     }
1453 
1454     @HotSpotIntrinsicCandidate
1455     public final boolean weakCompareAndSwapLong(Object o, long offset,
1456                                                        long expected,
1457                                                        long x) {
1458         return compareAndSwapLong(o, offset, expected, x);
1459     }
1460 
1461     @HotSpotIntrinsicCandidate
1462     public final boolean weakCompareAndSwapLongAcquire(Object o, long offset,
1463                                                               long expected,
1464                                                               long x) {
1465         return compareAndSwapLong(o, offset, expected, x);
1466     }
1467 
1468     @HotSpotIntrinsicCandidate
1469     public final boolean weakCompareAndSwapLongRelease(Object o, long offset,
1470                                                               long expected,
1471                                                               long x) {
1472         return compareAndSwapLong(o, offset, expected, x);
1473     }
1474 
1475     @HotSpotIntrinsicCandidate
1476     public final boolean weakCompareAndSwapLongVolatile(Object o, long offset,
1477                                                               long expected,
1478                                                               long x) {
1479         return compareAndSwapLong(o, offset, expected, x);
1480     }
1481 
1482     /**
1483      * Fetches a reference value from a given Java variable, with volatile
1484      * load semantics. Otherwise identical to {@link #getObject(Object, long)}
1485      */
1486     @HotSpotIntrinsicCandidate
1487     public native Object getObjectVolatile(Object o, long offset);
1488 
1489     /**
1490      * Stores a reference value into a given Java variable, with
1491      * volatile store semantics. Otherwise identical to {@link #putObject(Object, long, Object)}
1492      */
1493     @HotSpotIntrinsicCandidate
1494     public native void    putObjectVolatile(Object o, long offset, Object x);
1495 
1496     /** Volatile version of {@link #getInt(Object, long)}  */
1497     @HotSpotIntrinsicCandidate
1498     public native int     getIntVolatile(Object o, long offset);
1499 
1500     /** Volatile version of {@link #putInt(Object, long, int)}  */
1501     @HotSpotIntrinsicCandidate
1502     public native void    putIntVolatile(Object o, long offset, int x);
1503 
1504     /** Volatile version of {@link #getBoolean(Object, long)}  */
1505     @HotSpotIntrinsicCandidate
1506     public native boolean getBooleanVolatile(Object o, long offset);
1507 
1508     /** Volatile version of {@link #putBoolean(Object, long, boolean)}  */
1509     @HotSpotIntrinsicCandidate
1510     public native void    putBooleanVolatile(Object o, long offset, boolean x);
1511 
1512     /** Volatile version of {@link #getByte(Object, long)}  */
1513     @HotSpotIntrinsicCandidate
1514     public native byte    getByteVolatile(Object o, long offset);
1515 
1516     /** Volatile version of {@link #putByte(Object, long, byte)}  */
1517     @HotSpotIntrinsicCandidate
1518     public native void    putByteVolatile(Object o, long offset, byte x);
1519 
1520     /** Volatile version of {@link #getShort(Object, long)}  */
1521     @HotSpotIntrinsicCandidate
1522     public native short   getShortVolatile(Object o, long offset);
1523 
1524     /** Volatile version of {@link #putShort(Object, long, short)}  */
1525     @HotSpotIntrinsicCandidate
1526     public native void    putShortVolatile(Object o, long offset, short x);
1527 
1528     /** Volatile version of {@link #getChar(Object, long)}  */
1529     @HotSpotIntrinsicCandidate
1530     public native char    getCharVolatile(Object o, long offset);
1531 
1532     /** Volatile version of {@link #putChar(Object, long, char)}  */
1533     @HotSpotIntrinsicCandidate
1534     public native void    putCharVolatile(Object o, long offset, char x);
1535 
1536     /** Volatile version of {@link #getLong(Object, long)}  */
1537     @HotSpotIntrinsicCandidate
1538     public native long    getLongVolatile(Object o, long offset);
1539 
1540     /** Volatile version of {@link #putLong(Object, long, long)}  */
1541     @HotSpotIntrinsicCandidate
1542     public native void    putLongVolatile(Object o, long offset, long x);
1543 
1544     /** Volatile version of {@link #getFloat(Object, long)}  */
1545     @HotSpotIntrinsicCandidate
1546     public native float   getFloatVolatile(Object o, long offset);
1547 
1548     /** Volatile version of {@link #putFloat(Object, long, float)}  */
1549     @HotSpotIntrinsicCandidate
1550     public native void    putFloatVolatile(Object o, long offset, float x);
1551 
1552     /** Volatile version of {@link #getDouble(Object, long)}  */
1553     @HotSpotIntrinsicCandidate
1554     public native double  getDoubleVolatile(Object o, long offset);
1555 
1556     /** Volatile version of {@link #putDouble(Object, long, double)}  */
1557     @HotSpotIntrinsicCandidate
1558     public native void    putDoubleVolatile(Object o, long offset, double x);
1559 
1560 
1561 
1562     /** Acquire version of {@link #getObjectVolatile(Object, long)} */
1563     @HotSpotIntrinsicCandidate
1564     public final Object getObjectAcquire(Object o, long offset) {
1565         return getObjectVolatile(o, offset);
1566     }
1567 
1568     /** Acquire version of {@link #getBooleanVolatile(Object, long)} */
1569     @HotSpotIntrinsicCandidate
1570     public final boolean getBooleanAcquire(Object o, long offset) {
1571         return getBooleanVolatile(o, offset);
1572     }
1573 
1574     /** Acquire version of {@link #getByteVolatile(Object, long)} */
1575     @HotSpotIntrinsicCandidate
1576     public final byte getByteAcquire(Object o, long offset) {
1577         return getByteVolatile(o, offset);
1578     }
1579 
1580     /** Acquire version of {@link #getShortVolatile(Object, long)} */
1581     @HotSpotIntrinsicCandidate
1582     public final short getShortAcquire(Object o, long offset) {
1583         return getShortVolatile(o, offset);
1584     }
1585 
1586     /** Acquire version of {@link #getCharVolatile(Object, long)} */
1587     @HotSpotIntrinsicCandidate
1588     public final char getCharAcquire(Object o, long offset) {
1589         return getCharVolatile(o, offset);
1590     }
1591 
1592     /** Acquire version of {@link #getIntVolatile(Object, long)} */
1593     @HotSpotIntrinsicCandidate
1594     public final int getIntAcquire(Object o, long offset) {
1595         return getIntVolatile(o, offset);
1596     }
1597 
1598     /** Acquire version of {@link #getFloatVolatile(Object, long)} */
1599     @HotSpotIntrinsicCandidate
1600     public final float getFloatAcquire(Object o, long offset) {
1601         return getFloatVolatile(o, offset);
1602     }
1603 
1604     /** Acquire version of {@link #getLongVolatile(Object, long)} */
1605     @HotSpotIntrinsicCandidate
1606     public final long getLongAcquire(Object o, long offset) {
1607         return getLongVolatile(o, offset);
1608     }
1609 
1610     /** Acquire version of {@link #getDoubleVolatile(Object, long)} */
1611     @HotSpotIntrinsicCandidate
1612     public final double getDoubleAcquire(Object o, long offset) {
1613         return getDoubleVolatile(o, offset);
1614     }
1615 
1616     /*
1617       * Versions of {@link #putObjectVolatile(Object, long, Object)}
1618       * that do not guarantee immediate visibility of the store to
1619       * other threads. This method is generally only useful if the
1620       * underlying field is a Java volatile (or if an array cell, one
1621       * that is otherwise only accessed using volatile accesses).
1622       *
1623       * Corresponds to C11 atomic_store_explicit(..., memory_order_release).
1624       */
1625 
1626     /** Release version of {@link #putObjectVolatile(Object, long, Object)} */
1627     @HotSpotIntrinsicCandidate
1628     public final void putObjectRelease(Object o, long offset, Object x) {
1629         putObjectVolatile(o, offset, x);
1630     }
1631 
1632     /** Release version of {@link #putBooleanVolatile(Object, long, boolean)} */
1633     @HotSpotIntrinsicCandidate
1634     public final void putBooleanRelease(Object o, long offset, boolean x) {
1635         putBooleanVolatile(o, offset, x);
1636     }
1637 
1638     /** Release version of {@link #putByteVolatile(Object, long, byte)} */
1639     @HotSpotIntrinsicCandidate
1640     public final void putByteRelease(Object o, long offset, byte x) {
1641         putByteVolatile(o, offset, x);
1642     }
1643 
1644     /** Release version of {@link #putShortVolatile(Object, long, short)} */
1645     @HotSpotIntrinsicCandidate
1646     public final void putShortRelease(Object o, long offset, short x) {
1647         putShortVolatile(o, offset, x);
1648     }
1649 
1650     /** Release version of {@link #putCharVolatile(Object, long, char)} */
1651     @HotSpotIntrinsicCandidate
1652     public final void putCharRelease(Object o, long offset, char x) {
1653         putCharVolatile(o, offset, x);
1654     }
1655 
1656     /** Release version of {@link #putIntVolatile(Object, long, int)} */
1657     @HotSpotIntrinsicCandidate
1658     public final void putIntRelease(Object o, long offset, int x) {
1659         putIntVolatile(o, offset, x);
1660     }
1661 
1662     /** Release version of {@link #putFloatVolatile(Object, long, float)} */
1663     @HotSpotIntrinsicCandidate
1664     public final void putFloatRelease(Object o, long offset, float x) {
1665         putFloatVolatile(o, offset, x);
1666     }
1667 
1668     /** Release version of {@link #putLongVolatile(Object, long, long)} */
1669     @HotSpotIntrinsicCandidate
1670     public final void putLongRelease(Object o, long offset, long x) {
1671         putLongVolatile(o, offset, x);
1672     }
1673 
1674     /** Release version of {@link #putDoubleVolatile(Object, long, double)} */
1675     @HotSpotIntrinsicCandidate
1676     public final void putDoubleRelease(Object o, long offset, double x) {
1677         putDoubleVolatile(o, offset, x);
1678     }
1679 
1680     // ------------------------------ Opaque --------------------------------------
1681 
1682     /** Opaque version of {@link #getObjectVolatile(Object, long)} */
1683     @HotSpotIntrinsicCandidate
1684     public final Object getObjectOpaque(Object o, long offset) {
1685         return getObjectVolatile(o, offset);
1686     }
1687 
1688     /** Opaque version of {@link #getBooleanVolatile(Object, long)} */
1689     @HotSpotIntrinsicCandidate
1690     public final boolean getBooleanOpaque(Object o, long offset) {
1691         return getBooleanVolatile(o, offset);
1692     }
1693 
1694     /** Opaque version of {@link #getByteVolatile(Object, long)} */
1695     @HotSpotIntrinsicCandidate
1696     public final byte getByteOpaque(Object o, long offset) {
1697         return getByteVolatile(o, offset);
1698     }
1699 
1700     /** Opaque version of {@link #getShortVolatile(Object, long)} */
1701     @HotSpotIntrinsicCandidate
1702     public final short getShortOpaque(Object o, long offset) {
1703         return getShortVolatile(o, offset);
1704     }
1705 
1706     /** Opaque version of {@link #getCharVolatile(Object, long)} */
1707     @HotSpotIntrinsicCandidate
1708     public final char getCharOpaque(Object o, long offset) {
1709         return getCharVolatile(o, offset);
1710     }
1711 
1712     /** Opaque version of {@link #getIntVolatile(Object, long)} */
1713     @HotSpotIntrinsicCandidate
1714     public final int getIntOpaque(Object o, long offset) {
1715         return getIntVolatile(o, offset);
1716     }
1717 
1718     /** Opaque version of {@link #getFloatVolatile(Object, long)} */
1719     @HotSpotIntrinsicCandidate
1720     public final float getFloatOpaque(Object o, long offset) {
1721         return getFloatVolatile(o, offset);
1722     }
1723 
1724     /** Opaque version of {@link #getLongVolatile(Object, long)} */
1725     @HotSpotIntrinsicCandidate
1726     public final long getLongOpaque(Object o, long offset) {
1727         return getLongVolatile(o, offset);
1728     }
1729 
1730     /** Opaque version of {@link #getDoubleVolatile(Object, long)} */
1731     @HotSpotIntrinsicCandidate
1732     public final double getDoubleOpaque(Object o, long offset) {
1733         return getDoubleVolatile(o, offset);
1734     }
1735 
1736     /** Opaque version of {@link #putObjectVolatile(Object, long, Object)} */
1737     @HotSpotIntrinsicCandidate
1738     public final void putObjectOpaque(Object o, long offset, Object x) {
1739         putObjectVolatile(o, offset, x);
1740     }
1741 
1742     /** Opaque version of {@link #putBooleanVolatile(Object, long, boolean)} */
1743     @HotSpotIntrinsicCandidate
1744     public final void putBooleanOpaque(Object o, long offset, boolean x) {
1745         putBooleanVolatile(o, offset, x);
1746     }
1747 
1748     /** Opaque version of {@link #putByteVolatile(Object, long, byte)} */
1749     @HotSpotIntrinsicCandidate
1750     public final void putByteOpaque(Object o, long offset, byte x) {
1751         putByteVolatile(o, offset, x);
1752     }
1753 
1754     /** Opaque version of {@link #putShortVolatile(Object, long, short)} */
1755     @HotSpotIntrinsicCandidate
1756     public final void putShortOpaque(Object o, long offset, short x) {
1757         putShortVolatile(o, offset, x);
1758     }
1759 
1760     /** Opaque version of {@link #putCharVolatile(Object, long, char)} */
1761     @HotSpotIntrinsicCandidate
1762     public final void putCharOpaque(Object o, long offset, char x) {
1763         putCharVolatile(o, offset, x);
1764     }
1765 
1766     /** Opaque version of {@link #putIntVolatile(Object, long, int)} */
1767     @HotSpotIntrinsicCandidate
1768     public final void putIntOpaque(Object o, long offset, int x) {
1769         putIntVolatile(o, offset, x);
1770     }
1771 
1772     /** Opaque version of {@link #putFloatVolatile(Object, long, float)} */
1773     @HotSpotIntrinsicCandidate
1774     public final void putFloatOpaque(Object o, long offset, float x) {
1775         putFloatVolatile(o, offset, x);
1776     }
1777 
1778     /** Opaque version of {@link #putLongVolatile(Object, long, long)} */
1779     @HotSpotIntrinsicCandidate
1780     public final void putLongOpaque(Object o, long offset, long x) {
1781         putLongVolatile(o, offset, x);
1782     }
1783 
1784     /** Opaque version of {@link #putDoubleVolatile(Object, long, double)} */
1785     @HotSpotIntrinsicCandidate
1786     public final void putDoubleOpaque(Object o, long offset, double x) {
1787         putDoubleVolatile(o, offset, x);
1788     }
1789 
1790     /**
1791      * Unblocks the given thread blocked on {@code park}, or, if it is
1792      * not blocked, causes the subsequent call to {@code park} not to
1793      * block.  Note: this operation is "unsafe" solely because the
1794      * caller must somehow ensure that the thread has not been
1795      * destroyed. Nothing special is usually required to ensure this
1796      * when called from Java (in which there will ordinarily be a live
1797      * reference to the thread) but this is not nearly-automatically
1798      * so when calling from native code.
1799      *
1800      * @param thread the thread to unpark.
1801      */
1802     @HotSpotIntrinsicCandidate
1803     public native void unpark(Object thread);
1804 
1805     /**
1806      * Blocks current thread, returning when a balancing
1807      * {@code unpark} occurs, or a balancing {@code unpark} has
1808      * already occurred, or the thread is interrupted, or, if not
1809      * absolute and time is not zero, the given time nanoseconds have
1810      * elapsed, or if absolute, the given deadline in milliseconds
1811      * since Epoch has passed, or spuriously (i.e., returning for no
1812      * "reason"). Note: This operation is in the Unsafe class only
1813      * because {@code unpark} is, so it would be strange to place it
1814      * elsewhere.
1815      */
1816     @HotSpotIntrinsicCandidate
1817     public native void park(boolean isAbsolute, long time);
1818 
1819     /**
1820      * Gets the load average in the system run queue assigned
1821      * to the available processors averaged over various periods of time.
1822      * This method retrieves the given {@code nelem} samples and
1823      * assigns to the elements of the given {@code loadavg} array.
1824      * The system imposes a maximum of 3 samples, representing
1825      * averages over the last 1,  5,  and  15 minutes, respectively.
1826      *
1827      * @param loadavg an array of double of size nelems
1828      * @param nelems the number of samples to be retrieved and
1829      *        must be 1 to 3.
1830      *
1831      * @return the number of samples actually retrieved; or -1
1832      *         if the load average is unobtainable.
1833      */
1834     public int getLoadAverage(double[] loadavg, int nelems) {
1835         if (nelems < 0 || nelems > 3 || nelems > loadavg.length) {
1836             throw new ArrayIndexOutOfBoundsException();
1837         }
1838 
1839         return getLoadAverage0(loadavg, nelems);
1840     }
1841 
1842     // The following contain CAS-based Java implementations used on
1843     // platforms not supporting native instructions
1844 
1845     /**
1846      * Atomically adds the given value to the current value of a field
1847      * or array element within the given object {@code o}
1848      * at the given {@code offset}.
1849      *
1850      * @param o object/array to update the field/element in
1851      * @param offset field/element offset
1852      * @param delta the value to add
1853      * @return the previous value
1854      * @since 1.8
1855      */
1856     @HotSpotIntrinsicCandidate
1857     public final int getAndAddInt(Object o, long offset, int delta) {
1858         int v;
1859         do {
1860             v = getIntVolatile(o, offset);
1861         } while (!compareAndSwapInt(o, offset, v, v + delta));
1862         return v;
1863     }
1864 
1865     /**
1866      * Atomically adds the given value to the current value of a field
1867      * or array element within the given object {@code o}
1868      * at the given {@code offset}.
1869      *
1870      * @param o object/array to update the field/element in
1871      * @param offset field/element offset
1872      * @param delta the value to add
1873      * @return the previous value
1874      * @since 1.8
1875      */
1876     @HotSpotIntrinsicCandidate
1877     public final long getAndAddLong(Object o, long offset, long delta) {
1878         long v;
1879         do {
1880             v = getLongVolatile(o, offset);
1881         } while (!compareAndSwapLong(o, offset, v, v + delta));
1882         return v;
1883     }
1884 
1885     /**
1886      * Atomically exchanges the given value with the current value of
1887      * a field or array element within the given object {@code o}
1888      * at the given {@code offset}.
1889      *
1890      * @param o object/array to update the field/element in
1891      * @param offset field/element offset
1892      * @param newValue new value
1893      * @return the previous value
1894      * @since 1.8
1895      */
1896     @HotSpotIntrinsicCandidate
1897     public final int getAndSetInt(Object o, long offset, int newValue) {
1898         int v;
1899         do {
1900             v = getIntVolatile(o, offset);
1901         } while (!compareAndSwapInt(o, offset, v, newValue));
1902         return v;
1903     }
1904 
1905     /**
1906      * Atomically exchanges the given value with the current value of
1907      * a field or array element within the given object {@code o}
1908      * at the given {@code offset}.
1909      *
1910      * @param o object/array to update the field/element in
1911      * @param offset field/element offset
1912      * @param newValue new value
1913      * @return the previous value
1914      * @since 1.8
1915      */
1916     @HotSpotIntrinsicCandidate
1917     public final long getAndSetLong(Object o, long offset, long newValue) {
1918         long v;
1919         do {
1920             v = getLongVolatile(o, offset);
1921         } while (!compareAndSwapLong(o, offset, v, newValue));
1922         return v;
1923     }
1924 
1925     /**
1926      * Atomically exchanges the given reference value with the current
1927      * reference value of a field or array element within the given
1928      * object {@code o} at the given {@code offset}.
1929      *
1930      * @param o object/array to update the field/element in
1931      * @param offset field/element offset
1932      * @param newValue new value
1933      * @return the previous value
1934      * @since 1.8
1935      */
1936     @HotSpotIntrinsicCandidate
1937     public final Object getAndSetObject(Object o, long offset, Object newValue) {
1938         Object v;
1939         do {
1940             v = getObjectVolatile(o, offset);
1941         } while (!compareAndSwapObject(o, offset, v, newValue));
1942         return v;
1943     }
1944 
1945 
1946     /**
1947      * Ensures that loads before the fence will not be reordered with loads and
1948      * stores after the fence; a "LoadLoad plus LoadStore barrier".
1949      *
1950      * Corresponds to C11 atomic_thread_fence(memory_order_acquire)
1951      * (an "acquire fence").
1952      *
1953      * A pure LoadLoad fence is not provided, since the addition of LoadStore
1954      * is almost always desired, and most current hardware instructions that
1955      * provide a LoadLoad barrier also provide a LoadStore barrier for free.
1956      * @since 1.8
1957      */
1958     @HotSpotIntrinsicCandidate
1959     public native void loadFence();
1960 
1961     /**
1962      * Ensures that loads and stores before the fence will not be reordered with
1963      * stores after the fence; a "StoreStore plus LoadStore barrier".
1964      *
1965      * Corresponds to C11 atomic_thread_fence(memory_order_release)
1966      * (a "release fence").
1967      *
1968      * A pure StoreStore fence is not provided, since the addition of LoadStore
1969      * is almost always desired, and most current hardware instructions that
1970      * provide a StoreStore barrier also provide a LoadStore barrier for free.
1971      * @since 1.8
1972      */
1973     @HotSpotIntrinsicCandidate
1974     public native void storeFence();
1975 
1976     /**
1977      * Ensures that loads and stores before the fence will not be reordered
1978      * with loads and stores after the fence.  Implies the effects of both
1979      * loadFence() and storeFence(), and in addition, the effect of a StoreLoad
1980      * barrier.
1981      *
1982      * Corresponds to C11 atomic_thread_fence(memory_order_seq_cst).
1983      * @since 1.8
1984      */
1985     @HotSpotIntrinsicCandidate
1986     public native void fullFence();
1987 
1988     /**
1989      * Ensures that loads before the fence will not be reordered with
1990      * loads after the fence.
1991      */
1992     public final void loadLoadFence() {
1993         loadFence();
1994     }
1995 
1996     /**
1997      * Ensures that stores before the fence will not be reordered with
1998      * stores after the fence.
1999      */
2000     public final void storeStoreFence() {
2001         storeFence();
2002     }
2003 
2004 
2005     /**
2006      * Throws IllegalAccessError; for use by the VM for access control
2007      * error support.
2008      * @since 1.8
2009      */
2010     private static void throwIllegalAccessError() {
2011         throw new IllegalAccessError();
2012     }
2013 
2014     /**
2015      * @return Returns true if the native byte ordering of this
2016      * platform is big-endian, false if it is little-endian.
2017      */
2018     public final boolean isBigEndian() { return BE; }
2019 
2020     /**
2021      * @return Returns true if this platform is capable of performing
2022      * accesses at addresses which are not aligned for the type of the
2023      * primitive type being accessed, false otherwise.
2024      */
2025     public final boolean unalignedAccess() { return unalignedAccess; }
2026 
2027     /**
2028      * Fetches a value at some byte offset into a given Java object.
2029      * More specifically, fetches a value within the given object
2030      * <code>o</code> at the given offset, or (if <code>o</code> is
2031      * null) from the memory address whose numerical value is the
2032      * given offset.  <p>
2033      *
2034      * The specification of this method is the same as {@link
2035      * #getLong(Object, long)} except that the offset does not need to
2036      * have been obtained from {@link #objectFieldOffset} on the
2037      * {@link java.lang.reflect.Field} of some Java field.  The value
2038      * in memory is raw data, and need not correspond to any Java
2039      * variable.  Unless <code>o</code> is null, the value accessed
2040      * must be entirely within the allocated object.  The endianness
2041      * of the value in memory is the endianness of the native platform.
2042      *
2043      * <p> The read will be atomic with respect to the largest power
2044      * of two that divides the GCD of the offset and the storage size.
2045      * For example, getLongUnaligned will make atomic reads of 2-, 4-,
2046      * or 8-byte storage units if the offset is zero mod 2, 4, or 8,
2047      * respectively.  There are no other guarantees of atomicity.
2048      * <p>
2049      * 8-byte atomicity is only guaranteed on platforms on which
2050      * support atomic accesses to longs.
2051      *
2052      * @param o Java heap object in which the value resides, if any, else
2053      *        null
2054      * @param offset The offset in bytes from the start of the object
2055      * @return the value fetched from the indicated object
2056      * @throws RuntimeException No defined exceptions are thrown, not even
2057      *         {@link NullPointerException}
2058      * @since 9
2059      */
2060     @HotSpotIntrinsicCandidate
2061     public final long getLongUnaligned(Object o, long offset) {
2062         if ((offset & 7) == 0) {
2063             return getLong(o, offset);
2064         } else if ((offset & 3) == 0) {
2065             return makeLong(getInt(o, offset),
2066                             getInt(o, offset + 4));
2067         } else if ((offset & 1) == 0) {
2068             return makeLong(getShort(o, offset),
2069                             getShort(o, offset + 2),
2070                             getShort(o, offset + 4),
2071                             getShort(o, offset + 6));
2072         } else {
2073             return makeLong(getByte(o, offset),
2074                             getByte(o, offset + 1),
2075                             getByte(o, offset + 2),
2076                             getByte(o, offset + 3),
2077                             getByte(o, offset + 4),
2078                             getByte(o, offset + 5),
2079                             getByte(o, offset + 6),
2080                             getByte(o, offset + 7));
2081         }
2082     }
2083     /**
2084      * As {@link #getLongUnaligned(Object, long)} but with an
2085      * additional argument which specifies the endianness of the value
2086      * as stored in memory.
2087      *
2088      * @param o Java heap object in which the variable resides
2089      * @param offset The offset in bytes from the start of the object
2090      * @param bigEndian The endianness of the value
2091      * @return the value fetched from the indicated object
2092      * @since 9
2093      */
2094     public final long getLongUnaligned(Object o, long offset, boolean bigEndian) {
2095         return convEndian(bigEndian, getLongUnaligned(o, offset));
2096     }
2097 
2098     /** @see #getLongUnaligned(Object, long) */
2099     @HotSpotIntrinsicCandidate
2100     public final int getIntUnaligned(Object o, long offset) {
2101         if ((offset & 3) == 0) {
2102             return getInt(o, offset);
2103         } else if ((offset & 1) == 0) {
2104             return makeInt(getShort(o, offset),
2105                            getShort(o, offset + 2));
2106         } else {
2107             return makeInt(getByte(o, offset),
2108                            getByte(o, offset + 1),
2109                            getByte(o, offset + 2),
2110                            getByte(o, offset + 3));
2111         }
2112     }
2113     /** @see #getLongUnaligned(Object, long, boolean) */
2114     public final int getIntUnaligned(Object o, long offset, boolean bigEndian) {
2115         return convEndian(bigEndian, getIntUnaligned(o, offset));
2116     }
2117 
2118     /** @see #getLongUnaligned(Object, long) */
2119     @HotSpotIntrinsicCandidate
2120     public final short getShortUnaligned(Object o, long offset) {
2121         if ((offset & 1) == 0) {
2122             return getShort(o, offset);
2123         } else {
2124             return makeShort(getByte(o, offset),
2125                              getByte(o, offset + 1));
2126         }
2127     }
2128     /** @see #getLongUnaligned(Object, long, boolean) */
2129     public final short getShortUnaligned(Object o, long offset, boolean bigEndian) {
2130         return convEndian(bigEndian, getShortUnaligned(o, offset));
2131     }
2132 
2133     /** @see #getLongUnaligned(Object, long) */
2134     @HotSpotIntrinsicCandidate
2135     public final char getCharUnaligned(Object o, long offset) {
2136         if ((offset & 1) == 0) {
2137             return getChar(o, offset);
2138         } else {
2139             return (char)makeShort(getByte(o, offset),
2140                                    getByte(o, offset + 1));
2141         }
2142     }
2143 
2144     /** @see #getLongUnaligned(Object, long, boolean) */
2145     public final char getCharUnaligned(Object o, long offset, boolean bigEndian) {
2146         return convEndian(bigEndian, getCharUnaligned(o, offset));
2147     }
2148 
2149     /**
2150      * Stores a value at some byte offset into a given Java object.
2151      * <p>
2152      * The specification of this method is the same as {@link
2153      * #getLong(Object, long)} except that the offset does not need to
2154      * have been obtained from {@link #objectFieldOffset} on the
2155      * {@link java.lang.reflect.Field} of some Java field.  The value
2156      * in memory is raw data, and need not correspond to any Java
2157      * variable.  The endianness of the value in memory is the
2158      * endianness of the native platform.
2159      * <p>
2160      * The write will be atomic with respect to the largest power of
2161      * two that divides the GCD of the offset and the storage size.
2162      * For example, putLongUnaligned will make atomic writes of 2-, 4-,
2163      * or 8-byte storage units if the offset is zero mod 2, 4, or 8,
2164      * respectively.  There are no other guarantees of atomicity.
2165      * <p>
2166      * 8-byte atomicity is only guaranteed on platforms on which
2167      * support atomic accesses to longs.
2168      *
2169      * @param o Java heap object in which the value resides, if any, else
2170      *        null
2171      * @param offset The offset in bytes from the start of the object
2172      * @param x the value to store
2173      * @throws RuntimeException No defined exceptions are thrown, not even
2174      *         {@link NullPointerException}
2175      * @since 9
2176      */
2177     @HotSpotIntrinsicCandidate
2178     public final void putLongUnaligned(Object o, long offset, long x) {
2179         if ((offset & 7) == 0) {
2180             putLong(o, offset, x);
2181         } else if ((offset & 3) == 0) {
2182             putLongParts(o, offset,
2183                          (int)(x >> 0),
2184                          (int)(x >>> 32));
2185         } else if ((offset & 1) == 0) {
2186             putLongParts(o, offset,
2187                          (short)(x >>> 0),
2188                          (short)(x >>> 16),
2189                          (short)(x >>> 32),
2190                          (short)(x >>> 48));
2191         } else {
2192             putLongParts(o, offset,
2193                          (byte)(x >>> 0),
2194                          (byte)(x >>> 8),
2195                          (byte)(x >>> 16),
2196                          (byte)(x >>> 24),
2197                          (byte)(x >>> 32),
2198                          (byte)(x >>> 40),
2199                          (byte)(x >>> 48),
2200                          (byte)(x >>> 56));
2201         }
2202     }
2203 
2204     /**
2205      * As {@link #putLongUnaligned(Object, long, long)} but with an additional
2206      * argument which specifies the endianness of the value as stored in memory.
2207      * @param o Java heap object in which the value resides
2208      * @param offset The offset in bytes from the start of the object
2209      * @param x the value to store
2210      * @param bigEndian The endianness of the value
2211      * @throws RuntimeException No defined exceptions are thrown, not even
2212      *         {@link NullPointerException}
2213      * @since 9
2214      */
2215     public final void putLongUnaligned(Object o, long offset, long x, boolean bigEndian) {
2216         putLongUnaligned(o, offset, convEndian(bigEndian, x));
2217     }
2218 
2219     /** @see #putLongUnaligned(Object, long, long) */
2220     @HotSpotIntrinsicCandidate
2221     public final void putIntUnaligned(Object o, long offset, int x) {
2222         if ((offset & 3) == 0) {
2223             putInt(o, offset, x);
2224         } else if ((offset & 1) == 0) {
2225             putIntParts(o, offset,
2226                         (short)(x >> 0),
2227                         (short)(x >>> 16));
2228         } else {
2229             putIntParts(o, offset,
2230                         (byte)(x >>> 0),
2231                         (byte)(x >>> 8),
2232                         (byte)(x >>> 16),
2233                         (byte)(x >>> 24));
2234         }
2235     }
2236     /** @see #putLongUnaligned(Object, long, long, boolean) */
2237     public final void putIntUnaligned(Object o, long offset, int x, boolean bigEndian) {
2238         putIntUnaligned(o, offset, convEndian(bigEndian, x));
2239     }
2240 
2241     /** @see #putLongUnaligned(Object, long, long) */
2242     @HotSpotIntrinsicCandidate
2243     public final void putShortUnaligned(Object o, long offset, short x) {
2244         if ((offset & 1) == 0) {
2245             putShort(o, offset, x);
2246         } else {
2247             putShortParts(o, offset,
2248                           (byte)(x >>> 0),
2249                           (byte)(x >>> 8));
2250         }
2251     }
2252     /** @see #putLongUnaligned(Object, long, long, boolean) */
2253     public final void putShortUnaligned(Object o, long offset, short x, boolean bigEndian) {
2254         putShortUnaligned(o, offset, convEndian(bigEndian, x));
2255     }
2256 
2257     /** @see #putLongUnaligned(Object, long, long) */
2258     @HotSpotIntrinsicCandidate
2259     public final void putCharUnaligned(Object o, long offset, char x) {
2260         putShortUnaligned(o, offset, (short)x);
2261     }
2262     /** @see #putLongUnaligned(Object, long, long, boolean) */
2263     public final void putCharUnaligned(Object o, long offset, char x, boolean bigEndian) {
2264         putCharUnaligned(o, offset, convEndian(bigEndian, x));
2265     }
2266 
2267     // JVM interface methods
2268     // BE is true iff the native endianness of this platform is big.
2269     private static final boolean BE = theUnsafe.isBigEndian0();
2270 
2271     // unalignedAccess is true iff this platform can perform unaligned accesses.
2272     private static final boolean unalignedAccess = theUnsafe.unalignedAccess0();
2273 
2274     private static int pickPos(int top, int pos) { return BE ? top - pos : pos; }
2275 
2276     // These methods construct integers from bytes.  The byte ordering
2277     // is the native endianness of this platform.
2278     private static long makeLong(byte i0, byte i1, byte i2, byte i3, byte i4, byte i5, byte i6, byte i7) {
2279         return ((toUnsignedLong(i0) << pickPos(56, 0))
2280               | (toUnsignedLong(i1) << pickPos(56, 8))
2281               | (toUnsignedLong(i2) << pickPos(56, 16))
2282               | (toUnsignedLong(i3) << pickPos(56, 24))
2283               | (toUnsignedLong(i4) << pickPos(56, 32))
2284               | (toUnsignedLong(i5) << pickPos(56, 40))
2285               | (toUnsignedLong(i6) << pickPos(56, 48))
2286               | (toUnsignedLong(i7) << pickPos(56, 56)));
2287     }
2288     private static long makeLong(short i0, short i1, short i2, short i3) {
2289         return ((toUnsignedLong(i0) << pickPos(48, 0))
2290               | (toUnsignedLong(i1) << pickPos(48, 16))
2291               | (toUnsignedLong(i2) << pickPos(48, 32))
2292               | (toUnsignedLong(i3) << pickPos(48, 48)));
2293     }
2294     private static long makeLong(int i0, int i1) {
2295         return (toUnsignedLong(i0) << pickPos(32, 0))
2296              | (toUnsignedLong(i1) << pickPos(32, 32));
2297     }
2298     private static int makeInt(short i0, short i1) {
2299         return (toUnsignedInt(i0) << pickPos(16, 0))
2300              | (toUnsignedInt(i1) << pickPos(16, 16));
2301     }
2302     private static int makeInt(byte i0, byte i1, byte i2, byte i3) {
2303         return ((toUnsignedInt(i0) << pickPos(24, 0))
2304               | (toUnsignedInt(i1) << pickPos(24, 8))
2305               | (toUnsignedInt(i2) << pickPos(24, 16))
2306               | (toUnsignedInt(i3) << pickPos(24, 24)));
2307     }
2308     private static short makeShort(byte i0, byte i1) {
2309         return (short)((toUnsignedInt(i0) << pickPos(8, 0))
2310                      | (toUnsignedInt(i1) << pickPos(8, 8)));
2311     }
2312 
2313     private static byte  pick(byte  le, byte  be) { return BE ? be : le; }
2314     private static short pick(short le, short be) { return BE ? be : le; }
2315     private static int   pick(int   le, int   be) { return BE ? be : le; }
2316 
2317     // These methods write integers to memory from smaller parts
2318     // provided by their caller.  The ordering in which these parts
2319     // are written is the native endianness of this platform.
2320     private void putLongParts(Object o, long offset, byte i0, byte i1, byte i2, byte i3, byte i4, byte i5, byte i6, byte i7) {
2321         putByte(o, offset + 0, pick(i0, i7));
2322         putByte(o, offset + 1, pick(i1, i6));
2323         putByte(o, offset + 2, pick(i2, i5));
2324         putByte(o, offset + 3, pick(i3, i4));
2325         putByte(o, offset + 4, pick(i4, i3));
2326         putByte(o, offset + 5, pick(i5, i2));
2327         putByte(o, offset + 6, pick(i6, i1));
2328         putByte(o, offset + 7, pick(i7, i0));
2329     }
2330     private void putLongParts(Object o, long offset, short i0, short i1, short i2, short i3) {
2331         putShort(o, offset + 0, pick(i0, i3));
2332         putShort(o, offset + 2, pick(i1, i2));
2333         putShort(o, offset + 4, pick(i2, i1));
2334         putShort(o, offset + 6, pick(i3, i0));
2335     }
2336     private void putLongParts(Object o, long offset, int i0, int i1) {
2337         putInt(o, offset + 0, pick(i0, i1));
2338         putInt(o, offset + 4, pick(i1, i0));
2339     }
2340     private void putIntParts(Object o, long offset, short i0, short i1) {
2341         putShort(o, offset + 0, pick(i0, i1));
2342         putShort(o, offset + 2, pick(i1, i0));
2343     }
2344     private void putIntParts(Object o, long offset, byte i0, byte i1, byte i2, byte i3) {
2345         putByte(o, offset + 0, pick(i0, i3));
2346         putByte(o, offset + 1, pick(i1, i2));
2347         putByte(o, offset + 2, pick(i2, i1));
2348         putByte(o, offset + 3, pick(i3, i0));
2349     }
2350     private void putShortParts(Object o, long offset, byte i0, byte i1) {
2351         putByte(o, offset + 0, pick(i0, i1));
2352         putByte(o, offset + 1, pick(i1, i0));
2353     }
2354 
2355     // Zero-extend an integer
2356     private static int toUnsignedInt(byte n)    { return n & 0xff; }
2357     private static int toUnsignedInt(short n)   { return n & 0xffff; }
2358     private static long toUnsignedLong(byte n)  { return n & 0xffl; }
2359     private static long toUnsignedLong(short n) { return n & 0xffffl; }
2360     private static long toUnsignedLong(int n)   { return n & 0xffffffffl; }
2361 
2362     // Maybe byte-reverse an integer
2363     private static char convEndian(boolean big, char n)   { return big == BE ? n : Character.reverseBytes(n); }
2364     private static short convEndian(boolean big, short n) { return big == BE ? n : Short.reverseBytes(n)    ; }
2365     private static int convEndian(boolean big, int n)     { return big == BE ? n : Integer.reverseBytes(n)  ; }
2366     private static long convEndian(boolean big, long n)   { return big == BE ? n : Long.reverseBytes(n)     ; }
2367 
2368 
2369 
2370     private native long allocateMemory0(long bytes);
2371     private native long reallocateMemory0(long address, long bytes);
2372     private native void freeMemory0(long address);
2373     private native void setMemory0(Object o, long offset, long bytes, byte value);
2374     @HotSpotIntrinsicCandidate
2375     private native void copyMemory0(Object srcBase, long srcOffset, Object destBase, long destOffset, long bytes);
2376     private native void copySwapMemory0(Object srcBase, long srcOffset, Object destBase, long destOffset, long bytes, long elemSize);
2377     private native long objectFieldOffset0(Field f);
2378     private native long staticFieldOffset0(Field f);
2379     private native Object staticFieldBase0(Field f);
2380     private native boolean shouldBeInitialized0(Class<?> c);
2381     private native void ensureClassInitialized0(Class<?> c);
2382     private native int arrayBaseOffset0(Class<?> arrayClass);
2383     private native int arrayIndexScale0(Class<?> arrayClass);
2384     private native int addressSize0();
2385     private native Class<?> defineAnonymousClass0(Class<?> hostClass, byte[] data, Object[] cpPatches);
2386     private native int getLoadAverage0(double[] loadavg, int nelems);
2387     private native boolean unalignedAccess0();
2388     private native boolean isBigEndian0();
2389 }