src/java.base/share/classes/jdk/internal/misc/Unsafe.java
Index Unified diffs Context diffs Sdiffs Patch New Old Previous File Next File jdk Sdiff src/java.base/share/classes/jdk/internal/misc

src/java.base/share/classes/jdk/internal/misc/Unsafe.java

Print this page
rev 13795 : [mq]: unsafejavachecks1


  23  * questions.
  24  */
  25 
  26 package jdk.internal.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 import jdk.internal.misc.VM;
  34 
  35 import jdk.internal.HotSpotIntrinsicCandidate;
  36 
  37 
  38 /**
  39  * A collection of methods for performing low-level, unsafe operations.
  40  * Although the class and all methods are public, use of this class is
  41  * limited because only trusted code can obtain instances of it.
  42  *









  43  * @author John R. Rose
  44  * @see #getUnsafe
  45  */
  46 
  47 public final class Unsafe {
  48 
  49     private static native void registerNatives();
  50     static {
  51         registerNatives();
  52         sun.reflect.Reflection.registerMethodsToFilter(Unsafe.class, "getUnsafe");
  53     }
  54 
  55     private Unsafe() {}
  56 
  57     private static final Unsafe theUnsafe = new Unsafe();
  58 
  59     /**
  60      * Provides the caller with the capability of performing unsafe
  61      * operations.
  62      *


 341      * #addressSize}.
 342      *
 343      * @see #allocateMemory
 344      */
 345     @HotSpotIntrinsicCandidate
 346     public native long getAddress(long address);
 347 
 348     /**
 349      * Stores a native pointer into a given memory address.  If the address is
 350      * zero, or does not point into a block obtained from {@link
 351      * #allocateMemory}, the results are undefined.
 352      *
 353      * <p>The number of bytes actually written at the target address may be
 354      * determined by consulting {@link #addressSize}.
 355      *
 356      * @see #getAddress(long)
 357      */
 358     @HotSpotIntrinsicCandidate
 359     public native void putAddress(long address, long x);
 360 



































































































































































 361     /// wrappers for malloc, realloc, free:
 362 
 363     /**
 364      * Allocates a new block of native memory, of the given size in bytes.  The
 365      * contents of the memory are uninitialized; they will generally be
 366      * garbage.  The resulting native pointer will never be zero, and will be
 367      * aligned for all value types.  Dispose of this memory by calling {@link
 368      * #freeMemory}, or resize it with {@link #reallocateMemory}.
 369      *
 370      * @throws IllegalArgumentException if the size is negative or too large









 371      *         for the native size_t type
 372      *
 373      * @throws OutOfMemoryError if the allocation is refused by the system
 374      *
 375      * @see #getByte(long)
 376      * @see #putByte(long, byte)
 377      */
 378     public native long allocateMemory(long bytes);

























 379 
 380     /**
 381      * Resizes a new block of native memory, to the given size in bytes.  The
 382      * contents of the new block past the size of the old block are
 383      * uninitialized; they will generally be garbage.  The resulting native
 384      * pointer will be zero if and only if the requested size is zero.  The
 385      * resulting native pointer will be aligned for all value types.  Dispose
 386      * of this memory by calling {@link #freeMemory}, or resize it with {@link
 387      * #reallocateMemory}.  The address passed to this method may be null, in
 388      * which case an allocation will be performed.
 389      *
 390      * @throws IllegalArgumentException if the size is negative or too large









 391      *         for the native size_t type
 392      *
 393      * @throws OutOfMemoryError if the allocation is refused by the system
 394      *
 395      * @see #allocateMemory
 396      */
 397     public native long reallocateMemory(long address, long bytes);



























 398 
 399     /**
 400      * Sets all bytes in a given block of memory to a fixed value
 401      * (usually zero).
 402      *
 403      * <p>This method determines a block's base address by means of two parameters,
 404      * and so it provides (in effect) a <em>double-register</em> addressing mode,
 405      * as discussed in {@link #getInt(Object,long)}.  When the object reference is null,
 406      * the offset supplies an absolute base address.
 407      *
 408      * <p>The stores are in coherent (atomic) units of a size determined
 409      * by the address and length parameters.  If the effective address and
 410      * length are all even modulo 8, the stores take place in 'long' units.
 411      * If the effective address and length are (resp.) even modulo 4 or 2,
 412      * the stores take place in units of 'int' or 'short'.
 413      *











 414      * @since 1.7
 415      */
 416     public native void setMemory(Object o, long offset, long bytes, byte value);








 417 
 418     /**
 419      * Sets all bytes in a given block of memory to a fixed value
 420      * (usually zero).  This provides a <em>single-register</em> addressing mode,
 421      * as discussed in {@link #getInt(Object,long)}.
 422      *
 423      * <p>Equivalent to {@code setMemory(null, address, bytes, value)}.
 424      */
 425     public void setMemory(long address, long bytes, byte value) {
 426         setMemory(null, address, bytes, value);
 427     }
 428 
 429     /**













 430      * Sets all bytes in a given block of memory to a copy of another
 431      * block.
 432      *
 433      * <p>This method determines each block's base address by means of two parameters,
 434      * and so it provides (in effect) a <em>double-register</em> addressing mode,
 435      * as discussed in {@link #getInt(Object,long)}.  When the object reference is null,
 436      * the offset supplies an absolute base address.
 437      *
 438      * <p>The transfers are in coherent (atomic) units of a size determined
 439      * by the address and length parameters.  If the effective addresses and
 440      * length are all even modulo 8, the transfer takes place in 'long' units.
 441      * If the effective addresses and length are (resp.) even modulo 4 or 2,
 442      * the transfer takes place in units of 'int' or 'short'.
 443      *











 444      * @since 1.7
 445      */
 446     @HotSpotIntrinsicCandidate
 447     public native void copyMemory(Object srcBase, long srcOffset,
 448                                   Object destBase, long destOffset,
 449                                   long bytes);









 450     /**
 451      * Sets all bytes in a given block of memory to a copy of another
 452      * block.  This provides a <em>single-register</em> addressing mode,
 453      * as discussed in {@link #getInt(Object,long)}.
 454      *
 455      * Equivalent to {@code copyMemory(null, srcAddress, null, destAddress, bytes)}.
 456      */
 457     public void copyMemory(long srcAddress, long destAddress, long bytes) {
 458         copyMemory(null, srcAddress, null, destAddress, bytes);
 459     }
 460 
 461     private boolean isPrimitiveArray(Class<?> c) {
 462         Class<?> componentType = c.getComponentType();
 463         return componentType != null && componentType.isPrimitive();
 464     }
 465 
 466     private native void copySwapMemory0(Object srcBase, long srcOffset,



 467                                         Object destBase, long destOffset,
 468                                         long bytes, long elemSize);




 469 
 470     /**
 471      * Copies all elements from one block of memory to another block,
 472      * *unconditionally* byte swapping the elements on the fly.
 473      *
 474      * <p>This method determines each block's base address by means of two parameters,
 475      * and so it provides (in effect) a <em>double-register</em> addressing mode,
 476      * as discussed in {@link #getInt(Object,long)}.  When the object reference is null,
 477      * the offset supplies an absolute base address.
 478      *











 479      * @since 9
 480      */
 481     public void copySwapMemory(Object srcBase, long srcOffset,
 482                                Object destBase, long destOffset,
 483                                long bytes, long elemSize) {
 484         if (bytes < 0) {
 485             throw new IllegalArgumentException();
 486         }
 487         if (elemSize != 2 && elemSize != 4 && elemSize != 8) {
 488             throw new IllegalArgumentException();
 489         }
 490         if (bytes % elemSize != 0) {
 491             throw new IllegalArgumentException();
 492         }
 493         if ((srcBase == null && srcOffset == 0) ||
 494             (destBase == null && destOffset == 0)) {
 495             throw new NullPointerException();
 496         }
 497 
 498         // Must be off-heap, or primitive heap arrays
 499         if (srcBase != null && (srcOffset < 0 || !isPrimitiveArray(srcBase.getClass()))) {
 500             throw new IllegalArgumentException();
 501         }
 502         if (destBase != null && (destOffset < 0 || !isPrimitiveArray(destBase.getClass()))) {
 503             throw new IllegalArgumentException();
 504         }
 505 
 506         // Sanity check size and offsets on 32-bit platforms. Most
 507         // significant 32 bits must be zero.
 508         if (ADDRESS_SIZE == 4 &&
 509             (bytes >>> 32 != 0 || srcOffset >>> 32 != 0 || destOffset >>> 32 != 0)) {
 510             throw new IllegalArgumentException();
 511         }
 512 
 513         if (bytes == 0) {
 514             return;








 515         }
 516 
 517         copySwapMemory0(srcBase, srcOffset, destBase, destOffset, bytes, elemSize);

 518     }
 519 
 520    /**
 521      * Copies all elements from one block of memory to another block, byte swapping the
 522      * elements on the fly.
 523      *
 524      * This provides a <em>single-register</em> addressing mode, as
 525      * discussed in {@link #getInt(Object,long)}.
 526      *
 527      * Equivalent to {@code copySwapMemory(null, srcAddress, null, destAddress, bytes, elemSize)}.
 528      */
 529     public void copySwapMemory(long srcAddress, long destAddress, long bytes, long elemSize) {
 530         copySwapMemory(null, srcAddress, null, destAddress, bytes, elemSize);
 531     }
 532 
 533     /**
 534      * Disposes of a block of native memory, as obtained from {@link
 535      * #allocateMemory} or {@link #reallocateMemory}.  The address passed to
 536      * this method may be null, in which case no action is taken.
 537      *











 538      * @see #allocateMemory
 539      */
 540     public native void freeMemory(long address);




















 541 
 542     /// random queries
 543 
 544     /**
 545      * This constant differs from all results that will ever be returned from
 546      * {@link #staticFieldOffset}, {@link #objectFieldOffset},
 547      * or {@link #arrayBaseOffset}.
 548      */
 549     public static final int INVALID_FIELD_OFFSET   = -1;
 550 
 551     /**
 552      * Reports the location of a given field in the storage allocation of its
 553      * class.  Do not expect to perform any sort of arithmetic on this offset;
 554      * it is just a cookie which is passed to the unsafe heap memory accessors.
 555      *
 556      * <p>Any given field will always have the same offset and base, and no
 557      * two distinct fields of the same class will ever have the same offset
 558      * and base.
 559      *
 560      * <p>As of 1.4.1, offsets for fields are represented as long values,
 561      * although the Sun JVM does not use the most significant 32 bits.
 562      * However, JVM implementations which store static fields at absolute
 563      * addresses can use long offsets and null base pointers to express
 564      * the field locations in a form usable by {@link #getInt(Object,long)}.
 565      * Therefore, code which will be ported to such JVMs on 64-bit platforms
 566      * must preserve all bits of static field offsets.
 567      * @see #getInt(Object, long)
 568      */
 569     public native long objectFieldOffset(Field f);






 570 
 571     /**
 572      * Reports the location of a given static field, in conjunction with {@link
 573      * #staticFieldBase}.
 574      * <p>Do not expect to perform any sort of arithmetic on this offset;
 575      * it is just a cookie which is passed to the unsafe heap memory accessors.
 576      *
 577      * <p>Any given field will always have the same offset, and no two distinct
 578      * fields of the same class will ever have the same offset.
 579      *
 580      * <p>As of 1.4.1, offsets for fields are represented as long values,
 581      * although the Sun JVM does not use the most significant 32 bits.
 582      * It is hard to imagine a JVM technology which needs more than
 583      * a few bits to encode an offset within a non-array object,
 584      * However, for consistency with other methods in this class,
 585      * this method reports its result as a long value.
 586      * @see #getInt(Object, long)
 587      */
 588     public native long staticFieldOffset(Field f);






 589 
 590     /**
 591      * Reports the location of a given static field, in conjunction with {@link
 592      * #staticFieldOffset}.
 593      * <p>Fetch the base "Object", if any, with which static fields of the
 594      * given class can be accessed via methods like {@link #getInt(Object,
 595      * long)}.  This value may be null.  This value may refer to an object
 596      * which is a "cookie", not guaranteed to be a real Object, and it should
 597      * not be used in any way except as argument to the get and put routines in
 598      * this class.
 599      */
 600     public native Object staticFieldBase(Field f);






 601 
 602     /**
 603      * Detects if the given class may need to be initialized. This is often
 604      * needed in conjunction with obtaining the static field base of a
 605      * class.
 606      * @return false only if a call to {@code ensureClassInitialized} would have no effect
 607      */
 608     public native boolean shouldBeInitialized(Class<?> c);






 609 
 610     /**
 611      * Ensures the given class has been initialized. This is often
 612      * needed in conjunction with obtaining the static field base of a
 613      * class.
 614      */
 615     public native void ensureClassInitialized(Class<?> c);






 616 
 617     /**
 618      * Reports the offset of the first element in the storage allocation of a
 619      * given array class.  If {@link #arrayIndexScale} returns a non-zero value
 620      * for the same class, you may use that scale factor, together with this
 621      * base offset, to form new offsets to access elements of arrays of the
 622      * given class.
 623      *
 624      * @see #getInt(Object, long)
 625      * @see #putInt(Object, long, int)
 626      */
 627     public native int arrayBaseOffset(Class<?> arrayClass);







 628 
 629     /** The value of {@code arrayBaseOffset(boolean[].class)} */
 630     public static final int ARRAY_BOOLEAN_BASE_OFFSET
 631             = theUnsafe.arrayBaseOffset(boolean[].class);
 632 
 633     /** The value of {@code arrayBaseOffset(byte[].class)} */
 634     public static final int ARRAY_BYTE_BASE_OFFSET
 635             = theUnsafe.arrayBaseOffset(byte[].class);
 636 
 637     /** The value of {@code arrayBaseOffset(short[].class)} */
 638     public static final int ARRAY_SHORT_BASE_OFFSET
 639             = theUnsafe.arrayBaseOffset(short[].class);
 640 
 641     /** The value of {@code arrayBaseOffset(char[].class)} */
 642     public static final int ARRAY_CHAR_BASE_OFFSET
 643             = theUnsafe.arrayBaseOffset(char[].class);
 644 
 645     /** The value of {@code arrayBaseOffset(int[].class)} */
 646     public static final int ARRAY_INT_BASE_OFFSET
 647             = theUnsafe.arrayBaseOffset(int[].class);


 656 
 657     /** The value of {@code arrayBaseOffset(double[].class)} */
 658     public static final int ARRAY_DOUBLE_BASE_OFFSET
 659             = theUnsafe.arrayBaseOffset(double[].class);
 660 
 661     /** The value of {@code arrayBaseOffset(Object[].class)} */
 662     public static final int ARRAY_OBJECT_BASE_OFFSET
 663             = theUnsafe.arrayBaseOffset(Object[].class);
 664 
 665     /**
 666      * Reports the scale factor for addressing elements in the storage
 667      * allocation of a given array class.  However, arrays of "narrow" types
 668      * will generally not work properly with accessors like {@link
 669      * #getByte(Object, long)}, so the scale factor for such classes is reported
 670      * as zero.
 671      *
 672      * @see #arrayBaseOffset
 673      * @see #getInt(Object, long)
 674      * @see #putInt(Object, long, int)
 675      */
 676     public native int arrayIndexScale(Class<?> arrayClass);







 677 
 678     /** The value of {@code arrayIndexScale(boolean[].class)} */
 679     public static final int ARRAY_BOOLEAN_INDEX_SCALE
 680             = theUnsafe.arrayIndexScale(boolean[].class);
 681 
 682     /** The value of {@code arrayIndexScale(byte[].class)} */
 683     public static final int ARRAY_BYTE_INDEX_SCALE
 684             = theUnsafe.arrayIndexScale(byte[].class);
 685 
 686     /** The value of {@code arrayIndexScale(short[].class)} */
 687     public static final int ARRAY_SHORT_INDEX_SCALE
 688             = theUnsafe.arrayIndexScale(short[].class);
 689 
 690     /** The value of {@code arrayIndexScale(char[].class)} */
 691     public static final int ARRAY_CHAR_INDEX_SCALE
 692             = theUnsafe.arrayIndexScale(char[].class);
 693 
 694     /** The value of {@code arrayIndexScale(int[].class)} */
 695     public static final int ARRAY_INT_INDEX_SCALE
 696             = theUnsafe.arrayIndexScale(int[].class);


 700             = theUnsafe.arrayIndexScale(long[].class);
 701 
 702     /** The value of {@code arrayIndexScale(float[].class)} */
 703     public static final int ARRAY_FLOAT_INDEX_SCALE
 704             = theUnsafe.arrayIndexScale(float[].class);
 705 
 706     /** The value of {@code arrayIndexScale(double[].class)} */
 707     public static final int ARRAY_DOUBLE_INDEX_SCALE
 708             = theUnsafe.arrayIndexScale(double[].class);
 709 
 710     /** The value of {@code arrayIndexScale(Object[].class)} */
 711     public static final int ARRAY_OBJECT_INDEX_SCALE
 712             = theUnsafe.arrayIndexScale(Object[].class);
 713 
 714     /**
 715      * Reports the size in bytes of a native pointer, as stored via {@link
 716      * #putAddress}.  This value will be either 4 or 8.  Note that the sizes of
 717      * other primitive types (as stored in native memory blocks) is determined
 718      * fully by their information content.
 719      */
 720     public native int addressSize();


 721 
 722     /** The value of {@code addressSize()} */
 723     public static final int ADDRESS_SIZE = theUnsafe.addressSize();
 724 
 725     /**
 726      * Reports the size in bytes of a native memory page (whatever that is).
 727      * This value will always be a power of two.
 728      */
 729     public native int pageSize();
 730 
 731 
 732     /// random trusted operations from JNI:
 733 
 734     /**
 735      * Tells the VM to define a class, without security checks.  By default, the
 736      * class loader and protection domain come from the caller's class.
 737      */
 738     public native Class<?> defineClass(String name, byte[] b, int off, int len,













 739                                        ClassLoader loader,
 740                                        ProtectionDomain protectionDomain);
 741 
 742     /**
 743      * Defines a class but does not make it known to the class loader or system dictionary.
 744      * <p>
 745      * For each CP entry, the corresponding CP patch must either be null or have
 746      * the a format that matches its tag:
 747      * <ul>
 748      * <li>Integer, Long, Float, Double: the corresponding wrapper object type from java.lang
 749      * <li>Utf8: a string (must have suitable syntax if used as signature or name)
 750      * <li>Class: any java.lang.Class object
 751      * <li>String: any object (not just a java.lang.String)
 752      * <li>InterfaceMethodRef: (NYI) a method handle to invoke on that call site's arguments
 753      * </ul>
 754      * @param hostClass context for linkage, access control, protection domain, and class loader
 755      * @param data      bytes of a class file
 756      * @param cpPatches where non-null entries exist, they replace corresponding CP entries in data
 757      */
 758     public native Class<?> defineAnonymousClass(Class<?> hostClass, byte[] data, Object[] cpPatches);






 759 
 760     /**
 761      * Allocates an instance but does not run any constructor.
 762      * Initializes the class if it has not yet been.
 763      */
 764     @HotSpotIntrinsicCandidate
 765     public native Object allocateInstance(Class<?> cls)
 766         throws InstantiationException;
 767 
 768     /** Throws the exception without telling the verifier. */
 769     public native void throwException(Throwable ee);
 770 
 771     /**
 772      * Atomically updates Java variable to {@code x} if it is currently
 773      * holding {@code expected}.
 774      *
 775      * <p>This operation has memory semantics of a {@code volatile} read
 776      * and write.  Corresponds to C11 atomic_compare_exchange_strong.
 777      *
 778      * @return {@code true} if successful


1273      * elsewhere.
1274      */
1275     @HotSpotIntrinsicCandidate
1276     public native void park(boolean isAbsolute, long time);
1277 
1278     /**
1279      * Gets the load average in the system run queue assigned
1280      * to the available processors averaged over various periods of time.
1281      * This method retrieves the given {@code nelem} samples and
1282      * assigns to the elements of the given {@code loadavg} array.
1283      * The system imposes a maximum of 3 samples, representing
1284      * averages over the last 1,  5,  and  15 minutes, respectively.
1285      *
1286      * @param loadavg an array of double of size nelems
1287      * @param nelems the number of samples to be retrieved and
1288      *        must be 1 to 3.
1289      *
1290      * @return the number of samples actually retrieved; or -1
1291      *         if the load average is unobtainable.
1292      */
1293     public native int getLoadAverage(double[] loadavg, int nelems);






1294 
1295     // The following contain CAS-based Java implementations used on
1296     // platforms not supporting native instructions
1297 
1298     /**
1299      * Atomically adds the given value to the current value of a field
1300      * or array element within the given object {@code o}
1301      * at the given {@code offset}.
1302      *
1303      * @param o object/array to update the field/element in
1304      * @param offset field/element offset
1305      * @param delta the value to add
1306      * @return the previous value
1307      * @since 1.8
1308      */
1309     @HotSpotIntrinsicCandidate
1310     public final int getAndAddInt(Object o, long offset, int delta) {
1311         int v;
1312         do {
1313             v = getIntVolatile(o, offset);


1701                           (byte)(x >>> 0),
1702                           (byte)(x >>> 8));
1703         }
1704     }
1705     /** @see #putLongUnaligned(Object, long, long, boolean) */
1706     public final void putShortUnaligned(Object o, long offset, short x, boolean bigEndian) {
1707         putShortUnaligned(o, offset, convEndian(bigEndian, x));
1708     }
1709 
1710     /** @see #putLongUnaligned(Object, long, long) */
1711     @HotSpotIntrinsicCandidate
1712     public final void putCharUnaligned(Object o, long offset, char x) {
1713         putShortUnaligned(o, offset, (short)x);
1714     }
1715     /** @see #putLongUnaligned(Object, long, long, boolean) */
1716     public final void putCharUnaligned(Object o, long offset, char x, boolean bigEndian) {
1717         putCharUnaligned(o, offset, convEndian(bigEndian, x));
1718     }
1719 
1720     // JVM interface methods
1721     private native boolean unalignedAccess0();
1722     private native boolean isBigEndian0();
1723 
1724     // BE is true iff the native endianness of this platform is big.
1725     private static final boolean BE = theUnsafe.isBigEndian0();
1726 
1727     // unalignedAccess is true iff this platform can perform unaligned accesses.
1728     private static final boolean unalignedAccess = theUnsafe.unalignedAccess0();
1729 
1730     private static int pickPos(int top, int pos) { return BE ? top - pos : pos; }
1731 
1732     // These methods construct integers from bytes.  The byte ordering
1733     // is the native endianness of this platform.
1734     private static long makeLong(byte i0, byte i1, byte i2, byte i3, byte i4, byte i5, byte i6, byte i7) {
1735         return ((toUnsignedLong(i0) << pickPos(56, 0))
1736               | (toUnsignedLong(i1) << pickPos(56, 8))
1737               | (toUnsignedLong(i2) << pickPos(56, 16))
1738               | (toUnsignedLong(i3) << pickPos(56, 24))
1739               | (toUnsignedLong(i4) << pickPos(56, 32))
1740               | (toUnsignedLong(i5) << pickPos(56, 40))
1741               | (toUnsignedLong(i6) << pickPos(56, 48))
1742               | (toUnsignedLong(i7) << pickPos(56, 56)));
1743     }


