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