1 /*
   2  * Copyright (c) 2000, 2015, 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 sun.misc;
  27 
  28 import java.lang.reflect.Field;
  29 import java.security.ProtectionDomain;
  30 
  31 import sun.reflect.CallerSensitive;
  32 import sun.reflect.Reflection;
  33 
  34 
  35 /**
  36  * A collection of methods for performing low-level, unsafe operations.
  37  * Although the class and all methods are public, use of this class is
  38  * limited because only trusted code can obtain instances of it.
  39  *
  40  * @author John R. Rose
  41  * @see #getUnsafe
  42  */
  43 
  44 public final class Unsafe {
  45 
  46     private static native void registerNatives();
  47     static {
  48         registerNatives();
  49         sun.reflect.Reflection.registerMethodsToFilter(Unsafe.class, "getUnsafe");
  50     }
  51 
  52     private Unsafe() {}
  53 
  54     private static final Unsafe theUnsafe = new Unsafe();
  55 
  56     /**
  57      * Provides the caller with the capability of performing unsafe
  58      * operations.
  59      *
  60      * <p>The returned {@code Unsafe} object should be carefully guarded
  61      * by the caller, since it can be used to read and write data at arbitrary
  62      * memory addresses.  It must never be passed to untrusted code.
  63      *
  64      * <p>Most methods in this class are very low-level, and correspond to a
  65      * small number of hardware instructions (on typical machines).  Compilers
  66      * are encouraged to optimize these methods accordingly.
  67      *
  68      * <p>Here is a suggested idiom for using unsafe operations:
  69      *
  70      * <pre> {@code
  71      * class MyTrustedClass {
  72      *   private static final Unsafe unsafe = Unsafe.getUnsafe();
  73      *   ...
  74      *   private long myCountAddress = ...;
  75      *   public int getCount() { return unsafe.getByte(myCountAddress); }
  76      * }}</pre>
  77      *
  78      * (It may assist compilers to make the local variable {@code final}.)
  79      *
  80      * @throws  SecurityException  if a security manager exists and its
  81      *          {@code checkPropertiesAccess} method doesn't allow
  82      *          access to the system properties.
  83      */
  84     @CallerSensitive
  85     public static Unsafe getUnsafe() {
  86         Class<?> caller = Reflection.getCallerClass();
  87         if (!VM.isSystemDomainLoader(caller.getClassLoader()))
  88             throw new SecurityException("Unsafe");
  89         return theUnsafe;
  90     }
  91 
  92     /// peek and poke operations
  93     /// (compilers should optimize these to memory ops)
  94 
  95     // These work on object fields in the Java heap.
  96     // They will not work on elements of packed arrays.
  97 
  98     /**
  99      * Fetches a value from a given Java variable.
 100      * More specifically, fetches a field or array element within the given
 101      * object {@code o} at the given offset, or (if {@code o} is null)
 102      * from the memory address whose numerical value is the given offset.
 103      * <p>
 104      * The results are undefined unless one of the following cases is true:
 105      * <ul>
 106      * <li>The offset was obtained from {@link #objectFieldOffset} on
 107      * the {@link java.lang.reflect.Field} of some Java field and the object
 108      * referred to by {@code o} is of a class compatible with that
 109      * field's class.
 110      *
 111      * <li>The offset and object reference {@code o} (either null or
 112      * non-null) were both obtained via {@link #staticFieldOffset}
 113      * and {@link #staticFieldBase} (respectively) from the
 114      * reflective {@link Field} representation of some Java field.
 115      *
 116      * <li>The object referred to by {@code o} is an array, and the offset
 117      * is an integer of the form {@code B+N*S}, where {@code N} is
 118      * a valid index into the array, and {@code B} and {@code S} are
 119      * the values obtained by {@link #arrayBaseOffset} and {@link
 120      * #arrayIndexScale} (respectively) from the array's class.  The value
 121      * referred to is the {@code N}<em>th</em> element of the array.
 122      *
 123      * </ul>
 124      * <p>
 125      * If one of the above cases is true, the call references a specific Java
 126      * variable (field or array element).  However, the results are undefined
 127      * if that variable is not in fact of the type returned by this method.
 128      * <p>
 129      * This method refers to a variable by means of two parameters, and so
 130      * it provides (in effect) a <em>double-register</em> addressing mode
 131      * for Java variables.  When the object reference is null, this method
 132      * uses its offset as an absolute address.  This is similar in operation
 133      * to methods such as {@link #getInt(long)}, which provide (in effect) a
 134      * <em>single-register</em> addressing mode for non-Java variables.
 135      * However, because Java variables may have a different layout in memory
 136      * from non-Java variables, programmers should not assume that these
 137      * two addressing modes are ever equivalent.  Also, programmers should
 138      * remember that offsets from the double-register addressing mode cannot
 139      * be portably confused with longs used in the single-register addressing
 140      * mode.
 141      *
 142      * @param o Java heap object in which the variable resides, if any, else
 143      *        null
 144      * @param offset indication of where the variable resides in a Java heap
 145      *        object, if any, else a memory address locating the variable
 146      *        statically
 147      * @return the value fetched from the indicated Java variable
 148      * @throws RuntimeException No defined exceptions are thrown, not even
 149      *         {@link NullPointerException}
 150      */
 151     public native int getInt(Object o, long offset);
 152 
 153     /**
 154      * Stores a value into a given Java variable.
 155      * <p>
 156      * The first two parameters are interpreted exactly as with
 157      * {@link #getInt(Object, long)} to refer to a specific
 158      * Java variable (field or array element).  The given value
 159      * is stored into that variable.
 160      * <p>
 161      * The variable must be of the same type as the method
 162      * parameter {@code x}.
 163      *
 164      * @param o Java heap object in which the variable resides, if any, else
 165      *        null
 166      * @param offset indication of where the variable resides in a Java heap
 167      *        object, if any, else a memory address locating the variable
 168      *        statically
 169      * @param x the value to store into the indicated Java variable
 170      * @throws RuntimeException No defined exceptions are thrown, not even
 171      *         {@link NullPointerException}
 172      */
 173     public native void putInt(Object o, long offset, int x);
 174 
 175     /**
 176      * Fetches a reference value from a given Java variable.
 177      * @see #getInt(Object, long)
 178      */
 179     public native Object getObject(Object o, long offset);
 180 
 181     /**
 182      * Stores a reference value into a given Java variable.
 183      * <p>
 184      * Unless the reference {@code x} being stored is either null
 185      * or matches the field type, the results are undefined.
 186      * If the reference {@code o} is non-null, card marks or
 187      * other store barriers for that object (if the VM requires them)
 188      * are updated.
 189      * @see #putInt(Object, long, int)
 190      */
 191     public native void putObject(Object o, long offset, Object x);
 192 
 193     /** @see #getInt(Object, long) */
 194     public native boolean getBoolean(Object o, long offset);
 195     /** @see #putInt(Object, long, int) */
 196     public native void    putBoolean(Object o, long offset, boolean x);
 197     /** @see #getInt(Object, long) */
 198     public native byte    getByte(Object o, long offset);
 199     /** @see #putInt(Object, long, int) */
 200     public native void    putByte(Object o, long offset, byte x);
 201     /** @see #getInt(Object, long) */
 202     public native short   getShort(Object o, long offset);
 203     /** @see #putInt(Object, long, int) */
 204     public native void    putShort(Object o, long offset, short x);
 205     /** @see #getInt(Object, long) */
 206     public native char    getChar(Object o, long offset);
 207     /** @see #putInt(Object, long, int) */
 208     public native void    putChar(Object o, long offset, char x);
 209     /** @see #getInt(Object, long) */
 210     public native long    getLong(Object o, long offset);
 211     /** @see #putInt(Object, long, int) */
 212     public native void    putLong(Object o, long offset, long x);
 213     /** @see #getInt(Object, long) */
 214     public native float   getFloat(Object o, long offset);
 215     /** @see #putInt(Object, long, int) */
 216     public native void    putFloat(Object o, long offset, float x);
 217     /** @see #getInt(Object, long) */
 218     public native double  getDouble(Object o, long offset);
 219     /** @see #putInt(Object, long, int) */
 220     public native void    putDouble(Object o, long offset, double x);
 221 
 222     // These read VM internal data.
 223 
 224     /**
 225      * Fetches an uncompressed reference value from a given native variable
 226      * ignoring the VM's compressed references mode.
 227      *
 228      * @param address a memory address locating the variable
 229      * @return the value fetched from the indicated native variable
 230      */
 231     public native Object getUncompressedObject(long address);
 232 
 233     /**
 234      * Fetches the {@link java.lang.Class} Java mirror for the given native
 235      * metaspace {@code Klass} pointer.
 236      *
 237      * @param metaspaceKlass a native metaspace {@code Klass} pointer
 238      * @return the {@link java.lang.Class} Java mirror
 239      */
 240     public native Class<?> getJavaMirror(long metaspaceKlass);
 241 
 242     /**
 243      * Fetches a native metaspace {@code Klass} pointer for the given Java
 244      * object.
 245      *
 246      * @param o Java heap object for which to fetch the class pointer
 247      * @return a native metaspace {@code Klass} pointer
 248      */
 249     public native long getKlassPointer(Object o);
 250 
 251     // These work on values in the C heap.
 252 
 253     /**
 254      * Fetches a value from a given memory address.  If the address is zero, or
 255      * does not point into a block obtained from {@link #allocateMemory}, the
 256      * results are undefined.
 257      *
 258      * @see #allocateMemory
 259      */
 260     public native byte    getByte(long address);
 261 
 262     /**
 263      * Stores a value into a given memory address.  If the address is zero, or
 264      * does not point into a block obtained from {@link #allocateMemory}, the
 265      * results are undefined.
 266      *
 267      * @see #getByte(long)
 268      */
 269     public native void    putByte(long address, byte x);
 270 
 271     /** @see #getByte(long) */
 272     public native short   getShort(long address);
 273     /** @see #putByte(long, byte) */
 274     public native void    putShort(long address, short x);
 275     /** @see #getByte(long) */
 276     public native char    getChar(long address);
 277     /** @see #putByte(long, byte) */
 278     public native void    putChar(long address, char x);
 279     /** @see #getByte(long) */
 280     public native int     getInt(long address);
 281     /** @see #putByte(long, byte) */
 282     public native void    putInt(long address, int x);
 283     /** @see #getByte(long) */
 284     public native long    getLong(long address);
 285     /** @see #putByte(long, byte) */
 286     public native void    putLong(long address, long x);
 287     /** @see #getByte(long) */
 288     public native float   getFloat(long address);
 289     /** @see #putByte(long, byte) */
 290     public native void    putFloat(long address, float x);
 291     /** @see #getByte(long) */
 292     public native double  getDouble(long address);
 293     /** @see #putByte(long, byte) */
 294     public native void    putDouble(long address, double x);
 295 
 296     /**
 297      * Fetches a native pointer from a given memory address.  If the address is
 298      * zero, or does not point into a block obtained from {@link
 299      * #allocateMemory}, the results are undefined.
 300      *
 301      * <p>If the native pointer is less than 64 bits wide, it is extended as
 302      * an unsigned number to a Java long.  The pointer may be indexed by any
 303      * given byte offset, simply by adding that offset (as a simple integer) to
 304      * the long representing the pointer.  The number of bytes actually read
 305      * from the target address may be determined by consulting {@link
 306      * #addressSize}.
 307      *
 308      * @see #allocateMemory
 309      */
 310     public native long getAddress(long address);
 311 
 312     /**
 313      * Stores a native pointer into a given memory address.  If the address is
 314      * zero, or does not point into a block obtained from {@link
 315      * #allocateMemory}, the results are undefined.
 316      *
 317      * <p>The number of bytes actually written at the target address may be
 318      * determined by consulting {@link #addressSize}.
 319      *
 320      * @see #getAddress(long)
 321      */
 322     public native void putAddress(long address, long x);
 323 
 324     /// wrappers for malloc, realloc, free:
 325 
 326     /**
 327      * Allocates a new block of native memory, of the given size in bytes.  The
 328      * contents of the memory are uninitialized; they will generally be
 329      * garbage.  The resulting native pointer will never be zero, and will be
 330      * aligned for all value types.  Dispose of this memory by calling {@link
 331      * #freeMemory}, or resize it with {@link #reallocateMemory}.
 332      *
 333      * @throws IllegalArgumentException if the size is negative or too large
 334      *         for the native size_t type
 335      *
 336      * @throws OutOfMemoryError if the allocation is refused by the system
 337      *
 338      * @see #getByte(long)
 339      * @see #putByte(long, byte)
 340      */
 341     public native long allocateMemory(long bytes);
 342 
 343     /**
 344      * Resizes a new block of native memory, to the given size in bytes.  The
 345      * contents of the new block past the size of the old block are
 346      * uninitialized; they will generally be garbage.  The resulting native
 347      * pointer will be zero if and only if the requested size is zero.  The
 348      * resulting native pointer will be aligned for all value types.  Dispose
 349      * of this memory by calling {@link #freeMemory}, or resize it with {@link
 350      * #reallocateMemory}.  The address passed to this method may be null, in
 351      * which case an allocation will be performed.
 352      *
 353      * @throws IllegalArgumentException if the size is negative or too large
 354      *         for the native size_t type
 355      *
 356      * @throws OutOfMemoryError if the allocation is refused by the system
 357      *
 358      * @see #allocateMemory
 359      */
 360     public native long reallocateMemory(long address, long bytes);
 361 
 362     /**
 363      * Sets all bytes in a given block of memory to a fixed value
 364      * (usually zero).
 365      *
 366      * <p>This method determines a block's base address by means of two parameters,
 367      * and so it provides (in effect) a <em>double-register</em> addressing mode,
 368      * as discussed in {@link #getInt(Object,long)}.  When the object reference is null,
 369      * the offset supplies an absolute base address.
 370      *
 371      * <p>The stores are in coherent (atomic) units of a size determined
 372      * by the address and length parameters.  If the effective address and
 373      * length are all even modulo 8, the stores take place in 'long' units.
 374      * If the effective address and length are (resp.) even modulo 4 or 2,
 375      * the stores take place in units of 'int' or 'short'.
 376      *
 377      * @since 1.7
 378      */
 379     public native void setMemory(Object o, long offset, long bytes, byte value);
 380 
 381     /**
 382      * Sets all bytes in a given block of memory to a fixed value
 383      * (usually zero).  This provides a <em>single-register</em> addressing mode,
 384      * as discussed in {@link #getInt(Object,long)}.
 385      *
 386      * <p>Equivalent to {@code setMemory(null, address, bytes, value)}.
 387      */
 388     public void setMemory(long address, long bytes, byte value) {
 389         setMemory(null, address, bytes, value);
 390     }
 391 
 392     /**
 393      * Sets all bytes in a given block of memory to a copy of another
 394      * block.
 395      *
 396      * <p>This method determines each block's base address by means of two parameters,
 397      * and so it provides (in effect) a <em>double-register</em> addressing mode,
 398      * as discussed in {@link #getInt(Object,long)}.  When the object reference is null,
 399      * the offset supplies an absolute base address.
 400      *
 401      * <p>The transfers are in coherent (atomic) units of a size determined
 402      * by the address and length parameters.  If the effective addresses and
 403      * length are all even modulo 8, the transfer takes place in 'long' units.
 404      * If the effective addresses and length are (resp.) even modulo 4 or 2,
 405      * the transfer takes place in units of 'int' or 'short'.
 406      *
 407      * @since 1.7
 408      */
 409     public native void copyMemory(Object srcBase, long srcOffset,
 410                                   Object destBase, long destOffset,
 411                                   long bytes);
 412     /**
 413      * Sets all bytes in a given block of memory to a copy of another
 414      * block.  This provides a <em>single-register</em> addressing mode,
 415      * as discussed in {@link #getInt(Object,long)}.
 416      *
 417      * Equivalent to {@code copyMemory(null, srcAddress, null, destAddress, bytes)}.
 418      */
 419     public void copyMemory(long srcAddress, long destAddress, long bytes) {
 420         copyMemory(null, srcAddress, null, destAddress, bytes);
 421     }
 422 
 423     /**
 424      * Disposes of a block of native memory, as obtained from {@link
 425      * #allocateMemory} or {@link #reallocateMemory}.  The address passed to
 426      * this method may be null, in which case no action is taken.
 427      *
 428      * @see #allocateMemory
 429      */
 430     public native void freeMemory(long address);
 431 
 432     /// random queries
 433 
 434     /**
 435      * This constant differs from all results that will ever be returned from
 436      * {@link #staticFieldOffset}, {@link #objectFieldOffset},
 437      * or {@link #arrayBaseOffset}.
 438      */
 439     public static final int INVALID_FIELD_OFFSET   = -1;
 440 
 441     /**
 442      * Reports the location of a given field in the storage allocation of its
 443      * class.  Do not expect to perform any sort of arithmetic on this offset;
 444      * it is just a cookie which is passed to the unsafe heap memory accessors.
 445      *
 446      * <p>Any given field will always have the same offset and base, and no
 447      * two distinct fields of the same class will ever have the same offset
 448      * and base.
 449      *
 450      * <p>As of 1.4.1, offsets for fields are represented as long values,
 451      * although the Sun JVM does not use the most significant 32 bits.
 452      * However, JVM implementations which store static fields at absolute
 453      * addresses can use long offsets and null base pointers to express
 454      * the field locations in a form usable by {@link #getInt(Object,long)}.
 455      * Therefore, code which will be ported to such JVMs on 64-bit platforms
 456      * must preserve all bits of static field offsets.
 457      * @see #getInt(Object, long)
 458      */
 459     public native long objectFieldOffset(Field f);
 460 
 461     /**
 462      * Reports the location of a given static field, in conjunction with {@link
 463      * #staticFieldBase}.
 464      * <p>Do not expect to perform any sort of arithmetic on this offset;
 465      * it is just a cookie which is passed to the unsafe heap memory accessors.
 466      *
 467      * <p>Any given field will always have the same offset, and no two distinct
 468      * fields of the same class will ever have the same offset.
 469      *
 470      * <p>As of 1.4.1, offsets for fields are represented as long values,
 471      * although the Sun JVM does not use the most significant 32 bits.
 472      * It is hard to imagine a JVM technology which needs more than
 473      * a few bits to encode an offset within a non-array object,
 474      * However, for consistency with other methods in this class,
 475      * this method reports its result as a long value.
 476      * @see #getInt(Object, long)
 477      */
 478     public native long staticFieldOffset(Field f);
 479 
 480     /**
 481      * Reports the location of a given static field, in conjunction with {@link
 482      * #staticFieldOffset}.
 483      * <p>Fetch the base "Object", if any, with which static fields of the
 484      * given class can be accessed via methods like {@link #getInt(Object,
 485      * long)}.  This value may be null.  This value may refer to an object
 486      * which is a "cookie", not guaranteed to be a real Object, and it should
 487      * not be used in any way except as argument to the get and put routines in
 488      * this class.
 489      */
 490     public native Object staticFieldBase(Field f);
 491 
 492     /**
 493      * Detects if the given class may need to be initialized. This is often
 494      * needed in conjunction with obtaining the static field base of a
 495      * class.
 496      * @return false only if a call to {@code ensureClassInitialized} would have no effect
 497      */
 498     public native boolean shouldBeInitialized(Class<?> c);
 499 
 500     /**
 501      * Ensures the given class has been initialized. This is often
 502      * needed in conjunction with obtaining the static field base of a
 503      * class.
 504      */
 505     public native void ensureClassInitialized(Class<?> c);
 506 
 507     /**
 508      * Reports the offset of the first element in the storage allocation of a
 509      * given array class.  If {@link #arrayIndexScale} returns a non-zero value
 510      * for the same class, you may use that scale factor, together with this
 511      * base offset, to form new offsets to access elements of arrays of the
 512      * given class.
 513      *
 514      * @see #getInt(Object, long)
 515      * @see #putInt(Object, long, int)
 516      */
 517     public native int arrayBaseOffset(Class<?> arrayClass);
 518 
 519     /** The value of {@code arrayBaseOffset(boolean[].class)} */
 520     public static final int ARRAY_BOOLEAN_BASE_OFFSET
 521             = theUnsafe.arrayBaseOffset(boolean[].class);
 522 
 523     /** The value of {@code arrayBaseOffset(byte[].class)} */
 524     public static final int ARRAY_BYTE_BASE_OFFSET
 525             = theUnsafe.arrayBaseOffset(byte[].class);
 526 
 527     /** The value of {@code arrayBaseOffset(short[].class)} */
 528     public static final int ARRAY_SHORT_BASE_OFFSET
 529             = theUnsafe.arrayBaseOffset(short[].class);
 530 
 531     /** The value of {@code arrayBaseOffset(char[].class)} */
 532     public static final int ARRAY_CHAR_BASE_OFFSET
 533             = theUnsafe.arrayBaseOffset(char[].class);
 534 
 535     /** The value of {@code arrayBaseOffset(int[].class)} */
 536     public static final int ARRAY_INT_BASE_OFFSET
 537             = theUnsafe.arrayBaseOffset(int[].class);
 538 
 539     /** The value of {@code arrayBaseOffset(long[].class)} */
 540     public static final int ARRAY_LONG_BASE_OFFSET
 541             = theUnsafe.arrayBaseOffset(long[].class);
 542 
 543     /** The value of {@code arrayBaseOffset(float[].class)} */
 544     public static final int ARRAY_FLOAT_BASE_OFFSET
 545             = theUnsafe.arrayBaseOffset(float[].class);
 546 
 547     /** The value of {@code arrayBaseOffset(double[].class)} */
 548     public static final int ARRAY_DOUBLE_BASE_OFFSET
 549             = theUnsafe.arrayBaseOffset(double[].class);
 550 
 551     /** The value of {@code arrayBaseOffset(Object[].class)} */
 552     public static final int ARRAY_OBJECT_BASE_OFFSET
 553             = theUnsafe.arrayBaseOffset(Object[].class);
 554 
 555     /**
 556      * Reports the scale factor for addressing elements in the storage
 557      * allocation of a given array class.  However, arrays of "narrow" types
 558      * will generally not work properly with accessors like {@link
 559      * #getByte(Object, long)}, so the scale factor for such classes is reported
 560      * as zero.
 561      *
 562      * @see #arrayBaseOffset
 563      * @see #getInt(Object, long)
 564      * @see #putInt(Object, long, int)
 565      */
 566     public native int arrayIndexScale(Class<?> arrayClass);
 567 
 568     /** The value of {@code arrayIndexScale(boolean[].class)} */
 569     public static final int ARRAY_BOOLEAN_INDEX_SCALE
 570             = theUnsafe.arrayIndexScale(boolean[].class);
 571 
 572     /** The value of {@code arrayIndexScale(byte[].class)} */
 573     public static final int ARRAY_BYTE_INDEX_SCALE
 574             = theUnsafe.arrayIndexScale(byte[].class);
 575 
 576     /** The value of {@code arrayIndexScale(short[].class)} */
 577     public static final int ARRAY_SHORT_INDEX_SCALE
 578             = theUnsafe.arrayIndexScale(short[].class);
 579 
 580     /** The value of {@code arrayIndexScale(char[].class)} */
 581     public static final int ARRAY_CHAR_INDEX_SCALE
 582             = theUnsafe.arrayIndexScale(char[].class);
 583 
 584     /** The value of {@code arrayIndexScale(int[].class)} */
 585     public static final int ARRAY_INT_INDEX_SCALE
 586             = theUnsafe.arrayIndexScale(int[].class);
 587 
 588     /** The value of {@code arrayIndexScale(long[].class)} */
 589     public static final int ARRAY_LONG_INDEX_SCALE
 590             = theUnsafe.arrayIndexScale(long[].class);
 591 
 592     /** The value of {@code arrayIndexScale(float[].class)} */
 593     public static final int ARRAY_FLOAT_INDEX_SCALE
 594             = theUnsafe.arrayIndexScale(float[].class);
 595 
 596     /** The value of {@code arrayIndexScale(double[].class)} */
 597     public static final int ARRAY_DOUBLE_INDEX_SCALE
 598             = theUnsafe.arrayIndexScale(double[].class);
 599 
 600     /** The value of {@code arrayIndexScale(Object[].class)} */
 601     public static final int ARRAY_OBJECT_INDEX_SCALE
 602             = theUnsafe.arrayIndexScale(Object[].class);
 603 
 604     /**
 605      * Reports the size in bytes of a native pointer, as stored via {@link
 606      * #putAddress}.  This value will be either 4 or 8.  Note that the sizes of
 607      * other primitive types (as stored in native memory blocks) is determined
 608      * fully by their information content.
 609      */
 610     public native int addressSize();
 611 
 612     /** The value of {@code addressSize()} */
 613     public static final int ADDRESS_SIZE = theUnsafe.addressSize();
 614 
 615     /**
 616      * Reports the size in bytes of a native memory page (whatever that is).
 617      * This value will always be a power of two.
 618      */
 619     public native int pageSize();
 620 
 621 
 622     /// random trusted operations from JNI:
 623 
 624     /**
 625      * Tells the VM to define a class, without security checks.  By default, the
 626      * class loader and protection domain come from the caller's class.
 627      */
 628     public native Class<?> defineClass(String name, byte[] b, int off, int len,
 629                                        ClassLoader loader,
 630                                        ProtectionDomain protectionDomain);
 631 
 632     /**
 633      * Defines a class but does not make it known to the class loader or system dictionary.
 634      * <p>
 635      * For each CP entry, the corresponding CP patch must either be null or have
 636      * the a format that matches its tag:
 637      * <ul>
 638      * <li>Integer, Long, Float, Double: the corresponding wrapper object type from java.lang
 639      * <li>Utf8: a string (must have suitable syntax if used as signature or name)
 640      * <li>Class: any java.lang.Class object
 641      * <li>String: any object (not just a java.lang.String)
 642      * <li>InterfaceMethodRef: (NYI) a method handle to invoke on that call site's arguments
 643      * </ul>
 644      * @param hostClass context for linkage, access control, protection domain, and class loader
 645      * @param data      bytes of a class file
 646      * @param cpPatches where non-null entries exist, they replace corresponding CP entries in data
 647      */
 648     public native Class<?> defineAnonymousClass(Class<?> hostClass, byte[] data, Object[] cpPatches);
 649 
 650     /**
 651      * Allocates an instance but does not run any constructor.
 652      * Initializes the class if it has not yet been.
 653      */
 654     public native Object allocateInstance(Class<?> cls)
 655         throws InstantiationException;
 656 
 657     /** Throws the exception without telling the verifier. */
 658     public native void throwException(Throwable ee);
 659 
 660     /**
 661      * Atomically updates Java variable to {@code x} if it is currently
 662      * holding {@code expected}.
 663      *
 664      * <p>This operation has memory semantics of a {@code volatile} read
 665      * and write.  Corresponds to C11 atomic_compare_exchange_strong.
 666      *
 667      * @return {@code true} if successful
 668      */
 669     public final native boolean compareAndSwapObject(Object o, long offset,
 670                                                      Object expected,
 671                                                      Object x);
 672 
 673     /**
 674      * Atomically updates Java variable to {@code x} if it is currently
 675      * holding {@code expected}.
 676      *
 677      * <p>This operation has memory semantics of a {@code volatile} read
 678      * and write.  Corresponds to C11 atomic_compare_exchange_strong.
 679      *
 680      * @return {@code true} if successful
 681      */
 682     public final native boolean compareAndSwapInt(Object o, long offset,
 683                                                   int expected,
 684                                                   int x);
 685 
 686     /**
 687      * Atomically updates Java variable to {@code x} if it is currently
 688      * holding {@code expected}.
 689      *
 690      * <p>This operation has memory semantics of a {@code volatile} read
 691      * and write.  Corresponds to C11 atomic_compare_exchange_strong.
 692      *
 693      * @return {@code true} if successful
 694      */
 695     public final native boolean compareAndSwapLong(Object o, long offset,
 696                                                    long expected,
 697                                                    long x);
 698 
 699     /**
 700      * Fetches a reference value from a given Java variable, with volatile
 701      * load semantics. Otherwise identical to {@link #getObject(Object, long)}
 702      */
 703     public native Object getObjectVolatile(Object o, long offset);
 704 
 705     /**
 706      * Stores a reference value into a given Java variable, with
 707      * volatile store semantics. Otherwise identical to {@link #putObject(Object, long, Object)}
 708      */
 709     public native void    putObjectVolatile(Object o, long offset, Object x);
 710 
 711     /** Volatile version of {@link #getInt(Object, long)}  */
 712     public native int     getIntVolatile(Object o, long offset);
 713 
 714     /** Volatile version of {@link #putInt(Object, long, int)}  */
 715     public native void    putIntVolatile(Object o, long offset, int x);
 716 
 717     /** Volatile version of {@link #getBoolean(Object, long)}  */
 718     public native boolean getBooleanVolatile(Object o, long offset);
 719 
 720     /** Volatile version of {@link #putBoolean(Object, long, boolean)}  */
 721     public native void    putBooleanVolatile(Object o, long offset, boolean x);
 722 
 723     /** Volatile version of {@link #getByte(Object, long)}  */
 724     public native byte    getByteVolatile(Object o, long offset);
 725 
 726     /** Volatile version of {@link #putByte(Object, long, byte)}  */
 727     public native void    putByteVolatile(Object o, long offset, byte x);
 728 
 729     /** Volatile version of {@link #getShort(Object, long)}  */
 730     public native short   getShortVolatile(Object o, long offset);
 731 
 732     /** Volatile version of {@link #putShort(Object, long, short)}  */
 733     public native void    putShortVolatile(Object o, long offset, short x);
 734 
 735     /** Volatile version of {@link #getChar(Object, long)}  */
 736     public native char    getCharVolatile(Object o, long offset);
 737 
 738     /** Volatile version of {@link #putChar(Object, long, char)}  */
 739     public native void    putCharVolatile(Object o, long offset, char x);
 740 
 741     /** Volatile version of {@link #getLong(Object, long)}  */
 742     public native long    getLongVolatile(Object o, long offset);
 743 
 744     /** Volatile version of {@link #putLong(Object, long, long)}  */
 745     public native void    putLongVolatile(Object o, long offset, long x);
 746 
 747     /** Volatile version of {@link #getFloat(Object, long)}  */
 748     public native float   getFloatVolatile(Object o, long offset);
 749 
 750     /** Volatile version of {@link #putFloat(Object, long, float)}  */
 751     public native void    putFloatVolatile(Object o, long offset, float x);
 752 
 753     /** Volatile version of {@link #getDouble(Object, long)}  */
 754     public native double  getDoubleVolatile(Object o, long offset);
 755 
 756     /** Volatile version of {@link #putDouble(Object, long, double)}  */
 757     public native void    putDoubleVolatile(Object o, long offset, double x);
 758 
 759     /**
 760      * Version of {@link #putObjectVolatile(Object, long, Object)}
 761      * that does not guarantee immediate visibility of the store to
 762      * other threads. This method is generally only useful if the
 763      * underlying field is a Java volatile (or if an array cell, one
 764      * that is otherwise only accessed using volatile accesses).
 765      *
 766      * Corresponds to C11 atomic_store_explicit(..., memory_order_release).
 767      */
 768     public native void    putOrderedObject(Object o, long offset, Object x);
 769 
 770     /** Ordered/Lazy version of {@link #putIntVolatile(Object, long, int)}  */
 771     public native void    putOrderedInt(Object o, long offset, int x);
 772 
 773     /** Ordered/Lazy version of {@link #putLongVolatile(Object, long, long)} */
 774     public native void    putOrderedLong(Object o, long offset, long x);
 775 
 776     /**
 777      * Unblocks the given thread blocked on {@code park}, or, if it is
 778      * not blocked, causes the subsequent call to {@code park} not to
 779      * block.  Note: this operation is "unsafe" solely because the
 780      * caller must somehow ensure that the thread has not been
 781      * destroyed. Nothing special is usually required to ensure this
 782      * when called from Java (in which there will ordinarily be a live
 783      * reference to the thread) but this is not nearly-automatically
 784      * so when calling from native code.
 785      *
 786      * @param thread the thread to unpark.
 787      */
 788     public native void unpark(Object thread);
 789 
 790     /**
 791      * Blocks current thread, returning when a balancing
 792      * {@code unpark} occurs, or a balancing {@code unpark} has
 793      * already occurred, or the thread is interrupted, or, if not
 794      * absolute and time is not zero, the given time nanoseconds have
 795      * elapsed, or if absolute, the given deadline in milliseconds
 796      * since Epoch has passed, or spuriously (i.e., returning for no
 797      * "reason"). Note: This operation is in the Unsafe class only
 798      * because {@code unpark} is, so it would be strange to place it
 799      * elsewhere.
 800      */
 801     public native void park(boolean isAbsolute, long time);
 802 
 803     /**
 804      * Gets the load average in the system run queue assigned
 805      * to the available processors averaged over various periods of time.
 806      * This method retrieves the given {@code nelem} samples and
 807      * assigns to the elements of the given {@code loadavg} array.
 808      * The system imposes a maximum of 3 samples, representing
 809      * averages over the last 1,  5,  and  15 minutes, respectively.
 810      *
 811      * @param loadavg an array of double of size nelems
 812      * @param nelems the number of samples to be retrieved and
 813      *        must be 1 to 3.
 814      *
 815      * @return the number of samples actually retrieved; or -1
 816      *         if the load average is unobtainable.
 817      */
 818     public native int getLoadAverage(double[] loadavg, int nelems);
 819 
 820     // The following contain CAS-based Java implementations used on
 821     // platforms not supporting native instructions
 822 
 823     /**
 824      * Atomically adds the given value to the current value of a field
 825      * or array element within the given object {@code o}
 826      * at the given {@code offset}.
 827      *
 828      * @param o object/array to update the field/element in
 829      * @param offset field/element offset
 830      * @param delta the value to add
 831      * @return the previous value
 832      * @since 1.8
 833      */
 834     public final int getAndAddInt(Object o, long offset, int delta) {
 835         int v;
 836         do {
 837             v = getIntVolatile(o, offset);
 838         } while (!compareAndSwapInt(o, offset, v, v + delta));
 839         return v;
 840     }
 841 
 842     /**
 843      * Atomically adds the given value to the current value of a field
 844      * or array element within the given object {@code o}
 845      * at the given {@code offset}.
 846      *
 847      * @param o object/array to update the field/element in
 848      * @param offset field/element offset
 849      * @param delta the value to add
 850      * @return the previous value
 851      * @since 1.8
 852      */
 853     public final long getAndAddLong(Object o, long offset, long delta) {
 854         long v;
 855         do {
 856             v = getLongVolatile(o, offset);
 857         } while (!compareAndSwapLong(o, offset, v, v + delta));
 858         return v;
 859     }
 860 
 861     /**
 862      * Atomically exchanges the given value with the current value of
 863      * a field or array element within the given object {@code o}
 864      * at the given {@code offset}.
 865      *
 866      * @param o object/array to update the field/element in
 867      * @param offset field/element offset
 868      * @param newValue new value
 869      * @return the previous value
 870      * @since 1.8
 871      */
 872     public final int getAndSetInt(Object o, long offset, int newValue) {
 873         int v;
 874         do {
 875             v = getIntVolatile(o, offset);
 876         } while (!compareAndSwapInt(o, offset, v, newValue));
 877         return v;
 878     }
 879 
 880     /**
 881      * Atomically exchanges the given value with the current value of
 882      * a field or array element within the given object {@code o}
 883      * at the given {@code offset}.
 884      *
 885      * @param o object/array to update the field/element in
 886      * @param offset field/element offset
 887      * @param newValue new value
 888      * @return the previous value
 889      * @since 1.8
 890      */
 891     public final long getAndSetLong(Object o, long offset, long newValue) {
 892         long v;
 893         do {
 894             v = getLongVolatile(o, offset);
 895         } while (!compareAndSwapLong(o, offset, v, newValue));
 896         return v;
 897     }
 898 
 899     /**
 900      * Atomically exchanges the given reference value with the current
 901      * reference value of a field or array element within the given
 902      * object {@code o} at the given {@code offset}.
 903      *
 904      * @param o object/array to update the field/element in
 905      * @param offset field/element offset
 906      * @param newValue new value
 907      * @return the previous value
 908      * @since 1.8
 909      */
 910     public final Object getAndSetObject(Object o, long offset, Object newValue) {
 911         Object v;
 912         do {
 913             v = getObjectVolatile(o, offset);
 914         } while (!compareAndSwapObject(o, offset, v, newValue));
 915         return v;
 916     }
 917 
 918 
 919     /**
 920      * Ensures that loads before the fence will not be reordered with loads and
 921      * stores after the fence; a "LoadLoad plus LoadStore barrier".
 922      *
 923      * Corresponds to C11 atomic_thread_fence(memory_order_acquire)
 924      * (an "acquire fence").
 925      *
 926      * A pure LoadLoad fence is not provided, since the addition of LoadStore
 927      * is almost always desired, and most current hardware instructions that
 928      * provide a LoadLoad barrier also provide a LoadStore barrier for free.
 929      * @since 1.8
 930      */
 931     public native void loadFence();
 932 
 933     /**
 934      * Ensures that loads and stores before the fence will not be reordered with
 935      * stores after the fence; a "StoreStore plus LoadStore barrier".
 936      *
 937      * Corresponds to C11 atomic_thread_fence(memory_order_release)
 938      * (a "release fence").
 939      *
 940      * A pure StoreStore fence is not provided, since the addition of LoadStore
 941      * is almost always desired, and most current hardware instructions that
 942      * provide a StoreStore barrier also provide a LoadStore barrier for free.
 943      * @since 1.8
 944      */
 945     public native void storeFence();
 946 
 947     /**
 948      * Ensures that loads and stores before the fence will not be reordered
 949      * with loads and stores after the fence.  Implies the effects of both
 950      * loadFence() and storeFence(), and in addition, the effect of a StoreLoad
 951      * barrier.
 952      *
 953      * Corresponds to C11 atomic_thread_fence(memory_order_seq_cst).
 954      * @since 1.8
 955      */
 956     public native void fullFence();
 957 
 958     /**
 959      * Throws IllegalAccessError; for use by the VM for access control
 960      * error support.
 961      * @since 1.8
 962      */
 963     private static void throwIllegalAccessError() {
 964         throw new IllegalAccessError();
 965     }
 966 
 967     /**
 968      * @return Returns true if the native byte ordering of this
 969      * platform is big-endian, false if it is little-endian.
 970      */
 971     public final boolean isBigEndian() { return BE; }
 972 
 973     /**
 974      * @return Returns true if this platform is capable of performing
 975      * accesses at addresses which are not aligned for the type of the
 976      * primitive type being accessed, false otherwise.
 977      */
 978     public final boolean unalignedAccess() { return unalignedAccess; }
 979 
 980     /**
 981      * Fetches a value at some byte offset into a given Java object.
 982      * More specifically, fetches a value within the given object
 983      * <code>o</code> at the given offset, or (if <code>o</code> is
 984      * null) from the memory address whose numerical value is the
 985      * given offset.  <p>
 986      *
 987      * The specification of this method is the same as {@link
 988      * #getLong(Object, long)} except that the offset does not need to
 989      * have been obtained from {@link #objectFieldOffset} on the
 990      * {@link java.lang.reflect.Field} of some Java field.  The value
 991      * in memory is raw data, and need not correspond to any Java
 992      * variable.  Unless <code>o</code> is null, the value accessed
 993      * must be entirely within the allocated object.  The endianness
 994      * of the value in memory is the endianness of the native platform.
 995      *
 996      * <p> The read will be atomic with respect to the largest power
 997      * of two that divides the GCD of the offset and the storage size.
 998      * For example, getLongUnaligned will make atomic reads of 2-, 4-,
 999      * or 8-byte storage units if the offset is zero mod 2, 4, or 8,
1000      * respectively.  There are no other guarantees of atomicity.
1001      * <p>
1002      * 8-byte atomicity is only guaranteed on platforms on which
1003      * support atomic accesses to longs.
1004      *
1005      * @param o Java heap object in which the value resides, if any, else
1006      *        null
1007      * @param offset The offset in bytes from the start of the object
1008      * @return the value fetched from the indicated object
1009      * @throws RuntimeException No defined exceptions are thrown, not even
1010      *         {@link NullPointerException}
1011      * @since 1.9
1012      */
1013     public final long getLongUnaligned(Object o, long offset) {
1014         if ((offset & 7) == 0) {
1015             return getLong(o, offset << 1);
1016         } else if ((offset & 3) == 0) {
1017             return makeLong(getInt(o, (offset + 0) << 1),
1018                             getInt(o, (offset + 4) << 1));
1019         } else if ((offset & 1) == 0) {
1020             return makeLong(getShort(o, (offset + 0) << 1),
1021                             getShort(o, (offset + 2) << 1),
1022                             getShort(o, (offset + 4) << 1),
1023                             getShort(o, (offset + 6) << 1));
1024         } else {
1025             return makeLong(getByte(o, (offset + 0) << 1),
1026                             getByte(o, (offset + 1) << 1),
1027                             getByte(o, (offset + 2) << 1),
1028                             getByte(o, (offset + 3) << 1),
1029                             getByte(o, (offset + 4) << 1),
1030                             getByte(o, (offset + 5) << 1),
1031                             getByte(o, (offset + 6) << 1),
1032                             getByte(o, (offset + 7) << 1));
1033         }
1034     }
1035     /**
1036      * As {@link #getLongUnaligned(Object, long)} but with an
1037      * additional argument which specifies the endianness of the value
1038      * as stored in memory.
1039      *
1040      * @param o Java heap object in which the variable resides
1041      * @param offset The offset in bytes from the start of the object
1042      * @param bigEndian The endianness of the value
1043      * @return the value fetched from the indicated object
1044      * @since 1.9
1045      */
1046     public final long getLongUnaligned(Object o, long offset, boolean bigEndian) {
1047         return convEndian(bigEndian, getLongUnaligned(o, offset));
1048     }
1049 
1050     /** @see #getLongUnaligned(Object, long) */
1051     public final int getIntUnaligned(Object o, long offset) {
1052         if ((offset & 3) == 0) {
1053             return getInt(o, offset << 1);
1054         } else if ((offset & 1) == 0) {
1055             return makeInt(getShort(o, (offset + 0) << 1),
1056                            getShort(o, (offset + 2) << 1));
1057         } else {
1058             return makeInt(getByte(o, (offset + 0) << 1),
1059                            getByte(o, (offset + 1) << 1),
1060                            getByte(o, (offset + 2) << 1),
1061                            getByte(o, (offset + 3) << 1));
1062         }
1063     }
1064     /** @see #getLongUnaligned(Object, long, boolean) */
1065     public final int getIntUnaligned(Object o, long offset, boolean bigEndian) {
1066         return convEndian(bigEndian, getIntUnaligned(o, offset));
1067     }
1068 
1069     /** @see #getLongUnaligned(Object, long) */
1070     public final short getShortUnaligned(Object o, long offset) {
1071         if ((offset & 1) == 0) {
1072             return getShort(o, offset << 1);
1073         } else {
1074             return makeShort(getByte(o, (offset + 0) << 1),
1075                              getByte(o, (offset + 1) << 1));
1076         }
1077     }
1078     /** @see #getLongUnaligned(Object, long, boolean) */
1079     public final short getShortUnaligned(Object o, long offset, boolean bigEndian) {
1080         return convEndian(bigEndian, getShortUnaligned(o, offset));
1081     }
1082 
1083     /** @see #getLongUnaligned(Object, long) */
1084     public final char getCharUnaligned(Object o, long offset) {
1085         return (char)getShortUnaligned(o, offset);
1086     }
1087     /** @see #getLongUnaligned(Object, long, boolean) */
1088     public final char getCharUnaligned(Object o, long offset, boolean bigEndian) {
1089         return convEndian(bigEndian, getCharUnaligned(o, offset));
1090     }
1091 
1092     /**
1093      * Stores a value at some byte offset into a given Java object.
1094      * <p>
1095      * The specification of this method is the same as {@link
1096      * #getLong(Object, long)} except that the offset does not need to
1097      * have been obtained from {@link #objectFieldOffset} on the
1098      * {@link java.lang.reflect.Field} of some Java field.  The value
1099      * in memory is raw data, and need not correspond to any Java
1100      * variable.  The endianness of the value in memory is the
1101      * endianness of the native platform.
1102      * <p>
1103      * The write will be atomic with respect to the largest power of
1104      * two that divides the GCD of the offset and the storage size.
1105      * For example, putLongUnaligned will make atomic writes of 2-, 4-,
1106      * or 8-byte storage units if the offset is zero mod 2, 4, or 8,
1107      * respectively.  There are no other guarantees of atomicity.
1108      * <p>
1109      * 8-byte atomicity is only guaranteed on platforms on which
1110      * support atomic accesses to longs.
1111      *
1112      * @param o Java heap object in which the value resides, if any, else
1113      *        null
1114      * @param offset The offset in bytes from the start of the object
1115      * @param x the value to store
1116      * @throws RuntimeException No defined exceptions are thrown, not even
1117      *         {@link NullPointerException}
1118      * @since 1.9
1119      */
1120     public final void putLongUnaligned(Object o, long offset, long x) {
1121         if ((offset & 7) == 0) {
1122             putLong(o, offset << 1, x);
1123         } else if ((offset & 3) == 0) {
1124             putLongParts(o, offset,
1125                          (int)(x >> 0),
1126                          (int)(x >>> 32));
1127         } else if ((offset & 1) == 0) {
1128             putLongParts(o, offset,
1129                          (short)(x >>> 0),
1130                          (short)(x >>> 16),
1131                          (short)(x >>> 32),
1132                          (short)(x >>> 48));
1133         } else {
1134             putLongParts(o, offset,
1135                          (byte)(x >>> 0),
1136                          (byte)(x >>> 8),
1137                          (byte)(x >>> 16),
1138                          (byte)(x >>> 24),
1139                          (byte)(x >>> 32),
1140                          (byte)(x >>> 40),
1141                          (byte)(x >>> 48),
1142                          (byte)(x >>> 56));
1143         }
1144     }
1145     /**
1146      * As {@link #putLongUnaligned(Object, long, long)} but with an additional
1147      * argument which specifies the endianness of the value as stored in memory.
1148      * @param o Java heap object in which the value resides
1149      * @param offset The offset in bytes from the start of the object
1150      * @param x the value to store
1151      * @param bigEndian The endianness of the value
1152      * @throws RuntimeException No defined exceptions are thrown, not even
1153      *         {@link NullPointerException}
1154      * @since 1.9
1155      */
1156     public final void putLongUnaligned(Object o, long offset, long x, boolean bigEndian) {
1157         putLongUnaligned(o, offset, convEndian(bigEndian, x));
1158     }
1159 
1160     /** @see #putLongUnaligned(Object, long, long) */
1161     public final void putIntUnaligned(Object o, long offset, int x) {
1162         if ((offset & 3) == 0) {
1163             putInt(o, offset << 1, x);
1164         } else if ((offset & 1) == 0) {
1165             putIntParts(o, offset,
1166                         (short)(x >> 0),
1167                         (short)(x >>> 16));
1168         } else {
1169             putIntParts(o, offset,
1170                         (byte)(x >>> 0),
1171                         (byte)(x >>> 8),
1172                         (byte)(x >>> 16),
1173                         (byte)(x >>> 24));
1174         }
1175     }
1176     /** @see #putLongUnaligned(Object, long, long, boolean) */
1177     public final void putIntUnaligned(Object o, long offset, int x, boolean bigEndian) {
1178         putIntUnaligned(o, offset, convEndian(bigEndian, x));
1179     }
1180 
1181     /** @see #putLongUnaligned(Object, long, long) */
1182     public final void putShortUnaligned(Object o, long offset, short x) {
1183         if ((offset & 1) == 0) {
1184             putShort(o, offset << 1, x);
1185         } else {
1186             putShortParts(o, offset,
1187                           (byte)(x >>> 0),
1188                           (byte)(x >>> 8));
1189         }
1190     }
1191     /** @see #putLongUnaligned(Object, long, long, boolean) */
1192     public final void putShortUnaligned(Object o, long offset, short x, boolean bigEndian) {
1193         putShortUnaligned(o, offset, convEndian(bigEndian, x));
1194     }
1195 
1196     /** @see #putLongUnaligned(Object, long, long) */
1197     public final void putCharUnaligned(Object o, long offset, char x) {
1198         putShortUnaligned(o, offset, (short)x);
1199     }
1200     /** @see #putLongUnaligned(Object, long, long, boolean) */
1201     public final void putCharUnaligned(Object o, long offset, char x, boolean bigEndian) {
1202         putCharUnaligned(o, offset, convEndian(bigEndian, x));
1203     }
1204 
1205     // JVM interface methods
1206     private native boolean unalignedAccess0();
1207     private native boolean isBigEndian0();
1208 
1209     // BE is true iff the native endianness of this platform is big.
1210     private static final boolean BE = theUnsafe.isBigEndian0();
1211 
1212     // unalignedAccess is true iff this platform can perform unaligned accesses.
1213     private static final boolean unalignedAccess = theUnsafe.unalignedAccess0();
1214 
1215     private static int pickPos(int top, int pos) { return BE ? top - pos : pos; }
1216 
1217     // These methods construct integers from bytes.  The byte ordering
1218     // is the native endianness of this platform.
1219     private static long makeLong(byte i0, byte i1, byte i2, byte i3, byte i4, byte i5, byte i6, byte i7) {
1220         return ((toUnsignedLong(i0) << pickPos(56, 0))
1221               | (toUnsignedLong(i1) << pickPos(56, 8))
1222               | (toUnsignedLong(i2) << pickPos(56, 16))
1223               | (toUnsignedLong(i3) << pickPos(56, 24))
1224               | (toUnsignedLong(i4) << pickPos(56, 32))
1225               | (toUnsignedLong(i5) << pickPos(56, 40))
1226               | (toUnsignedLong(i6) << pickPos(56, 48))
1227               | (toUnsignedLong(i7) << pickPos(56, 56)));
1228     }
1229     private static long makeLong(short i0, short i1, short i2, short i3) {
1230         return ((toUnsignedLong(i0) << pickPos(48, 0))
1231               | (toUnsignedLong(i1) << pickPos(48, 16))
1232               | (toUnsignedLong(i2) << pickPos(48, 32))
1233               | (toUnsignedLong(i3) << pickPos(48, 48)));
1234     }
1235     private static long makeLong(int i0, int i1) {
1236         return (toUnsignedLong(i0) << pickPos(32, 0))
1237              | (toUnsignedLong(i1) << pickPos(32, 32));
1238     }
1239     private static int makeInt(short i0, short i1) {
1240         return (toUnsignedInt(i0) << pickPos(16, 0))
1241              | (toUnsignedInt(i1) << pickPos(16, 16));
1242     }
1243     private static int makeInt(byte i0, byte i1, byte i2, byte i3) {
1244         return ((toUnsignedInt(i0) << pickPos(24, 0))
1245               | (toUnsignedInt(i1) << pickPos(24, 8))
1246               | (toUnsignedInt(i2) << pickPos(24, 16))
1247               | (toUnsignedInt(i3) << pickPos(24, 24)));
1248     }
1249     private static short makeShort(byte i0, byte i1) {
1250         return (short)((toUnsignedInt(i0) << pickPos(8, 0))
1251                      | (toUnsignedInt(i1) << pickPos(8, 8)));
1252     }
1253 
1254     private static byte  pick(byte  le, byte  be) { return BE ? be : le; }
1255     private static short pick(short le, short be) { return BE ? be : le; }
1256     private static int   pick(int   le, int   be) { return BE ? be : le; }
1257 
1258     // These methods write integers to memory from smaller parts
1259     // provided by their caller.  The ordering in which these parts
1260     // are written is the native endianness of this platform.
1261     private void putLongParts(Object o, long offset, byte i0, byte i1, byte i2, byte i3, byte i4, byte i5, byte i6, byte i7) {
1262         putByte(o, (offset + 0) << 1, pick(i0, i7));
1263         putByte(o, (offset + 1) << 1, pick(i1, i6));
1264         putByte(o, (offset + 2) << 1, pick(i2, i5));
1265         putByte(o, (offset + 3) << 1, pick(i3, i4));
1266         putByte(o, (offset + 4) << 1, pick(i4, i3));
1267         putByte(o, (offset + 5) << 1, pick(i5, i2));
1268         putByte(o, (offset + 6) << 1, pick(i6, i1));
1269         putByte(o, (offset + 7) << 1, pick(i7, i0));
1270     }
1271     private void putLongParts(Object o, long offset, short i0, short i1, short i2, short i3) {
1272         putShort(o, (offset + 0) << 1, pick(i0, i3));
1273         putShort(o, (offset + 2) << 1, pick(i1, i2));
1274         putShort(o, (offset + 4) << 1, pick(i2, i1));
1275         putShort(o, (offset + 6) << 1, pick(i3, i0));
1276     }
1277     private void putLongParts(Object o, long offset, int i0, int i1) {
1278         putInt(o, (offset + 0) << 1, pick(i0, i1));
1279         putInt(o, (offset + 4) << 1, pick(i1, i0));
1280     }
1281     private void putIntParts(Object o, long offset, short i0, short i1) {
1282         putShort(o, (offset + 0) << 1, pick(i0, i1));
1283         putShort(o, (offset + 2) << 1, pick(i1, i0));
1284     }
1285     private void putIntParts(Object o, long offset, byte i0, byte i1, byte i2, byte i3) {
1286         putByte(o, (offset + 0) << 1, pick(i0, i3));
1287         putByte(o, (offset + 1) << 1, pick(i1, i2));
1288         putByte(o, (offset + 2) << 1, pick(i2, i1));
1289         putByte(o, (offset + 3) << 1, pick(i3, i0));
1290     }
1291     private void putShortParts(Object o, long offset, byte i0, byte i1) {
1292         putByte(o, (offset + 0) << 1, pick(i0, i1));
1293         putByte(o, (offset + 1) << 1, pick(i1, i0));
1294     }
1295 
1296     // Zero-extend an integer
1297     private static int toUnsignedInt(byte n)    { return n & 0xff; }
1298     private static int toUnsignedInt(short n)   { return n & 0xffff; }
1299     private static long toUnsignedLong(byte n)  { return n & 0xffl; }
1300     private static long toUnsignedLong(short n) { return n & 0xffffl; }
1301     private static long toUnsignedLong(int n)   { return n & 0xffffffffl; }
1302 
1303     // Maybe byte-reverse an integer
1304     private static char convEndian(boolean big, char n)   { return big == BE ? n : Character.reverseBytes(n); }
1305     private static short convEndian(boolean big, short n) { return big == BE ? n : Short.reverseBytes(n)    ; }
1306     private static int convEndian(boolean big, int n)     { return big == BE ? n : Integer.reverseBytes(n)  ; }
1307     private static long convEndian(boolean big, long n)   { return big == BE ? n : Long.reverseBytes(n)     ; }
1308 }