< prev index next >

src/hotspot/share/prims/unsafe.cpp

Print this page

  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "classfile/classFileStream.hpp"
  27 #include "classfile/classLoader.hpp"
  28 #include "classfile/classLoadInfo.hpp"
  29 #include "classfile/javaClasses.inline.hpp"
  30 #include "classfile/systemDictionary.hpp"
  31 #include "classfile/vmSymbols.hpp"
  32 #include "jfr/jfrEvents.hpp"
  33 #include "jni.h"
  34 #include "jvm.h"
  35 #include "memory/allocation.inline.hpp"
  36 #include "memory/resourceArea.hpp"


  37 #include "oops/access.inline.hpp"
  38 #include "oops/fieldStreams.inline.hpp"



  39 #include "oops/instanceKlass.inline.hpp"
  40 #include "oops/klass.inline.hpp"
  41 #include "oops/objArrayOop.inline.hpp"
  42 #include "oops/oop.inline.hpp"
  43 #include "oops/typeArrayOop.inline.hpp"
  44 #include "prims/jvmtiExport.hpp"
  45 #include "prims/unsafe.hpp"

  46 #include "runtime/globals.hpp"
  47 #include "runtime/handles.inline.hpp"
  48 #include "runtime/interfaceSupport.inline.hpp"
  49 #include "runtime/javaThread.inline.hpp"
  50 #include "runtime/jniHandles.inline.hpp"
  51 #include "runtime/orderAccess.hpp"
  52 #include "runtime/reflection.hpp"
  53 #include "runtime/sharedRuntime.hpp"
  54 #include "runtime/stubRoutines.hpp"
  55 #include "runtime/threadSMR.hpp"
  56 #include "runtime/vmOperations.hpp"
  57 #include "runtime/vm_version.hpp"
  58 #include "sanitizers/ub.hpp"
  59 #include "services/threadService.hpp"
  60 #include "utilities/align.hpp"
  61 #include "utilities/copy.hpp"
  62 #include "utilities/dtrace.hpp"
  63 #include "utilities/macros.hpp"
  64 
  65 /**

 152   }
 153 #endif
 154 }
 155 
 156 static inline void* index_oop_from_field_offset_long(oop p, jlong field_offset) {
 157   assert_field_offset_sane(p, field_offset);
 158   uintptr_t base_address = cast_from_oop<uintptr_t>(p);
 159   uintptr_t byte_offset  = (uintptr_t)field_offset_to_byte_offset(field_offset);
 160   return (void*)(base_address + byte_offset);
 161 }
 162 
 163 // Externally callable versions:
 164 // (Use these in compiler intrinsics which emulate unsafe primitives.)
 165 jlong Unsafe_field_offset_to_byte_offset(jlong field_offset) {
 166   return field_offset;
 167 }
 168 jlong Unsafe_field_offset_from_byte_offset(jlong byte_offset) {
 169   return byte_offset;
 170 }
 171 
 172 
 173 ///// Data read/writes on the Java heap and in native (off-heap) memory
 174 
 175 /**
 176  * Helper class to wrap memory accesses in JavaThread::doing_unsafe_access()
 177  */
 178 class GuardUnsafeAccess {
 179   JavaThread* _thread;
 180 
 181 public:
 182   GuardUnsafeAccess(JavaThread* thread) : _thread(thread) {
 183     // native/off-heap access which may raise SIGBUS if accessing
 184     // memory mapped file data in a region of the file which has
 185     // been truncated and is now invalid.
 186     _thread->set_doing_unsafe_access(true);
 187   }
 188 
 189   ~GuardUnsafeAccess() {
 190     _thread->set_doing_unsafe_access(false);
 191   }
 192 };

 231   jboolean normalize_for_read(jboolean x) {
 232     return x != 0;
 233   }
 234 
 235 public:
 236   MemoryAccess(JavaThread* thread, jobject obj, jlong offset)
 237     : _thread(thread), _obj(JNIHandles::resolve(obj)), _offset((ptrdiff_t)offset) {
 238     assert_field_offset_sane(_obj, offset);
 239   }
 240 
 241   T get() {
 242     GuardUnsafeAccess guard(_thread);
 243     return normalize_for_read(*addr());
 244   }
 245 
 246   // we use this method at some places for writing to 0 e.g. to cause a crash;
 247   // ubsan does not know that this is the desired behavior
 248   ATTRIBUTE_NO_UBSAN
 249   void put(T x) {
 250     GuardUnsafeAccess guard(_thread);

 251     *addr() = normalize_for_write(x);
 252   }
 253 
 254 
 255   T get_volatile() {
 256     GuardUnsafeAccess guard(_thread);
 257     volatile T ret = RawAccess<MO_SEQ_CST>::load(addr());
 258     return normalize_for_read(ret);
 259   }
 260 
 261   void put_volatile(T x) {
 262     GuardUnsafeAccess guard(_thread);
 263     RawAccess<MO_SEQ_CST>::store(addr(), normalize_for_write(x));
 264   }
 265 };
 266 






























































 267 // These functions allow a null base pointer with an arbitrary address.
 268 // But if the base pointer is non-null, the offset should make some sense.
 269 // That is, it should be in the range [0, MAX_OBJECT_SIZE].
 270 UNSAFE_ENTRY(jobject, Unsafe_GetReference(JNIEnv *env, jobject unsafe, jobject obj, jlong offset)) {
 271   oop p = JNIHandles::resolve(obj);
 272   assert_field_offset_sane(p, offset);
 273   oop v = HeapAccess<ON_UNKNOWN_OOP_REF>::oop_load_at(p, offset);
 274   return JNIHandles::make_local(THREAD, v);
 275 } UNSAFE_END
 276 
 277 UNSAFE_ENTRY(void, Unsafe_PutReference(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject x_h)) {
 278   oop x = JNIHandles::resolve(x_h);
 279   oop p = JNIHandles::resolve(obj);
 280   assert_field_offset_sane(p, offset);

 281   HeapAccess<ON_UNKNOWN_OOP_REF>::oop_store_at(p, offset, x);
 282 } UNSAFE_END
 283 















































































 284 UNSAFE_ENTRY(jobject, Unsafe_GetReferenceVolatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset)) {
 285   oop p = JNIHandles::resolve(obj);
 286   assert_field_offset_sane(p, offset);
 287   oop v = HeapAccess<MO_SEQ_CST | ON_UNKNOWN_OOP_REF>::oop_load_at(p, offset);
 288   return JNIHandles::make_local(THREAD, v);
 289 } UNSAFE_END
 290 
 291 UNSAFE_ENTRY(void, Unsafe_PutReferenceVolatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject x_h)) {
 292   oop x = JNIHandles::resolve(x_h);
 293   oop p = JNIHandles::resolve(obj);
 294   assert_field_offset_sane(p, offset);
 295   HeapAccess<MO_SEQ_CST | ON_UNKNOWN_OOP_REF>::oop_store_at(p, offset, x);
 296 } UNSAFE_END
 297 
 298 UNSAFE_ENTRY(jobject, Unsafe_GetUncompressedObject(JNIEnv *env, jobject unsafe, jlong addr)) {
 299   oop v = *(oop*) (address) addr;
 300   return JNIHandles::make_local(THREAD, v);
 301 } UNSAFE_END
 302 
 303 #define DEFINE_GETSETOOP(java_type, Type) \

 584   return false;
 585 }
 586 UNSAFE_END
 587 
 588 static void getBaseAndScale(int& base, int& scale, jclass clazz, TRAPS) {
 589   assert(clazz != nullptr, "clazz must not be null");
 590 
 591   oop mirror = JNIHandles::resolve_non_null(clazz);
 592   Klass* k = java_lang_Class::as_Klass(mirror);
 593 
 594   if (k == nullptr || !k->is_array_klass()) {
 595     THROW(vmSymbols::java_lang_InvalidClassException());
 596   } else if (k->is_objArray_klass()) {
 597     base  = arrayOopDesc::base_offset_in_bytes(T_OBJECT);
 598     scale = heapOopSize;
 599   } else if (k->is_typeArray_klass()) {
 600     TypeArrayKlass* tak = TypeArrayKlass::cast(k);
 601     base  = tak->array_header_in_bytes();
 602     assert(base == arrayOopDesc::base_offset_in_bytes(tak->element_type()), "array_header_size semantics ok");
 603     scale = (1 << tak->log2_element_size());





 604   } else {
 605     ShouldNotReachHere();
 606   }
 607 }
 608 
 609 UNSAFE_ENTRY(jint, Unsafe_ArrayBaseOffset0(JNIEnv *env, jobject unsafe, jclass clazz)) {
 610   int base = 0, scale = 0;
 611   getBaseAndScale(base, scale, clazz, CHECK_0);
 612 
 613   return field_offset_from_byte_offset(base);
 614 } UNSAFE_END
 615 
 616 
 617 UNSAFE_ENTRY(jint, Unsafe_ArrayIndexScale0(JNIEnv *env, jobject unsafe, jclass clazz)) {
 618   int base = 0, scale = 0;
 619   getBaseAndScale(base, scale, clazz, CHECK_0);
 620 
 621   // This VM packs both fields and array elements down to the byte.
 622   // But watch out:  If this changes, so that array references for
 623   // a given primitive type (say, T_BOOLEAN) use different memory units
 624   // than fields, this method MUST return zero for such arrays.
 625   // For example, the VM used to store sub-word sized fields in full
 626   // words in the object layout, so that accessors like getByte(Object,int)
 627   // did not really do what one might expect for arrays.  Therefore,
 628   // this function used to report a zero scale factor, so that the user
 629   // would know not to attempt to access sub-word array elements.
 630   // // Code for unpacked fields:
 631   // if (scale < wordSize)  return 0;
 632 
 633   // The following allows for a pretty general fieldOffset cookie scheme,
 634   // but requires it to be linear in byte offset.
 635   return field_offset_from_byte_offset(scale) - field_offset_from_byte_offset(0);
 636 } UNSAFE_END
 637 
 638 






 639 static inline void throw_new(JNIEnv *env, const char *ename) {
 640   jclass cls = env->FindClass(ename);
 641   if (env->ExceptionCheck()) {
 642     env->ExceptionClear();
 643     tty->print_cr("Unsafe: cannot throw %s because FindClass has failed", ename);
 644     return;
 645   }
 646 
 647   env->ThrowNew(cls, nullptr);
 648 }
 649 
 650 static jclass Unsafe_DefineClass_impl(JNIEnv *env, jstring name, jbyteArray data, int offset, int length, jobject loader, jobject pd) {
 651   // Code lifted from JDK 1.3 ClassLoader.c
 652 
 653   jbyte *body;
 654   char *utfName = nullptr;
 655   jclass result = nullptr;
 656   char buf[128];
 657 
 658   assert(data != nullptr, "Class bytes must not be null");

 838 
 839 
 840 /// JVM_RegisterUnsafeMethods
 841 
 842 #define ADR "J"
 843 
 844 #define LANG "Ljava/lang/"
 845 
 846 #define OBJ LANG "Object;"
 847 #define CLS LANG "Class;"
 848 #define FLD LANG "reflect/Field;"
 849 #define THR LANG "Throwable;"
 850 
 851 #define DC_Args  LANG "String;[BII" LANG "ClassLoader;" "Ljava/security/ProtectionDomain;"
 852 #define DAC_Args CLS "[B[" OBJ
 853 
 854 #define CC (char*)  /*cast a literal from (const char*)*/
 855 #define FN_PTR(f) CAST_FROM_FN_PTR(void*, &f)
 856 
 857 #define DECLARE_GETPUTOOP(Type, Desc) \
 858     {CC "get" #Type,      CC "(" OBJ "J)" #Desc,       FN_PTR(Unsafe_Get##Type)}, \
 859     {CC "put" #Type,      CC "(" OBJ "J" #Desc ")V",   FN_PTR(Unsafe_Put##Type)}, \
 860     {CC "get" #Type "Volatile",      CC "(" OBJ "J)" #Desc,       FN_PTR(Unsafe_Get##Type##Volatile)}, \
 861     {CC "put" #Type "Volatile",      CC "(" OBJ "J" #Desc ")V",   FN_PTR(Unsafe_Put##Type##Volatile)}
 862 
 863 
 864 static JNINativeMethod jdk_internal_misc_Unsafe_methods[] = {
 865     {CC "getReference",         CC "(" OBJ "J)" OBJ "",   FN_PTR(Unsafe_GetReference)},
 866     {CC "putReference",         CC "(" OBJ "J" OBJ ")V",  FN_PTR(Unsafe_PutReference)},
 867     {CC "getReferenceVolatile", CC "(" OBJ "J)" OBJ,      FN_PTR(Unsafe_GetReferenceVolatile)},
 868     {CC "putReferenceVolatile", CC "(" OBJ "J" OBJ ")V",  FN_PTR(Unsafe_PutReferenceVolatile)},
 869 











 870     {CC "getUncompressedObject", CC "(" ADR ")" OBJ,  FN_PTR(Unsafe_GetUncompressedObject)},
 871 
 872     DECLARE_GETPUTOOP(Boolean, Z),
 873     DECLARE_GETPUTOOP(Byte, B),
 874     DECLARE_GETPUTOOP(Short, S),
 875     DECLARE_GETPUTOOP(Char, C),
 876     DECLARE_GETPUTOOP(Int, I),
 877     DECLARE_GETPUTOOP(Long, J),
 878     DECLARE_GETPUTOOP(Float, F),
 879     DECLARE_GETPUTOOP(Double, D),
 880 
 881     {CC "allocateMemory0",    CC "(J)" ADR,              FN_PTR(Unsafe_AllocateMemory0)},
 882     {CC "reallocateMemory0",  CC "(" ADR "J)" ADR,       FN_PTR(Unsafe_ReallocateMemory0)},
 883     {CC "freeMemory0",        CC "(" ADR ")V",           FN_PTR(Unsafe_FreeMemory0)},
 884 
 885     {CC "objectFieldOffset0", CC "(" FLD ")J",           FN_PTR(Unsafe_ObjectFieldOffset0)},
 886     {CC "objectFieldOffset1", CC "(" CLS LANG "String;)J", FN_PTR(Unsafe_ObjectFieldOffset1)},
 887     {CC "staticFieldOffset0", CC "(" FLD ")J",           FN_PTR(Unsafe_StaticFieldOffset0)},
 888     {CC "staticFieldBase0",   CC "(" FLD ")" OBJ,        FN_PTR(Unsafe_StaticFieldBase0)},
 889     {CC "ensureClassInitialized0", CC "(" CLS ")V",      FN_PTR(Unsafe_EnsureClassInitialized0)},
 890     {CC "arrayBaseOffset0",   CC "(" CLS ")I",           FN_PTR(Unsafe_ArrayBaseOffset0)},
 891     {CC "arrayIndexScale0",   CC "(" CLS ")I",           FN_PTR(Unsafe_ArrayIndexScale0)},

 892 
 893     {CC "defineClass0",       CC "(" DC_Args ")" CLS,    FN_PTR(Unsafe_DefineClass0)},
 894     {CC "allocateInstance",   CC "(" CLS ")" OBJ,        FN_PTR(Unsafe_AllocateInstance)},
 895     {CC "throwException",     CC "(" THR ")V",           FN_PTR(Unsafe_ThrowException)},
 896     {CC "compareAndSetReference",CC "(" OBJ "J" OBJ "" OBJ ")Z", FN_PTR(Unsafe_CompareAndSetReference)},
 897     {CC "compareAndSetInt",   CC "(" OBJ "J""I""I"")Z",  FN_PTR(Unsafe_CompareAndSetInt)},
 898     {CC "compareAndSetLong",  CC "(" OBJ "J""J""J"")Z",  FN_PTR(Unsafe_CompareAndSetLong)},
 899     {CC "compareAndExchangeReference", CC "(" OBJ "J" OBJ "" OBJ ")" OBJ, FN_PTR(Unsafe_CompareAndExchangeReference)},
 900     {CC "compareAndExchangeInt",  CC "(" OBJ "J""I""I"")I", FN_PTR(Unsafe_CompareAndExchangeInt)},
 901     {CC "compareAndExchangeLong", CC "(" OBJ "J""J""J"")J", FN_PTR(Unsafe_CompareAndExchangeLong)},
 902 
 903     {CC "park",               CC "(ZJ)V",                FN_PTR(Unsafe_Park)},
 904     {CC "unpark",             CC "(" OBJ ")V",           FN_PTR(Unsafe_Unpark)},
 905 
 906     {CC "getLoadAverage0",    CC "([DI)I",               FN_PTR(Unsafe_GetLoadAverage0)},
 907 
 908     {CC "copyMemory0",        CC "(" OBJ "J" OBJ "JJ)V", FN_PTR(Unsafe_CopyMemory0)},
 909     {CC "copySwapMemory0",    CC "(" OBJ "J" OBJ "JJJ)V", FN_PTR(Unsafe_CopySwapMemory0)},
 910     {CC "writeback0",         CC "(" "J" ")V",           FN_PTR(Unsafe_WriteBack0)},
 911     {CC "writebackPreSync0",  CC "()V",                  FN_PTR(Unsafe_WriteBackPreSync0)},

  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "classfile/classFileStream.hpp"
  27 #include "classfile/classLoader.hpp"
  28 #include "classfile/classLoadInfo.hpp"
  29 #include "classfile/javaClasses.inline.hpp"
  30 #include "classfile/systemDictionary.hpp"
  31 #include "classfile/vmSymbols.hpp"
  32 #include "jfr/jfrEvents.hpp"
  33 #include "jni.h"
  34 #include "jvm.h"
  35 #include "memory/allocation.inline.hpp"
  36 #include "memory/resourceArea.hpp"
  37 #include "logging/log.hpp"
  38 #include "logging/logStream.hpp"
  39 #include "oops/access.inline.hpp"
  40 #include "oops/fieldStreams.inline.hpp"
  41 #include "oops/flatArrayKlass.hpp"
  42 #include "oops/flatArrayOop.inline.hpp"
  43 #include "oops/inlineKlass.inline.hpp"
  44 #include "oops/instanceKlass.inline.hpp"
  45 #include "oops/klass.inline.hpp"
  46 #include "oops/objArrayOop.inline.hpp"
  47 #include "oops/oop.inline.hpp"
  48 #include "oops/typeArrayOop.inline.hpp"
  49 #include "prims/jvmtiExport.hpp"
  50 #include "prims/unsafe.hpp"
  51 #include "runtime/fieldDescriptor.inline.hpp"
  52 #include "runtime/globals.hpp"
  53 #include "runtime/handles.inline.hpp"
  54 #include "runtime/interfaceSupport.inline.hpp"
  55 #include "runtime/javaThread.inline.hpp"
  56 #include "runtime/jniHandles.inline.hpp"
  57 #include "runtime/orderAccess.hpp"
  58 #include "runtime/reflection.hpp"
  59 #include "runtime/sharedRuntime.hpp"
  60 #include "runtime/stubRoutines.hpp"
  61 #include "runtime/threadSMR.hpp"
  62 #include "runtime/vmOperations.hpp"
  63 #include "runtime/vm_version.hpp"
  64 #include "sanitizers/ub.hpp"
  65 #include "services/threadService.hpp"
  66 #include "utilities/align.hpp"
  67 #include "utilities/copy.hpp"
  68 #include "utilities/dtrace.hpp"
  69 #include "utilities/macros.hpp"
  70 
  71 /**

 158   }
 159 #endif
 160 }
 161 
 162 static inline void* index_oop_from_field_offset_long(oop p, jlong field_offset) {
 163   assert_field_offset_sane(p, field_offset);
 164   uintptr_t base_address = cast_from_oop<uintptr_t>(p);
 165   uintptr_t byte_offset  = (uintptr_t)field_offset_to_byte_offset(field_offset);
 166   return (void*)(base_address + byte_offset);
 167 }
 168 
 169 // Externally callable versions:
 170 // (Use these in compiler intrinsics which emulate unsafe primitives.)
 171 jlong Unsafe_field_offset_to_byte_offset(jlong field_offset) {
 172   return field_offset;
 173 }
 174 jlong Unsafe_field_offset_from_byte_offset(jlong byte_offset) {
 175   return byte_offset;
 176 }
 177 

 178 ///// Data read/writes on the Java heap and in native (off-heap) memory
 179 
 180 /**
 181  * Helper class to wrap memory accesses in JavaThread::doing_unsafe_access()
 182  */
 183 class GuardUnsafeAccess {
 184   JavaThread* _thread;
 185 
 186 public:
 187   GuardUnsafeAccess(JavaThread* thread) : _thread(thread) {
 188     // native/off-heap access which may raise SIGBUS if accessing
 189     // memory mapped file data in a region of the file which has
 190     // been truncated and is now invalid.
 191     _thread->set_doing_unsafe_access(true);
 192   }
 193 
 194   ~GuardUnsafeAccess() {
 195     _thread->set_doing_unsafe_access(false);
 196   }
 197 };

 236   jboolean normalize_for_read(jboolean x) {
 237     return x != 0;
 238   }
 239 
 240 public:
 241   MemoryAccess(JavaThread* thread, jobject obj, jlong offset)
 242     : _thread(thread), _obj(JNIHandles::resolve(obj)), _offset((ptrdiff_t)offset) {
 243     assert_field_offset_sane(_obj, offset);
 244   }
 245 
 246   T get() {
 247     GuardUnsafeAccess guard(_thread);
 248     return normalize_for_read(*addr());
 249   }
 250 
 251   // we use this method at some places for writing to 0 e.g. to cause a crash;
 252   // ubsan does not know that this is the desired behavior
 253   ATTRIBUTE_NO_UBSAN
 254   void put(T x) {
 255     GuardUnsafeAccess guard(_thread);
 256     assert(_obj == nullptr || !_obj->is_inline_type() || _obj->mark().is_larval_state(), "must be an object instance or a larval inline type");
 257     *addr() = normalize_for_write(x);
 258   }
 259 

 260   T get_volatile() {
 261     GuardUnsafeAccess guard(_thread);
 262     volatile T ret = RawAccess<MO_SEQ_CST>::load(addr());
 263     return normalize_for_read(ret);
 264   }
 265 
 266   void put_volatile(T x) {
 267     GuardUnsafeAccess guard(_thread);
 268     RawAccess<MO_SEQ_CST>::store(addr(), normalize_for_write(x));
 269   }
 270 };
 271 
 272 #ifdef ASSERT
 273 /*
 274  * Get the field descriptor of the field of the given object at the given offset.
 275  */
 276 static bool get_field_descriptor(oop p, jlong offset, fieldDescriptor* fd) {
 277   bool found = false;
 278   Klass* k = p->klass();
 279   if (k->is_instance_klass()) {
 280     InstanceKlass* ik = InstanceKlass::cast(k);
 281     found = ik->find_field_from_offset((int)offset, false, fd);
 282     if (!found && ik->is_mirror_instance_klass()) {
 283       Klass* k2 = java_lang_Class::as_Klass(p);
 284       if (k2->is_instance_klass()) {
 285         ik = InstanceKlass::cast(k2);
 286         found = ik->find_field_from_offset((int)offset, true, fd);
 287       }
 288     }
 289   }
 290   return found;
 291 }
 292 #endif // ASSERT
 293 
 294 static void assert_and_log_unsafe_value_access(oop p, jlong offset, InlineKlass* vk) {
 295   Klass* k = p->klass();
 296 #ifdef ASSERT
 297   if (k->is_instance_klass()) {
 298     assert_field_offset_sane(p, offset);
 299     fieldDescriptor fd;
 300     bool found = get_field_descriptor(p, offset, &fd);
 301     if (found) {
 302       assert(found, "value field not found");
 303       assert(fd.is_flat(), "field not flat");
 304     } else {
 305       if (log_is_enabled(Trace, valuetypes)) {
 306         log_trace(valuetypes)("not a field in %s at offset " UINT64_FORMAT_X,
 307                               p->klass()->external_name(), (uint64_t)offset);
 308       }
 309     }
 310   } else if (k->is_flatArray_klass()) {
 311     FlatArrayKlass* vak = FlatArrayKlass::cast(k);
 312     int index = (offset - vak->array_header_in_bytes()) / vak->element_byte_size();
 313     address dest = (address)((flatArrayOop)p)->value_at_addr(index, vak->layout_helper());
 314     assert(dest == (cast_from_oop<address>(p) + offset), "invalid offset");
 315   } else {
 316     ShouldNotReachHere();
 317   }
 318 #endif // ASSERT
 319   if (log_is_enabled(Trace, valuetypes)) {
 320     if (k->is_flatArray_klass()) {
 321       FlatArrayKlass* vak = FlatArrayKlass::cast(k);
 322       int index = (offset - vak->array_header_in_bytes()) / vak->element_byte_size();
 323       address dest = (address)((flatArrayOop)p)->value_at_addr(index, vak->layout_helper());
 324       log_trace(valuetypes)("%s array type %s index %d element size %d offset " UINT64_FORMAT_X " at " INTPTR_FORMAT,
 325                             p->klass()->external_name(), vak->external_name(),
 326                             index, vak->element_byte_size(), (uint64_t)offset, p2i(dest));
 327     } else {
 328       log_trace(valuetypes)("%s field type %s at offset " UINT64_FORMAT_X,
 329                             p->klass()->external_name(), vk->external_name(), (uint64_t)offset);
 330     }
 331   }
 332 }
 333 
 334 // These functions allow a null base pointer with an arbitrary address.
 335 // But if the base pointer is non-null, the offset should make some sense.
 336 // That is, it should be in the range [0, MAX_OBJECT_SIZE].
 337 UNSAFE_ENTRY(jobject, Unsafe_GetReference(JNIEnv *env, jobject unsafe, jobject obj, jlong offset)) {
 338   oop p = JNIHandles::resolve(obj);
 339   assert_field_offset_sane(p, offset);
 340   oop v = HeapAccess<ON_UNKNOWN_OOP_REF>::oop_load_at(p, offset);
 341   return JNIHandles::make_local(THREAD, v);
 342 } UNSAFE_END
 343 
 344 UNSAFE_ENTRY(void, Unsafe_PutReference(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject x_h)) {
 345   oop x = JNIHandles::resolve(x_h);
 346   oop p = JNIHandles::resolve(obj);
 347   assert_field_offset_sane(p, offset);
 348   assert(!p->is_inline_type() || p->mark().is_larval_state(), "must be an object instance or a larval inline type");
 349   HeapAccess<ON_UNKNOWN_OOP_REF>::oop_store_at(p, offset, x);
 350 } UNSAFE_END
 351 
 352 UNSAFE_ENTRY(jlong, Unsafe_ValueHeaderSize(JNIEnv *env, jobject unsafe, jclass c)) {
 353   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(c));
 354   InlineKlass* vk = InlineKlass::cast(k);
 355   return vk->first_field_offset();
 356 } UNSAFE_END
 357 
 358 UNSAFE_ENTRY(jboolean, Unsafe_IsFlatField(JNIEnv *env, jobject unsafe, jobject o)) {
 359   oop f = JNIHandles::resolve_non_null(o);
 360   Klass* k = java_lang_Class::as_Klass(java_lang_reflect_Field::clazz(f));
 361   int slot = java_lang_reflect_Field::slot(f);
 362   return InstanceKlass::cast(k)->field_is_flat(slot);
 363 } UNSAFE_END
 364 
 365 UNSAFE_ENTRY(jboolean, Unsafe_HasNullMarker(JNIEnv *env, jobject unsafe, jobject o)) {
 366   oop f = JNIHandles::resolve_non_null(o);
 367   Klass* k = java_lang_Class::as_Klass(java_lang_reflect_Field::clazz(f));
 368   int slot = java_lang_reflect_Field::slot(f);
 369   return InstanceKlass::cast(k)->field_has_null_marker(slot);
 370 } UNSAFE_END
 371 
 372 UNSAFE_ENTRY(jint, Unsafe_NullMarkerOffset(JNIEnv *env, jobject unsafe, jobject o)) {
 373   oop f = JNIHandles::resolve_non_null(o);
 374   Klass* k = java_lang_Class::as_Klass(java_lang_reflect_Field::clazz(f));
 375   int slot = java_lang_reflect_Field::slot(f);
 376   return InstanceKlass::cast(k)->null_marker_offset(slot);
 377 } UNSAFE_END
 378 
 379 UNSAFE_ENTRY(jboolean, Unsafe_IsFlatArray(JNIEnv *env, jobject unsafe, jclass c)) {
 380   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(c));
 381   return k->is_flatArray_klass();
 382 } UNSAFE_END
 383 
 384 UNSAFE_ENTRY(jobject, Unsafe_UninitializedDefaultValue(JNIEnv *env, jobject unsafe, jclass vc)) {
 385   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(vc));
 386   InlineKlass* vk = InlineKlass::cast(k);
 387   oop v = vk->default_value();
 388   return JNIHandles::make_local(THREAD, v);
 389 } UNSAFE_END
 390 
 391 UNSAFE_ENTRY(jobject, Unsafe_GetValue(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jclass vc)) {
 392   oop base = JNIHandles::resolve(obj);
 393   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(vc));
 394   InlineKlass* vk = InlineKlass::cast(k);
 395   assert_and_log_unsafe_value_access(base, offset, vk);
 396   Handle base_h(THREAD, base);
 397   oop v = vk->read_flat_field(base_h(), offset, LayoutKind::PAYLOAD, CHECK_NULL);  // TODO FIXME Hard coded layout kind to make the code compile, Unsafe must be upgraded to handle correct layout kind
 398   return JNIHandles::make_local(THREAD, v);
 399 } UNSAFE_END
 400 
 401 UNSAFE_ENTRY(void, Unsafe_PutValue(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jclass vc, jobject value)) {
 402   oop base = JNIHandles::resolve(obj);
 403   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(vc));
 404   InlineKlass* vk = InlineKlass::cast(k);
 405   assert(!base->is_inline_type() || base->mark().is_larval_state(), "must be an object instance or a larval inline type");
 406   assert_and_log_unsafe_value_access(base, offset, vk);
 407   oop v = JNIHandles::resolve(value);
 408   vk->write_flat_field(base, offset, v, true /*null free*/, LayoutKind::PAYLOAD, CHECK);  // TODO FIXME Hard coded layout kind to make the code compile, Unsafe must be upgraded to handle correct layout kind
 409 } UNSAFE_END
 410 
 411 UNSAFE_ENTRY(jobject, Unsafe_MakePrivateBuffer(JNIEnv *env, jobject unsafe, jobject value)) {
 412   oop v = JNIHandles::resolve_non_null(value);
 413   assert(v->is_inline_type(), "must be an inline type instance");
 414   Handle vh(THREAD, v);
 415   InlineKlass* vk = InlineKlass::cast(v->klass());
 416   instanceOop new_value = vk->allocate_instance_buffer(CHECK_NULL);
 417   vk->inline_copy_oop_to_new_oop(vh(), new_value, LayoutKind::PAYLOAD);  // FIXME temporary hack for the transition
 418   markWord mark = new_value->mark();
 419   new_value->set_mark(mark.enter_larval_state());
 420   return JNIHandles::make_local(THREAD, new_value);
 421 } UNSAFE_END
 422 
 423 UNSAFE_ENTRY(jobject, Unsafe_FinishPrivateBuffer(JNIEnv *env, jobject unsafe, jobject value)) {
 424   oop v = JNIHandles::resolve(value);
 425   assert(v->mark().is_larval_state(), "must be a larval value");
 426   markWord mark = v->mark();
 427   v->set_mark(mark.exit_larval_state());
 428   return JNIHandles::make_local(THREAD, v);
 429 } UNSAFE_END
 430 
 431 UNSAFE_ENTRY(jobject, Unsafe_GetReferenceVolatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset)) {
 432   oop p = JNIHandles::resolve(obj);
 433   assert_field_offset_sane(p, offset);
 434   oop v = HeapAccess<MO_SEQ_CST | ON_UNKNOWN_OOP_REF>::oop_load_at(p, offset);
 435   return JNIHandles::make_local(THREAD, v);
 436 } UNSAFE_END
 437 
 438 UNSAFE_ENTRY(void, Unsafe_PutReferenceVolatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject x_h)) {
 439   oop x = JNIHandles::resolve(x_h);
 440   oop p = JNIHandles::resolve(obj);
 441   assert_field_offset_sane(p, offset);
 442   HeapAccess<MO_SEQ_CST | ON_UNKNOWN_OOP_REF>::oop_store_at(p, offset, x);
 443 } UNSAFE_END
 444 
 445 UNSAFE_ENTRY(jobject, Unsafe_GetUncompressedObject(JNIEnv *env, jobject unsafe, jlong addr)) {
 446   oop v = *(oop*) (address) addr;
 447   return JNIHandles::make_local(THREAD, v);
 448 } UNSAFE_END
 449 
 450 #define DEFINE_GETSETOOP(java_type, Type) \

 731   return false;
 732 }
 733 UNSAFE_END
 734 
 735 static void getBaseAndScale(int& base, int& scale, jclass clazz, TRAPS) {
 736   assert(clazz != nullptr, "clazz must not be null");
 737 
 738   oop mirror = JNIHandles::resolve_non_null(clazz);
 739   Klass* k = java_lang_Class::as_Klass(mirror);
 740 
 741   if (k == nullptr || !k->is_array_klass()) {
 742     THROW(vmSymbols::java_lang_InvalidClassException());
 743   } else if (k->is_objArray_klass()) {
 744     base  = arrayOopDesc::base_offset_in_bytes(T_OBJECT);
 745     scale = heapOopSize;
 746   } else if (k->is_typeArray_klass()) {
 747     TypeArrayKlass* tak = TypeArrayKlass::cast(k);
 748     base  = tak->array_header_in_bytes();
 749     assert(base == arrayOopDesc::base_offset_in_bytes(tak->element_type()), "array_header_size semantics ok");
 750     scale = (1 << tak->log2_element_size());
 751   } else if (k->is_flatArray_klass()) {
 752     FlatArrayKlass* vak = FlatArrayKlass::cast(k);
 753     InlineKlass* vklass = vak->element_klass();
 754     base = vak->array_header_in_bytes();
 755     scale = vak->element_byte_size();
 756   } else {
 757     ShouldNotReachHere();
 758   }
 759 }
 760 
 761 UNSAFE_ENTRY(jint, Unsafe_ArrayBaseOffset0(JNIEnv *env, jobject unsafe, jclass clazz)) {
 762   int base = 0, scale = 0;
 763   getBaseAndScale(base, scale, clazz, CHECK_0);
 764 
 765   return field_offset_from_byte_offset(base);
 766 } UNSAFE_END
 767 
 768 
 769 UNSAFE_ENTRY(jint, Unsafe_ArrayIndexScale0(JNIEnv *env, jobject unsafe, jclass clazz)) {
 770   int base = 0, scale = 0;
 771   getBaseAndScale(base, scale, clazz, CHECK_0);
 772 
 773   // This VM packs both fields and array elements down to the byte.
 774   // But watch out:  If this changes, so that array references for
 775   // a given primitive type (say, T_BOOLEAN) use different memory units
 776   // than fields, this method MUST return zero for such arrays.
 777   // For example, the VM used to store sub-word sized fields in full
 778   // words in the object layout, so that accessors like getByte(Object,int)
 779   // did not really do what one might expect for arrays.  Therefore,
 780   // this function used to report a zero scale factor, so that the user
 781   // would know not to attempt to access sub-word array elements.
 782   // // Code for unpacked fields:
 783   // if (scale < wordSize)  return 0;
 784 
 785   // The following allows for a pretty general fieldOffset cookie scheme,
 786   // but requires it to be linear in byte offset.
 787   return field_offset_from_byte_offset(scale) - field_offset_from_byte_offset(0);
 788 } UNSAFE_END
 789 
 790 
 791 UNSAFE_ENTRY(jlong, Unsafe_GetObjectSize0(JNIEnv* env, jobject o, jobject obj))
 792   oop p = JNIHandles::resolve(obj);
 793   return p->size() * HeapWordSize;
 794 UNSAFE_END
 795 
 796 
 797 static inline void throw_new(JNIEnv *env, const char *ename) {
 798   jclass cls = env->FindClass(ename);
 799   if (env->ExceptionCheck()) {
 800     env->ExceptionClear();
 801     tty->print_cr("Unsafe: cannot throw %s because FindClass has failed", ename);
 802     return;
 803   }
 804 
 805   env->ThrowNew(cls, nullptr);
 806 }
 807 
 808 static jclass Unsafe_DefineClass_impl(JNIEnv *env, jstring name, jbyteArray data, int offset, int length, jobject loader, jobject pd) {
 809   // Code lifted from JDK 1.3 ClassLoader.c
 810 
 811   jbyte *body;
 812   char *utfName = nullptr;
 813   jclass result = nullptr;
 814   char buf[128];
 815 
 816   assert(data != nullptr, "Class bytes must not be null");

 996 
 997 
 998 /// JVM_RegisterUnsafeMethods
 999 
1000 #define ADR "J"
1001 
1002 #define LANG "Ljava/lang/"
1003 
1004 #define OBJ LANG "Object;"
1005 #define CLS LANG "Class;"
1006 #define FLD LANG "reflect/Field;"
1007 #define THR LANG "Throwable;"
1008 
1009 #define DC_Args  LANG "String;[BII" LANG "ClassLoader;" "Ljava/security/ProtectionDomain;"
1010 #define DAC_Args CLS "[B[" OBJ
1011 
1012 #define CC (char*)  /*cast a literal from (const char*)*/
1013 #define FN_PTR(f) CAST_FROM_FN_PTR(void*, &f)
1014 
1015 #define DECLARE_GETPUTOOP(Type, Desc) \
1016     {CC "get"  #Type,      CC "(" OBJ "J)" #Desc,                 FN_PTR(Unsafe_Get##Type)}, \
1017     {CC "put"  #Type,      CC "(" OBJ "J" #Desc ")V",             FN_PTR(Unsafe_Put##Type)}, \
1018     {CC "get"  #Type "Volatile",      CC "(" OBJ "J)" #Desc,      FN_PTR(Unsafe_Get##Type##Volatile)}, \
1019     {CC "put"  #Type "Volatile",      CC "(" OBJ "J" #Desc ")V",  FN_PTR(Unsafe_Put##Type##Volatile)}
1020 
1021 
1022 static JNINativeMethod jdk_internal_misc_Unsafe_methods[] = {
1023     {CC "getReference",         CC "(" OBJ "J)" OBJ "",   FN_PTR(Unsafe_GetReference)},
1024     {CC "putReference",         CC "(" OBJ "J" OBJ ")V",  FN_PTR(Unsafe_PutReference)},
1025     {CC "getReferenceVolatile", CC "(" OBJ "J)" OBJ,      FN_PTR(Unsafe_GetReferenceVolatile)},
1026     {CC "putReferenceVolatile", CC "(" OBJ "J" OBJ ")V",  FN_PTR(Unsafe_PutReferenceVolatile)},
1027 
1028     {CC "isFlatArray", CC "(" CLS ")Z",                   FN_PTR(Unsafe_IsFlatArray)},
1029     {CC "isFlatField0", CC "(" OBJ ")Z",                  FN_PTR(Unsafe_IsFlatField)},
1030     {CC "hasNullMarker0"   , CC "(" OBJ ")Z",                    FN_PTR(Unsafe_HasNullMarker)},
1031     {CC "nullMarkerOffset0", CC "(" OBJ ")I",                    FN_PTR(Unsafe_NullMarkerOffset)},
1032     {CC "getValue",         CC "(" OBJ "J" CLS ")" OBJ,   FN_PTR(Unsafe_GetValue)},
1033     {CC "putValue",         CC "(" OBJ "J" CLS OBJ ")V",  FN_PTR(Unsafe_PutValue)},
1034     {CC "uninitializedDefaultValue", CC "(" CLS ")" OBJ,  FN_PTR(Unsafe_UninitializedDefaultValue)},
1035     {CC "makePrivateBuffer",     CC "(" OBJ ")" OBJ,      FN_PTR(Unsafe_MakePrivateBuffer)},
1036     {CC "finishPrivateBuffer",   CC "(" OBJ ")" OBJ,      FN_PTR(Unsafe_FinishPrivateBuffer)},
1037     {CC "valueHeaderSize",       CC "(" CLS ")J",         FN_PTR(Unsafe_ValueHeaderSize)},
1038 
1039     {CC "getUncompressedObject", CC "(" ADR ")" OBJ,  FN_PTR(Unsafe_GetUncompressedObject)},
1040 
1041     DECLARE_GETPUTOOP(Boolean, Z),
1042     DECLARE_GETPUTOOP(Byte, B),
1043     DECLARE_GETPUTOOP(Short, S),
1044     DECLARE_GETPUTOOP(Char, C),
1045     DECLARE_GETPUTOOP(Int, I),
1046     DECLARE_GETPUTOOP(Long, J),
1047     DECLARE_GETPUTOOP(Float, F),
1048     DECLARE_GETPUTOOP(Double, D),
1049 
1050     {CC "allocateMemory0",    CC "(J)" ADR,              FN_PTR(Unsafe_AllocateMemory0)},
1051     {CC "reallocateMemory0",  CC "(" ADR "J)" ADR,       FN_PTR(Unsafe_ReallocateMemory0)},
1052     {CC "freeMemory0",        CC "(" ADR ")V",           FN_PTR(Unsafe_FreeMemory0)},
1053 
1054     {CC "objectFieldOffset0", CC "(" FLD ")J",           FN_PTR(Unsafe_ObjectFieldOffset0)},
1055     {CC "objectFieldOffset1", CC "(" CLS LANG "String;)J", FN_PTR(Unsafe_ObjectFieldOffset1)},
1056     {CC "staticFieldOffset0", CC "(" FLD ")J",           FN_PTR(Unsafe_StaticFieldOffset0)},
1057     {CC "staticFieldBase0",   CC "(" FLD ")" OBJ,        FN_PTR(Unsafe_StaticFieldBase0)},
1058     {CC "ensureClassInitialized0", CC "(" CLS ")V",      FN_PTR(Unsafe_EnsureClassInitialized0)},
1059     {CC "arrayBaseOffset0",   CC "(" CLS ")I",           FN_PTR(Unsafe_ArrayBaseOffset0)},
1060     {CC "arrayIndexScale0",   CC "(" CLS ")I",           FN_PTR(Unsafe_ArrayIndexScale0)},
1061     {CC "getObjectSize0",     CC "(Ljava/lang/Object;)J", FN_PTR(Unsafe_GetObjectSize0)},
1062 
1063     {CC "defineClass0",       CC "(" DC_Args ")" CLS,    FN_PTR(Unsafe_DefineClass0)},
1064     {CC "allocateInstance",   CC "(" CLS ")" OBJ,        FN_PTR(Unsafe_AllocateInstance)},
1065     {CC "throwException",     CC "(" THR ")V",           FN_PTR(Unsafe_ThrowException)},
1066     {CC "compareAndSetReference",CC "(" OBJ "J" OBJ "" OBJ ")Z", FN_PTR(Unsafe_CompareAndSetReference)},
1067     {CC "compareAndSetInt",   CC "(" OBJ "J""I""I"")Z",  FN_PTR(Unsafe_CompareAndSetInt)},
1068     {CC "compareAndSetLong",  CC "(" OBJ "J""J""J"")Z",  FN_PTR(Unsafe_CompareAndSetLong)},
1069     {CC "compareAndExchangeReference", CC "(" OBJ "J" OBJ "" OBJ ")" OBJ, FN_PTR(Unsafe_CompareAndExchangeReference)},
1070     {CC "compareAndExchangeInt",  CC "(" OBJ "J""I""I"")I", FN_PTR(Unsafe_CompareAndExchangeInt)},
1071     {CC "compareAndExchangeLong", CC "(" OBJ "J""J""J"")J", FN_PTR(Unsafe_CompareAndExchangeLong)},
1072 
1073     {CC "park",               CC "(ZJ)V",                FN_PTR(Unsafe_Park)},
1074     {CC "unpark",             CC "(" OBJ ")V",           FN_PTR(Unsafe_Unpark)},
1075 
1076     {CC "getLoadAverage0",    CC "([DI)I",               FN_PTR(Unsafe_GetLoadAverage0)},
1077 
1078     {CC "copyMemory0",        CC "(" OBJ "J" OBJ "JJ)V", FN_PTR(Unsafe_CopyMemory0)},
1079     {CC "copySwapMemory0",    CC "(" OBJ "J" OBJ "JJJ)V", FN_PTR(Unsafe_CopySwapMemory0)},
1080     {CC "writeback0",         CC "(" "J" ")V",           FN_PTR(Unsafe_WriteBack0)},
1081     {CC "writebackPreSync0",  CC "()V",                  FN_PTR(Unsafe_WriteBackPreSync0)},
< prev index next >