1803         putByte(o, offset + 2, pick(i2, i1));
1804         putByte(o, offset + 3, pick(i3, i0));
1805     }
1806     private void putShortParts(Object o, long offset, byte i0, byte i1) {
1807         putByte(o, offset + 0, pick(i0, i1));
1808         putByte(o, offset + 1, pick(i1, i0));
1809     }
1810 
1811     // Zero-extend an integer
1812     private static int toUnsignedInt(byte n)    { return n & 0xff; }
1813     private static int toUnsignedInt(short n)   { return n & 0xffff; }
1814     private static long toUnsignedLong(byte n)  { return n & 0xffl; }
1815     private static long toUnsignedLong(short n) { return n & 0xffffl; }
1816     private static long toUnsignedLong(int n)   { return n & 0xffffffffl; }
1817 
1818     // Maybe byte-reverse an integer
1819     private static char convEndian(boolean big, char n)   { return big == BE ? n : Character.reverseBytes(n); }
1820     private static short convEndian(boolean big, short n) { return big == BE ? n : Short.reverseBytes(n)    ; }
1821     private static int convEndian(boolean big, int n)     { return big == BE ? n : Integer.reverseBytes(n)  ; }
1822     private static long convEndian(boolean big, long n)   { return big == BE ? n : Long.reverseBytes(n)     ; }






















