< prev index next >

src/hotspot/share/prims/unsafe.cpp

Print this page

   1 /*
   2  * Copyright (c) 2000, 2024, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  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)},

   1 /*
   2  * Copyright (c) 2000, 2025, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  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_payload_from_addr(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   // TODO FIXME: problem below, with new APIs, null checking depends on LayoutKind, but Unsafe APIs are not able to communicate the right layout kind yet
 409   vk->write_value_to_addr(v, ((char*)(oopDesc*)base) + offset, LayoutKind::PAYLOAD, true, CHECK);// TODO FIXME Hard coded layout kind to make the code compile, Unsafe must be upgraded to handle correct layout kind
 410 } UNSAFE_END
 411 
 412 UNSAFE_ENTRY(jobject, Unsafe_MakePrivateBuffer(JNIEnv *env, jobject unsafe, jobject value)) {
 413   oop v = JNIHandles::resolve_non_null(value);
 414   assert(v->is_inline_type(), "must be an inline type instance");
 415   Handle vh(THREAD, v);
 416   InlineKlass* vk = InlineKlass::cast(v->klass());
 417   instanceOop new_value = vk->allocate_instance_buffer(CHECK_NULL);
 418   vk->copy_payload_to_addr(vk->data_for_oop(vh()), vk->data_for_oop(new_value), LayoutKind::PAYLOAD, false);
 419   markWord mark = new_value->mark();
 420   new_value->set_mark(mark.enter_larval_state());
 421   return JNIHandles::make_local(THREAD, new_value);
 422 } UNSAFE_END
 423 
 424 UNSAFE_ENTRY(jobject, Unsafe_FinishPrivateBuffer(JNIEnv *env, jobject unsafe, jobject value)) {
 425   oop v = JNIHandles::resolve(value);
 426   assert(v->mark().is_larval_state(), "must be a larval value");
 427   markWord mark = v->mark();
 428   v->set_mark(mark.exit_larval_state());
 429   return JNIHandles::make_local(THREAD, v);
 430 } UNSAFE_END
 431 
 432 UNSAFE_ENTRY(jobject, Unsafe_GetReferenceVolatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset)) {
 433   oop p = JNIHandles::resolve(obj);
 434   assert_field_offset_sane(p, offset);
 435   oop v = HeapAccess<MO_SEQ_CST | ON_UNKNOWN_OOP_REF>::oop_load_at(p, offset);
 436   return JNIHandles::make_local(THREAD, v);
 437 } UNSAFE_END
 438 
 439 UNSAFE_ENTRY(void, Unsafe_PutReferenceVolatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject x_h)) {
 440   oop x = JNIHandles::resolve(x_h);
 441   oop p = JNIHandles::resolve(obj);
 442   assert_field_offset_sane(p, offset);
 443   HeapAccess<MO_SEQ_CST | ON_UNKNOWN_OOP_REF>::oop_store_at(p, offset, x);
 444 } UNSAFE_END
 445 
 446 UNSAFE_ENTRY(jobject, Unsafe_GetUncompressedObject(JNIEnv *env, jobject unsafe, jlong addr)) {
 447   oop v = *(oop*) (address) addr;
 448   return JNIHandles::make_local(THREAD, v);
 449 } UNSAFE_END
 450 
 451 #define DEFINE_GETSETOOP(java_type, Type) \

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

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