1823 }


  23  * questions.
  24  */
  25 
  26 package jdk.internal.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 import jdk.internal.misc.VM;
  34 
  35 import jdk.internal.HotSpotIntrinsicCandidate;
  36 
  37 
  38 /**
  39  * A collection of methods for performing low-level, unsafe operations.
  40  * Although the class and all methods are public, use of this class is
  41  * limited because only trusted code can obtain instances of it.
  42  *
  43  * <em>Note:</em> It is the resposibility of the caller to make sure
  44  * arguments are checked before methods of this class are
  45  * called. While some rudimentary checks are performed on the input,
  46  * the checks are best effort and when performance is an overriding
  47  * priority, as when methods of this class are optimized by the
  48  * runtime compiler, some or all checks (if any) may be elided. Hence,
  49  * the caller must not rely on the checks and corresponding
  50  * exceptions!
  51  *
  52  * @author John R. Rose
  53  * @see #getUnsafe
  54  */
  55 
  56 public final class Unsafe {
  57 
  58     private static native void registerNatives();
  59     static {
  60         registerNatives();
  61         sun.reflect.Reflection.registerMethodsToFilter(Unsafe.class, "getUnsafe");
  62     }
  63 
  64     private Unsafe() {}
  65 
  66     private static final Unsafe theUnsafe = new Unsafe();
  67 
  68     /**
  69      * Provides the caller with the capability of performing unsafe
  70      * operations.
  71      *


 350      * #addressSize}.
 351      *
 352      * @see #allocateMemory
 353      */
 354     @HotSpotIntrinsicCandidate
 355     public native long getAddress(long address);
 356 
 357     /**
 358      * Stores a native pointer into a given memory address.  If the address is
 359      * zero, or does not point into a block obtained from {@link
 360      * #allocateMemory}, the results are undefined.
 361      *
 362      * <p>The number of bytes actually written at the target address may be
 363      * determined by consulting {@link #addressSize}.
 364      *
 365      * @see #getAddress(long)
 366      */
 367     @HotSpotIntrinsicCandidate
 368     public native void putAddress(long address, long x);
 369 
 370 
 371 
 372     /// helper methods for validating various types of objects/values
 373 
 374     /**
 375      * Create an exception reflecting that some of the input was invalid
 376      *
 377      * <em>Note:</em> It is the resposibility of the caller to make
 378      * sure arguments are checked before the methods are called. While
 379      * some rudimentary checks are performed on the input, the checks
 380      * are best effort and when performance is an overriding priority,
 381      * as when methods of this class are optimized by the runtime
 382      * compiler, some or all checks (if any) may be elided. Hence, the
 383      * caller must not rely on the checks and corresponding
 384      * exceptions!
 385      *
 386      * @return an exception object
 387      */
 388     private RuntimeException invalidInput() {
 389         return new IllegalArgumentException();
 390     }
 391 
 392     /**
 393      * Check if a value is 32-bit clean (32 MSB are all zero)
 394      *
 395      * @param value the 64-bit value to check
 396      *
 397      * @return true if the value is 32-bit clean
 398      */
 399     private boolean is32BitClean(long value) {
 400         return value >>> 32 == 0;
 401     }
 402 
 403     /**
 404      * Check the validity of a size (the equivalent of a size_t)
 405      *
 406      * @throws RuntimeException if the size is invalid
 407      *         (<em>Note:</em> after optimization, invalid inputs may
 408      *         go undetected, which will lead to unpredictable
 409      *         behavior)
 410      */
 411     private void checkSize(long size) {
 412         if (ADDRESS_SIZE == 4) {
 413             // Note: this will also check for negative sizes
 414             if (!is32BitClean(size)) {
 415                 throw invalidInput();
 416             }
 417         } else if (size < 0) {
 418             throw invalidInput();
 419         }
 420     }
 421 
 422     /**
 423      * Check the validity of a native address (the equivalent of void*)
 424      *
 425      * @throws RuntimeException if the address is invalid
 426      *         (<em>Note:</em> after optimization, invalid inputs may
 427      *         go undetected, which will lead to unpredictable
 428      *         behavior)
 429      */
 430     private void checkNativeAddress(long address) {
 431         if (ADDRESS_SIZE == 4) {
 432             // Accept both zero and sign extended pointers. A valid
 433             // pointer will, after the +1 below, either have produced
 434             // the value 0x0 or 0x1. Masking off the low bit allows
 435             // for testing against 0.
 436             if ((((address >> 32) + 1) & ~1) != 0) {
 437                 throw invalidInput();
 438             }
 439         }
 440     }
 441 
 442     /**
 443      * Check the validity of an offset, relative to a base object
 444      *
 445      * @param o the base object
 446      * @param offset the offset to check
 447      *
 448      * @throws RuntimeException if the size is invalid
 449      *         (<em>Note:</em> after optimization, invalid inputs may
 450      *         go undetected, which will lead to unpredictable
 451      *         behavior)
 452      */
 453     private void checkOffset(Object o, long offset) {
 454         if (ADDRESS_SIZE == 4) {
 455             // Note: this will also check for negative offsets
 456             if (!is32BitClean(offset)) {
 457                 throw invalidInput();
 458             }
 459         } else if (offset < 0) {
 460             throw invalidInput();
 461         }
 462     }
 463 
 464     /**
 465      * Check the validity of a double-register pointer
 466      *
 467      * Note: This code deliberately does *not* check for NPE for (at
 468      * least) three reasons:
 469      *
 470      * 1) NPE is not just NULL/0 - there is a range of values all
 471      * resulting in an NPE, which is not trivial to check for
 472      *
 473      * 2) It is the responsibility of the callers of Unsafe methods
 474      * to verify the input, so throwing an exception here is not really
 475      * useful - passing in a NULL pointer is a critical error and the
 476      * must not expect an exception to be thrown anyway.
 477      *
 478      * 3) the actual operations will detect NULL pointers anyway by
 479      * means of traps and signals (like SIGSEGV).
 480      *
 481      * @param o Java heap object, or null
 482      * @param offset indication of where the variable resides in a Java heap
 483      *        object, if any, else a memory address locating the variable
 484      *        statically
 485      *
 486      * @throws RuntimeException if the pointer is invalid
 487      *         (<em>Note:</em> after optimization, invalid inputs may
 488      *         go undetected, which will lead to unpredictable
 489      *         behavior)
 490      */
 491     private void checkPointer(Object o, long offset) {
 492         if (o == null) {
 493             checkNativeAddress(offset);
 494         } else {
 495             checkOffset(o, offset);
 496         }
 497     }
 498 
 499     /**
 500      * Check if a type is a primitive array type
 501      *
 502      * @param c the type to check
 503      *
 504      * @return true if the type is a primitive array type
 505      */
 506     private void checkPrimitiveArray(Class<?> c) {
 507         Class<?> componentType = c.getComponentType();
 508         if (componentType == null || !componentType.isPrimitive()) {
 509             throw invalidInput();
 510         }
 511     }
 512 
 513     /**
 514      * Check that a pointer is a valid primitive array type pointer
 515      *
 516      * Note: pointers off-heap are considered to be primitive arrays
 517      *
 518      * @throws RuntimeException if the pointer is invalid
 519      *         (<em>Note:</em> after optimization, invalid inputs may
 520      *         go undetected, which will lead to unpredictable
 521      *         behavior)
 522      */
 523     private void checkPrimitivePointer(Object o, long offset) {
 524         checkPointer(o, offset);
 525 
 526         if (o != null) {
 527             // If on heap, it it must be a primitive array
 528             checkPrimitiveArray(o.getClass());
 529         }
 530     }
 531 
 532 
 533     /// wrappers for malloc, realloc, free:
 534 
 535     /**
 536      * Allocates a new block of native memory, of the given size in bytes.  The
 537      * contents of the memory are uninitialized; they will generally be
 538      * garbage.  The resulting native pointer will never be zero, and will be
 539      * aligned for all value types.  Dispose of this memory by calling {@link
 540      * #freeMemory}, or resize it with {@link #reallocateMemory}.
 541      *
 542      * <em>Note:</em> It is the resposibility of the caller to make
 543      * sure arguments are checked before the methods are called. While
 544      * some rudimentary checks are performed on the input, the checks
 545      * are best effort and when performance is an overriding priority,
 546      * as when methods of this class are optimized by the runtime
 547      * compiler, some or all checks (if any) may be elided. Hence, the
 548      * caller must not rely on the checks and corresponding
 549      * exceptions!
 550      *
 551      * @throws RuntimeException if the size is negative or too large
 552      *         for the native size_t type
 553      *
 554      * @throws OutOfMemoryError if the allocation is refused by the system
 555      *
 556      * @see #getByte(long)
 557      * @see #putByte(long, byte)
 558      */
 559     public long allocateMemory(long bytes) {
 560         allocateMemoryChecks(bytes);
 561 
 562         if (bytes == 0) {
 563             return 0;
 564         }
 565 
 566         long p = allocateMemory0(bytes);
 567         if (p == 0) {
 568             throw new OutOfMemoryError();
 569         }
 570 
 571         return p;
 572     }
 573 
 574     /**
 575      * Validate the arguments to allocateMemory
 576      *
 577      * @throws RuntimeException if the arguments are invalid
 578      *         (<em>Note:</em> after optimization, invalid inputs may
 579      *         go undetected, which will lead to unpredictable
 580      *         behavior)
 581      */
 582     private void allocateMemoryChecks(long bytes) {
 583         checkSize(bytes);
 584     }
 585 
 586     /**
 587      * Resizes a new block of native memory, to the given size in bytes.  The
 588      * contents of the new block past the size of the old block are
 589      * uninitialized; they will generally be garbage.  The resulting native
 590      * pointer will be zero if and only if the requested size is zero.  The
 591      * resulting native pointer will be aligned for all value types.  Dispose
 592      * of this memory by calling {@link #freeMemory}, or resize it with {@link
 593      * #reallocateMemory}.  The address passed to this method may be null, in
 594      * which case an allocation will be performed.
 595      *
 596      * <em>Note:</em> It is the resposibility of the caller to make
 597      * sure arguments are checked before the methods are called. While
 598      * some rudimentary checks are performed on the input, the checks
 599      * are best effort and when performance is an overriding priority,
 600      * as when methods of this class are optimized by the runtime
 601      * compiler, some or all checks (if any) may be elided. Hence, the
 602      * caller must not rely on the checks and corresponding
 603      * exceptions!
 604      *
 605      * @throws RuntimeException if the size is negative or too large
 606      *         for the native size_t type
 607      *
 608      * @throws OutOfMemoryError if the allocation is refused by the system
 609      *
 610      * @see #allocateMemory
 611      */
 612     public long reallocateMemory(long address, long bytes) {
 613         reallocateMemoryChecks(address, bytes);
 614 
 615         if (bytes == 0) {
 616             freeMemory(address);
 617             return 0;
 618         }
 619 
 620         long p = (address == 0) ? allocateMemory0(bytes) : reallocateMemory0(address, bytes);
 621         if (p == 0) {
 622             throw new OutOfMemoryError();
 623         }
 624 
 625         return p;
 626     }
 627 
 628     /**
 629      * Validate the arguments to reallocateMemory
 630      *
 631      * @throws RuntimeException if the arguments are invalid
 632      *         (<em>Note:</em> after optimization, invalid inputs may
 633      *         go undetected, which will lead to unpredictable
 634      *         behavior)
 635      */
 636     private void reallocateMemoryChecks(long address, long bytes) {
 637         checkPointer(null, address);
 638         checkSize(bytes);
 639     }
 640 
 641     /**
 642      * Sets all bytes in a given block of memory to a fixed value
 643      * (usually zero).
 644      *
 645      * <p>This method determines a block's base address by means of two parameters,
 646      * and so it provides (in effect) a <em>double-register</em> addressing mode,
 647      * as discussed in {@link #getInt(Object,long)}.  When the object reference is null,
 648      * the offset supplies an absolute base address.
 649      *
 650      * <p>The stores are in coherent (atomic) units of a size determined
 651      * by the address and length parameters.  If the effective address and
 652      * length are all even modulo 8, the stores take place in 'long' units.
 653      * If the effective address and length are (resp.) even modulo 4 or 2,
 654      * the stores take place in units of 'int' or 'short'.
 655      *
 656      * <em>Note:</em> It is the resposibility of the caller to make
 657      * sure arguments are checked before the methods are called. While
 658      * some rudimentary checks are performed on the input, the checks
 659      * are best effort and when performance is an overriding priority,
 660      * as when methods of this class are optimized by the runtime
 661      * compiler, some or all checks (if any) may be elided. Hence, the
 662      * caller must not rely on the checks and corresponding
 663      * exceptions!
 664      *
 665      * @throws RuntimeException if any of the arguments is invalid
 666      *
 667      * @since 1.7
 668      */
 669     public void setMemory(Object o, long offset, long bytes, byte value) {
 670         setMemoryChecks(o, offset, bytes, value);
 671 
 672         if (bytes == 0) {
 673             return;
 674         }
 675 
 676         setMemory0(o, offset, bytes, value);
 677     }
 678 
 679     /**
 680      * Sets all bytes in a given block of memory to a fixed value
 681      * (usually zero).  This provides a <em>single-register</em> addressing mode,
 682      * as discussed in {@link #getInt(Object,long)}.
 683      *
 684      * <p>Equivalent to {@code setMemory(null, address, bytes, value)}.
 685      */
 686     public void setMemory(long address, long bytes, byte value) {
 687         setMemory(null, address, bytes, value);
 688     }
 689 
 690     /**
 691      * Validate the arguments to setMemory
 692      *
 693      * @throws RuntimeException if the arguments are invalid
 694      *         (<em>Note:</em> after optimization, invalid inputs may
 695      *         go undetected, which will lead to unpredictable
 696      *         behavior)
 697      */
 698     private void setMemoryChecks(Object o, long offset, long bytes, byte value) {
 699         checkPrimitivePointer(o, offset);
 700         checkSize(bytes);
 701     }
 702 
 703     /**
 704      * Sets all bytes in a given block of memory to a copy of another
 705      * block.
 706      *
 707      * <p>This method determines each block's base address by means of two parameters,
 708      * and so it provides (in effect) a <em>double-register</em> addressing mode,
 709      * as discussed in {@link #getInt(Object,long)}.  When the object reference is null,
 710      * the offset supplies an absolute base address.
 711      *
 712      * <p>The transfers are in coherent (atomic) units of a size determined
 713      * by the address and length parameters.  If the effective addresses and
 714      * length are all even modulo 8, the transfer takes place in 'long' units.
 715      * If the effective addresses and length are (resp.) even modulo 4 or 2,
 716      * the transfer takes place in units of 'int' or 'short'.
 717      *
 718      * <em>Note:</em> It is the resposibility of the caller to make
 719      * sure arguments are checked before the methods are called. While
 720      * some rudimentary checks are performed on the input, the checks
 721      * are best effort and when performance is an overriding priority,
 722      * as when methods of this class are optimized by the runtime
 723      * compiler, some or all checks (if any) may be elided. Hence, the
 724      * caller must not rely on the checks and corresponding
 725      * exceptions!
 726      *
 727      * @throws RuntimeException if any of the arguments is invalid
 728      *
 729      * @since 1.7
 730      */
 731     public void copyMemory(Object srcBase, long srcOffset,

 732                            Object destBase, long destOffset,
 733                            long bytes) {
 734         copyMemoryChecks(srcBase, srcOffset, destBase, destOffset, bytes);
 735 
 736         if (bytes == 0) {
 737             return;
 738         }
 739 
 740         copyMemory0(srcBase, srcOffset, destBase, destOffset, bytes);
 741     }
 742 
 743     /**
 744      * Sets all bytes in a given block of memory to a copy of another
 745      * block.  This provides a <em>single-register</em> addressing mode,
 746      * as discussed in {@link #getInt(Object,long)}.
 747      *
 748      * Equivalent to {@code copyMemory(null, srcAddress, null, destAddress, bytes)}.
 749      */
 750     public void copyMemory(long srcAddress, long destAddress, long bytes) {
 751         copyMemory(null, srcAddress, null, destAddress, bytes);
 752     }
 753 
 754     /**
 755      * Validate the arguments to copyMemory
 756      *
 757      * @throws RuntimeException if any of the arguments is invalid
 758      *         (<em>Note:</em> after optimization, invalid inputs may
 759      *         go undetected, which will lead to unpredictable
 760      *         behavior)
 761      */
 762     private void copyMemoryChecks(Object srcBase, long srcOffset,
 763                                   Object destBase, long destOffset,
 764                                   long bytes) {
 765         checkSize(bytes);
 766         checkPrimitivePointer(srcBase, srcOffset);
 767         checkPrimitivePointer(destBase, destOffset);
 768     }
 769 
 770     /**
 771      * Copies all elements from one block of memory to another block,
 772      * *unconditionally* byte swapping the elements on the fly.
 773      *
 774      * <p>This method determines each block's base address by means of two parameters,
 775      * and so it provides (in effect) a <em>double-register</em> addressing mode,
 776      * as discussed in {@link #getInt(Object,long)}.  When the object reference is null,
 777      * the offset supplies an absolute base address.
 778      *
 779      * <em>Note:</em> It is the resposibility of the caller to make
 780      * sure arguments are checked before the methods are called. While
 781      * some rudimentary checks are performed on the input, the checks
 782      * are best effort and when performance is an overriding priority,
 783      * as when methods of this class are optimized by the runtime
 784      * compiler, some or all checks (if any) may be elided. Hence, the
 785      * caller must not rely on the checks and corresponding
 786      * exceptions!
 787      *
 788      * @throws RuntimeException if any of the arguments is invalid
 789      *
 790      * @since 9
 791      */
 792     public void copySwapMemory(Object srcBase, long srcOffset,
 793                                Object destBase, long destOffset,
 794                                long bytes, long elemSize) {
 795         copySwapMemoryChecks(srcBase, srcOffset, destBase, destOffset, bytes, elemSize);












 796 
 797         if (bytes == 0) {
 798             return;




 799         }
 800 
 801         copySwapMemory0(srcBase, srcOffset, destBase, destOffset, bytes, elemSize);




 802     }
 803 
 804     private void copySwapMemoryChecks(Object srcBase, long srcOffset,
 805                                       Object destBase, long destOffset,
 806                                       long bytes, long elemSize) {
 807         checkSize(bytes);
 808 
 809         if (elemSize != 2 && elemSize != 4 && elemSize != 8) {
 810             throw invalidInput();
 811         }
 812         if (bytes % elemSize != 0) {
 813             throw invalidInput();
 814         }
 815 
 816         checkPrimitivePointer(srcBase, srcOffset);
 817         checkPrimitivePointer(destBase, destOffset);
 818     }
 819 
 820    /**
 821      * Copies all elements from one block of memory to another block, byte swapping the
 822      * elements on the fly.
 823      *
 824      * This provides a <em>single-register</em> addressing mode, as
 825      * discussed in {@link #getInt(Object,long)}.
 826      *
 827      * Equivalent to {@code copySwapMemory(null, srcAddress, null, destAddress, bytes, elemSize)}.
 828      */
 829     public void copySwapMemory(long srcAddress, long destAddress, long bytes, long elemSize) {
 830         copySwapMemory(null, srcAddress, null, destAddress, bytes, elemSize);
 831     }
 832 
 833     /**
 834      * Disposes of a block of native memory, as obtained from {@link
 835      * #allocateMemory} or {@link #reallocateMemory}.  The address passed to
 836      * this method may be null, in which case no action is taken.
 837      *
 838      * <em>Note:</em> It is the resposibility of the caller to make
 839      * sure arguments are checked before the methods are called. While
 840      * some rudimentary checks are performed on the input, the checks
 841      * are best effort and when performance is an overriding priority,
 842      * as when methods of this class are optimized by the runtime
 843      * compiler, some or all checks (if any) may be elided. Hence, the
 844      * caller must not rely on the checks and corresponding
 845      * exceptions!
 846      *
 847      * @throws RuntimeException if any of the arguments is invalid
 848      *
 849      * @see #allocateMemory
 850      */
 851     public void freeMemory(long address) {
 852         freeMemoryChecks(address);
 853 
 854         if (address == 0) {
 855             return;
 856         }
 857 
 858         freeMemory0(address);
 859     }
 860 
 861     /**
 862      * Validate the arguments to freeMemory
 863      *
 864      * @throws RuntimeException if the arguments are invalid
 865      *         (<em>Note:</em> after optimization, invalid inputs may
 866      *         go undetected, which will lead to unpredictable
 867      *         behavior)
 868      */
 869     private void freeMemoryChecks(long address) {
 870         checkPointer(null, address);
 871     }
 872 
 873     /// random queries
 874 
 875     /**
 876      * This constant differs from all results that will ever be returned from
 877      * {@link #staticFieldOffset}, {@link #objectFieldOffset},
 878      * or {@link #arrayBaseOffset}.
 879      */
 880     public static final int INVALID_FIELD_OFFSET = -1;
 881 
 882     /**
 883      * Reports the location of a given field in the storage allocation of its
 884      * class.  Do not expect to perform any sort of arithmetic on this offset;
 885      * it is just a cookie which is passed to the unsafe heap memory accessors.
 886      *
 887      * <p>Any given field will always have the same offset and base, and no
 888      * two distinct fields of the same class will ever have the same offset
 889      * and base.
 890      *
 891      * <p>As of 1.4.1, offsets for fields are represented as long values,
 892      * although the Sun JVM does not use the most significant 32 bits.
 893      * However, JVM implementations which store static fields at absolute
 894      * addresses can use long offsets and null base pointers to express
 895      * the field locations in a form usable by {@link #getInt(Object,long)}.
 896      * Therefore, code which will be ported to such JVMs on 64-bit platforms
 897      * must preserve all bits of static field offsets.
 898      * @see #getInt(Object, long)
 899      */
 900     public long objectFieldOffset(Field f) {
 901         if (f == null) {
 902             throw new NullPointerException();
 903         }
 904 
 905         return objectFieldOffset0(f);
 906     }
 907 
 908     /**
 909      * Reports the location of a given static field, in conjunction with {@link
 910      * #staticFieldBase}.
 911      * <p>Do not expect to perform any sort of arithmetic on this offset;
 912      * it is just a cookie which is passed to the unsafe heap memory accessors.
 913      *
 914      * <p>Any given field will always have the same offset, and no two distinct
 915      * fields of the same class will ever have the same offset.
 916      *
 917      * <p>As of 1.4.1, offsets for fields are represented as long values,
 918      * although the Sun JVM does not use the most significant 32 bits.
 919      * It is hard to imagine a JVM technology which needs more than
 920      * a few bits to encode an offset within a non-array object,
 921      * However, for consistency with other methods in this class,
 922      * this method reports its result as a long value.
 923      * @see #getInt(Object, long)
 924      */
 925     public long staticFieldOffset(Field f) {
 926         if (f == null) {
 927             throw new NullPointerException();
 928         }
 929 
 930         return staticFieldOffset0(f);
 931     }
 932 
 933     /**
 934      * Reports the location of a given static field, in conjunction with {@link
 935      * #staticFieldOffset}.
 936      * <p>Fetch the base "Object", if any, with which static fields of the
 937      * given class can be accessed via methods like {@link #getInt(Object,
 938      * long)}.  This value may be null.  This value may refer to an object
 939      * which is a "cookie", not guaranteed to be a real Object, and it should
 940      * not be used in any way except as argument to the get and put routines in
 941      * this class.
 942      */
 943     public Object staticFieldBase(Field f) {
 944         if (f == null) {
 945             throw new NullPointerException();
 946         }
 947 
 948         return staticFieldBase0(f);
 949     }
 950 
 951     /**
 952      * Detects if the given class may need to be initialized. This is often
 953      * needed in conjunction with obtaining the static field base of a
 954      * class.
 955      * @return false only if a call to {@code ensureClassInitialized} would have no effect
 956      */
 957     public boolean shouldBeInitialized(Class<?> c) {
 958         if (c == null) {
 959             throw new NullPointerException();
 960         }
 961 
 962         return shouldBeInitialized0(c);
 963     }
 964 
 965     /**
 966      * Ensures the given class has been initialized. This is often
 967      * needed in conjunction with obtaining the static field base of a
 968      * class.
 969      */
 970     public void ensureClassInitialized(Class<?> c) {
 971         if (c == null) {
 972             throw new NullPointerException();
 973         }
 974 
 975         ensureClassInitialized0(c);
 976     }
 977 
 978     /**
 979      * Reports the offset of the first element in the storage allocation of a
 980      * given array class.  If {@link #arrayIndexScale} returns a non-zero value
 981      * for the same class, you may use that scale factor, together with this
 982      * base offset, to form new offsets to access elements of arrays of the
 983      * given class.
 984      *
 985      * @see #getInt(Object, long)
 986      * @see #putInt(Object, long, int)
 987      */
 988     public int arrayBaseOffset(Class<?> arrayClass) {
 989         if (arrayClass == null) {
 990             throw new NullPointerException();
 991         }
 992 
 993         return arrayBaseOffset0(arrayClass);
 994     }
 995 
 996 
 997     /** The value of {@code arrayBaseOffset(boolean[].class)} */
 998     public static final int ARRAY_BOOLEAN_BASE_OFFSET
 999             = theUnsafe.arrayBaseOffset(boolean[].class);
1000 
1001     /** The value of {@code arrayBaseOffset(byte[].class)} */
1002     public static final int ARRAY_BYTE_BASE_OFFSET
1003             = theUnsafe.arrayBaseOffset(byte[].class);
1004 
1005     /** The value of {@code arrayBaseOffset(short[].class)} */
1006     public static final int ARRAY_SHORT_BASE_OFFSET
1007             = theUnsafe.arrayBaseOffset(short[].class);
1008 
1009     /** The value of {@code arrayBaseOffset(char[].class)} */
1010     public static final int ARRAY_CHAR_BASE_OFFSET
1011             = theUnsafe.arrayBaseOffset(char[].class);
1012 
1013     /** The value of {@code arrayBaseOffset(int[].class)} */
1014     public static final int ARRAY_INT_BASE_OFFSET
1015             = theUnsafe.arrayBaseOffset(int[].class);


1024 
1025     /** The value of {@code arrayBaseOffset(double[].class)} */
1026     public static final int ARRAY_DOUBLE_BASE_OFFSET
1027             = theUnsafe.arrayBaseOffset(double[].class);
1028 
1029     /** The value of {@code arrayBaseOffset(Object[].class)} */
1030     public static final int ARRAY_OBJECT_BASE_OFFSET
1031             = theUnsafe.arrayBaseOffset(Object[].class);
1032 
1033     /**
1034      * Reports the scale factor for addressing elements in the storage
1035      * allocation of a given array class.  However, arrays of "narrow" types
1036      * will generally not work properly with accessors like {@link
1037      * #getByte(Object, long)}, so the scale factor for such classes is reported
1038      * as zero.
1039      *
1040      * @see #arrayBaseOffset
1041      * @see #getInt(Object, long)
1042      * @see #putInt(Object, long, int)
1043      */
1044     public int arrayIndexScale(Class<?> arrayClass) {
1045         if (arrayClass == null) {
1046             throw new NullPointerException();
1047         }
1048 
1049         return arrayIndexScale0(arrayClass);
1050     }
1051 
1052 
1053     /** The value of {@code arrayIndexScale(boolean[].class)} */
1054     public static final int ARRAY_BOOLEAN_INDEX_SCALE
1055             = theUnsafe.arrayIndexScale(boolean[].class);
1056 
1057     /** The value of {@code arrayIndexScale(byte[].class)} */
1058     public static final int ARRAY_BYTE_INDEX_SCALE
1059             = theUnsafe.arrayIndexScale(byte[].class);
1060 
1061     /** The value of {@code arrayIndexScale(short[].class)} */
1062     public static final int ARRAY_SHORT_INDEX_SCALE
1063             = theUnsafe.arrayIndexScale(short[].class);
1064 
1065     /** The value of {@code arrayIndexScale(char[].class)} */
1066     public static final int ARRAY_CHAR_INDEX_SCALE
1067             = theUnsafe.arrayIndexScale(char[].class);
1068 
1069     /** The value of {@code arrayIndexScale(int[].class)} */
1070     public static final int ARRAY_INT_INDEX_SCALE
1071             = theUnsafe.arrayIndexScale(int[].class);


1075             = theUnsafe.arrayIndexScale(long[].class);
1076 
1077     /** The value of {@code arrayIndexScale(float[].class)} */
1078     public static final int ARRAY_FLOAT_INDEX_SCALE
1079             = theUnsafe.arrayIndexScale(float[].class);
1080 
1081     /** The value of {@code arrayIndexScale(double[].class)} */
1082     public static final int ARRAY_DOUBLE_INDEX_SCALE
1083             = theUnsafe.arrayIndexScale(double[].class);
1084 
1085     /** The value of {@code arrayIndexScale(Object[].class)} */
1086     public static final int ARRAY_OBJECT_INDEX_SCALE
1087             = theUnsafe.arrayIndexScale(Object[].class);
1088 
1089     /**
1090      * Reports the size in bytes of a native pointer, as stored via {@link
1091      * #putAddress}.  This value will be either 4 or 8.  Note that the sizes of
1092      * other primitive types (as stored in native memory blocks) is determined
1093      * fully by their information content.
1094      */
1095     public int addressSize() {
1096         return ADDRESS_SIZE;
1097     }
1098 
1099     /** The value of {@code addressSize()} */
1100     public static final int ADDRESS_SIZE = theUnsafe.addressSize0();
1101 
1102     /**
1103      * Reports the size in bytes of a native memory page (whatever that is).
1104      * This value will always be a power of two.
1105      */
1106     public native int pageSize();
1107 
1108 
1109     /// random trusted operations from JNI:
1110 
1111     /**
1112      * Tells the VM to define a class, without security checks.  By default, the
1113      * class loader and protection domain come from the caller's class.
1114      */
1115     public Class<?> defineClass(String name, byte[] b, int off, int len,
1116                                 ClassLoader loader,
1117                                 ProtectionDomain protectionDomain) {
1118         if (b == null) {
1119             throw new NullPointerException();
1120         }
1121         if (len < 0) {
1122             throw new ArrayIndexOutOfBoundsException();
1123         }
1124 
1125         return defineClass0(name, b, off, len, loader, protectionDomain);
1126     }
1127 
1128     public native Class<?> defineClass0(String name, byte[] b, int off, int len,
1129                                         ClassLoader loader,
1130                                         ProtectionDomain protectionDomain);
1131 
1132     /**
1133      * Defines a class but does not make it known to the class loader or system dictionary.
1134      * <p>
1135      * For each CP entry, the corresponding CP patch must either be null or have
1136      * the a format that matches its tag:
1137      * <ul>
1138      * <li>Integer, Long, Float, Double: the corresponding wrapper object type from java.lang
1139      * <li>Utf8: a string (must have suitable syntax if used as signature or name)
1140      * <li>Class: any java.lang.Class object
1141      * <li>String: any object (not just a java.lang.String)
1142      * <li>InterfaceMethodRef: (NYI) a method handle to invoke on that call site's arguments
1143      * </ul>
1144      * @param hostClass context for linkage, access control, protection domain, and class loader
1145      * @param data      bytes of a class file
1146      * @param cpPatches where non-null entries exist, they replace corresponding CP entries in data
1147      */
1148     public Class<?> defineAnonymousClass(Class<?> hostClass, byte[] data, Object[] cpPatches) {
1149         if (hostClass == null || data == null) {
1150             throw new NullPointerException();
1151         }
1152 
1153         return defineAnonymousClass0(hostClass, data, cpPatches);
1154     }
1155 
1156     /**
1157      * Allocates an instance but does not run any constructor.
1158      * Initializes the class if it has not yet been.
1159      */
1160     @HotSpotIntrinsicCandidate
1161     public native Object allocateInstance(Class<?> cls)
1162         throws InstantiationException;
1163 
1164     /** Throws the exception without telling the verifier. */
1165     public native void throwException(Throwable ee);
1166 
1167     /**
1168      * Atomically updates Java variable to {@code x} if it is currently
1169      * holding {@code expected}.
1170      *
1171      * <p>This operation has memory semantics of a {@code volatile} read
1172      * and write.  Corresponds to C11 atomic_compare_exchange_strong.
1173      *
1174      * @return {@code true} if successful


1669      * elsewhere.
1670      */
1671     @HotSpotIntrinsicCandidate
1672     public native void park(boolean isAbsolute, long time);
1673 
1674     /**
1675      * Gets the load average in the system run queue assigned
1676      * to the available processors averaged over various periods of time.
1677      * This method retrieves the given {@code nelem} samples and
1678      * assigns to the elements of the given {@code loadavg} array.
1679      * The system imposes a maximum of 3 samples, representing
1680      * averages over the last 1,  5,  and  15 minutes, respectively.
1681      *
1682      * @param loadavg an array of double of size nelems
1683      * @param nelems the number of samples to be retrieved and
1684      *        must be 1 to 3.
1685      *
1686      * @return the number of samples actually retrieved; or -1
1687      *         if the load average is unobtainable.
1688      */
1689     public int getLoadAverage(double[] loadavg, int nelems) {
1690         if (nelems < 0 || nelems > 3 || nelems > loadavg.length) {
1691             throw new ArrayIndexOutOfBoundsException();
1692         }
1693 
1694         return getLoadAverage0(loadavg, nelems);
1695     }
1696 
1697     // The following contain CAS-based Java implementations used on
1698     // platforms not supporting native instructions
1699 
1700     /**
1701      * Atomically adds the given value to the current value of a field
1702      * or array element within the given object {@code o}
1703      * at the given {@code offset}.
1704      *
1705      * @param o object/array to update the field/element in
1706      * @param offset field/element offset
1707      * @param delta the value to add
1708      * @return the previous value
1709      * @since 1.8
1710      */
1711     @HotSpotIntrinsicCandidate
1712     public final int getAndAddInt(Object o, long offset, int delta) {
1713         int v;
1714         do {
1715             v = getIntVolatile(o, offset);


2103                           (byte)(x >>> 0),
2104                           (byte)(x >>> 8));
2105         }
2106     }
2107     /** @see #putLongUnaligned(Object, long, long, boolean) */
2108     public final void putShortUnaligned(Object o, long offset, short x, boolean bigEndian) {
2109         putShortUnaligned(o, offset, convEndian(bigEndian, x));
2110     }
2111 
2112     /** @see #putLongUnaligned(Object, long, long) */
2113     @HotSpotIntrinsicCandidate
2114     public final void putCharUnaligned(Object o, long offset, char x) {
2115         putShortUnaligned(o, offset, (short)x);
2116     }
2117     /** @see #putLongUnaligned(Object, long, long, boolean) */
2118     public final void putCharUnaligned(Object o, long offset, char x, boolean bigEndian) {
2119         putCharUnaligned(o, offset, convEndian(bigEndian, x));
2120     }
2121 
2122     // JVM interface methods



2123     // BE is true iff the native endianness of this platform is big.
2124     private static final boolean BE = theUnsafe.isBigEndian0();
2125 
2126     // unalignedAccess is true iff this platform can perform unaligned accesses.
2127     private static final boolean unalignedAccess = theUnsafe.unalignedAccess0();
2128 
2129     private static int pickPos(int top, int pos) { return BE ? top - pos : pos; }
2130 
2131     // These methods construct integers from bytes.  The byte ordering
2132     // is the native endianness of this platform.
2133     private static long makeLong(byte i0, byte i1, byte i2, byte i3, byte i4, byte i5, byte i6, byte i7) {
2134         return ((toUnsignedLong(i0) << pickPos(56, 0))
2135               | (toUnsignedLong(i1) << pickPos(56, 8))
2136               | (toUnsignedLong(i2) << pickPos(56, 16))
2137               | (toUnsignedLong(i3) << pickPos(56, 24))
2138               | (toUnsignedLong(i4) << pickPos(56, 32))
2139               | (toUnsignedLong(i5) << pickPos(56, 40))
2140               | (toUnsignedLong(i6) << pickPos(56, 48))
2141               | (toUnsignedLong(i7) << pickPos(56, 56)));
2142     }


2202         putByte(o, offset + 2, pick(i2, i1));
2203         putByte(o, offset + 3, pick(i3, i0));
2204     }
2205     private void putShortParts(Object o, long offset, byte i0, byte i1) {
2206         putByte(o, offset + 0, pick(i0, i1));
2207         putByte(o, offset + 1, pick(i1, i0));
2208     }
2209 
2210     // Zero-extend an integer
2211     private static int toUnsignedInt(byte n)    { return n & 0xff; }
2212     private static int toUnsignedInt(short n)   { return n & 0xffff; }
2213     private static long toUnsignedLong(byte n)  { return n & 0xffl; }
2214     private static long toUnsignedLong(short n) { return n & 0xffffl; }
2215     private static long toUnsignedLong(int n)   { return n & 0xffffffffl; }
2216 
2217     // Maybe byte-reverse an integer
2218     private static char convEndian(boolean big, char n)   { return big == BE ? n : Character.reverseBytes(n); }
2219     private static short convEndian(boolean big, short n) { return big == BE ? n : Short.reverseBytes(n)    ; }
2220     private static int convEndian(boolean big, int n)     { return big == BE ? n : Integer.reverseBytes(n)  ; }
2221     private static long convEndian(boolean big, long n)   { return big == BE ? n : Long.reverseBytes(n)     ; }
2222 
2223 
2224 
2225     private native long allocateMemory0(long bytes);
2226     private native long reallocateMemory0(long address, long bytes);
2227     private native void freeMemory0(long address);
2228     private native void setMemory0(Object o, long offset, long bytes, byte value);
2229     @HotSpotIntrinsicCandidate
2230     private native void copyMemory0(Object srcBase, long srcOffset, Object destBase, long destOffset, long bytes);
2231     private native void copySwapMemory0(Object srcBase, long srcOffset, Object destBase, long destOffset, long bytes, long elemSize);
2232     private native long objectFieldOffset0(Field f);
2233     private native long staticFieldOffset0(Field f);
2234     private native Object staticFieldBase0(Field f);
2235     private native boolean shouldBeInitialized0(Class<?> c);
2236     private native void ensureClassInitialized0(Class<?> c);
2237     private native int arrayBaseOffset0(Class<?> arrayClass);
2238     private native int arrayIndexScale0(Class<?> arrayClass);
2239     private native int addressSize0();
2240     private native Class<?> defineAnonymousClass0(Class<?> hostClass, byte[] data, Object[] cpPatches);
2241     private native int getLoadAverage0(double[] loadavg, int nelems);
2242     private native boolean unalignedAccess0();
2243     private native boolean isBigEndian0();
2244 }
src/java.base/share/classes/jdk/internal/misc/Unsafe.java
Index Unified diffs Context diffs Sdiffs Patch New Old Previous File Next File