1 /*
   2  * Copyright (c) 2000, 2022, 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 "jni.h"
  27 #include "jvm.h"
  28 #include "classfile/classFileStream.hpp"
  29 #include "classfile/classLoader.hpp"
  30 #include "classfile/classLoadInfo.hpp"
  31 #include "classfile/javaClasses.inline.hpp"
  32 #include "classfile/systemDictionary.hpp"
  33 #include "classfile/vmSymbols.hpp"
  34 #include "jfr/jfrEvents.hpp"
  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 "services/threadService.hpp"
  65 #include "utilities/align.hpp"
  66 #include "utilities/copy.hpp"
  67 #include "utilities/dtrace.hpp"
  68 #include "utilities/macros.hpp"
  69 
  70 /**
  71  * Implementation of the jdk.internal.misc.Unsafe class
  72  */
  73 
  74 
  75 #define MAX_OBJECT_SIZE \
  76   ( arrayOopDesc::header_size(T_DOUBLE) * HeapWordSize \
  77     + ((julong)max_jint * sizeof(double)) )
  78 
  79 
  80 #define UNSAFE_ENTRY(result_type, header) \
  81   JVM_ENTRY(static result_type, header)
  82 
  83 #define UNSAFE_LEAF(result_type, header) \
  84   JVM_LEAF(static result_type, header)
  85 
  86 #define UNSAFE_END JVM_END
  87 
  88 
  89 static inline void* addr_from_java(jlong addr) {
  90   // This assert fails in a variety of ways on 32-bit systems.
  91   // It is impossible to predict whether native code that converts
  92   // pointers to longs will sign-extend or zero-extend the addresses.
  93   //assert(addr == (uintptr_t)addr, "must not be odd high bits");
  94   return (void*)(uintptr_t)addr;
  95 }
  96 
  97 static inline jlong addr_to_java(void* p) {
  98   assert(p == (void*)(uintptr_t)p, "must not be odd high bits");
  99   return (uintptr_t)p;
 100 }
 101 
 102 
 103 // Note: The VM's obj_field and related accessors use byte-scaled
 104 // ("unscaled") offsets, just as the unsafe methods do.
 105 
 106 // However, the method Unsafe.fieldOffset explicitly declines to
 107 // guarantee this.  The field offset values manipulated by the Java user
 108 // through the Unsafe API are opaque cookies that just happen to be byte
 109 // offsets.  We represent this state of affairs by passing the cookies
 110 // through conversion functions when going between the VM and the Unsafe API.
 111 // The conversion functions just happen to be no-ops at present.
 112 
 113 static inline jlong field_offset_to_byte_offset(jlong field_offset) {
 114   return field_offset;
 115 }
 116 
 117 static inline jlong field_offset_from_byte_offset(jlong byte_offset) {
 118   return byte_offset;
 119 }
 120 
 121 static inline void assert_field_offset_sane(oop p, jlong field_offset) {
 122 #ifdef ASSERT
 123   jlong byte_offset = field_offset_to_byte_offset(field_offset);
 124 
 125   if (p != NULL) {
 126     assert(byte_offset >= 0 && byte_offset <= (jlong)MAX_OBJECT_SIZE, "sane offset");
 127     if (byte_offset == (jint)byte_offset) {
 128       void* ptr_plus_disp = cast_from_oop<address>(p) + byte_offset;
 129       assert(p->field_addr<void>((jint)byte_offset) == ptr_plus_disp,
 130              "raw [ptr+disp] must be consistent with oop::field_addr");
 131     }
 132     jlong p_size = HeapWordSize * (jlong)(p->size());
 133     assert(byte_offset < p_size, "Unsafe access: offset " INT64_FORMAT " > object's size " INT64_FORMAT, (int64_t)byte_offset, (int64_t)p_size);
 134   }
 135 #endif
 136 }
 137 
 138 static inline void* index_oop_from_field_offset_long(oop p, jlong field_offset) {
 139   assert_field_offset_sane(p, field_offset);
 140   jlong byte_offset = field_offset_to_byte_offset(field_offset);
 141 
 142   if (sizeof(char*) == sizeof(jint)) {   // (this constant folds!)
 143     return cast_from_oop<address>(p) + (jint) byte_offset;
 144   } else {
 145     return cast_from_oop<address>(p) +        byte_offset;
 146   }
 147 }
 148 
 149 // Externally callable versions:
 150 // (Use these in compiler intrinsics which emulate unsafe primitives.)
 151 jlong Unsafe_field_offset_to_byte_offset(jlong field_offset) {
 152   return field_offset;
 153 }
 154 jlong Unsafe_field_offset_from_byte_offset(jlong byte_offset) {
 155   return byte_offset;
 156 }
 157 
 158 ///// Data read/writes on the Java heap and in native (off-heap) memory
 159 
 160 /**
 161  * Helper class to wrap memory accesses in JavaThread::doing_unsafe_access()
 162  */
 163 class GuardUnsafeAccess {
 164   JavaThread* _thread;
 165 
 166 public:
 167   GuardUnsafeAccess(JavaThread* thread) : _thread(thread) {
 168     // native/off-heap access which may raise SIGBUS if accessing
 169     // memory mapped file data in a region of the file which has
 170     // been truncated and is now invalid.
 171     _thread->set_doing_unsafe_access(true);
 172   }
 173 
 174   ~GuardUnsafeAccess() {
 175     _thread->set_doing_unsafe_access(false);
 176   }
 177 };
 178 
 179 /**
 180  * Helper class for accessing memory.
 181  *
 182  * Normalizes values and wraps accesses in
 183  * JavaThread::doing_unsafe_access() if needed.
 184  */
 185 template <typename T>
 186 class MemoryAccess : StackObj {
 187   JavaThread* _thread;
 188   oop _obj;
 189   ptrdiff_t _offset;
 190 
 191   // Resolves and returns the address of the memory access.
 192   // This raw memory access may fault, so we make sure it happens within the
 193   // guarded scope by making the access volatile at least. Since the store
 194   // of Thread::set_doing_unsafe_access() is also volatile, these accesses
 195   // can not be reordered by the compiler. Therefore, if the access triggers
 196   // a fault, we will know that Thread::doing_unsafe_access() returns true.
 197   volatile T* addr() {
 198     void* addr = index_oop_from_field_offset_long(_obj, _offset);
 199     return static_cast<volatile T*>(addr);
 200   }
 201 
 202   template <typename U>
 203   U normalize_for_write(U x) {
 204     return x;
 205   }
 206 
 207   jboolean normalize_for_write(jboolean x) {
 208     return x & 1;
 209   }
 210 
 211   template <typename U>
 212   U normalize_for_read(U x) {
 213     return x;
 214   }
 215 
 216   jboolean normalize_for_read(jboolean x) {
 217     return x != 0;
 218   }
 219 
 220 public:
 221   MemoryAccess(JavaThread* thread, jobject obj, jlong offset)
 222     : _thread(thread), _obj(JNIHandles::resolve(obj)), _offset((ptrdiff_t)offset) {
 223     assert_field_offset_sane(_obj, offset);
 224   }
 225 
 226   T get() {
 227     GuardUnsafeAccess guard(_thread);
 228     return normalize_for_read(*addr());
 229   }
 230 
 231   void put(T x) {
 232     GuardUnsafeAccess guard(_thread);
 233     assert(_obj == NULL || !_obj->is_inline_type() || _obj->mark().is_larval_state(), "must be an object instance or a larval inline type");
 234     *addr() = normalize_for_write(x);
 235   }
 236 
 237   T get_volatile() {
 238     GuardUnsafeAccess guard(_thread);
 239     volatile T ret = RawAccess<MO_SEQ_CST>::load(addr());
 240     return normalize_for_read(ret);
 241   }
 242 
 243   void put_volatile(T x) {
 244     GuardUnsafeAccess guard(_thread);
 245     RawAccess<MO_SEQ_CST>::store(addr(), normalize_for_write(x));
 246   }
 247 };
 248 
 249 #ifdef ASSERT
 250 /*
 251  * Get the field descriptor of the field of the given object at the given offset.
 252  */
 253 static bool get_field_descriptor(oop p, jlong offset, fieldDescriptor* fd) {
 254   bool found = false;
 255   Klass* k = p->klass();
 256   if (k->is_instance_klass()) {
 257     InstanceKlass* ik = InstanceKlass::cast(k);
 258     found = ik->find_field_from_offset((int)offset, false, fd);
 259     if (!found && ik->is_mirror_instance_klass()) {
 260       Klass* k2 = java_lang_Class::as_Klass(p);
 261       if (k2->is_instance_klass()) {
 262         ik = InstanceKlass::cast(k2);
 263         found = ik->find_field_from_offset((int)offset, true, fd);
 264       }
 265     }
 266   }
 267   return found;
 268 }
 269 #endif // ASSERT
 270 
 271 static void assert_and_log_unsafe_value_access(oop p, jlong offset, InlineKlass* vk) {
 272   Klass* k = p->klass();
 273 #ifdef ASSERT
 274   if (k->is_instance_klass()) {
 275     assert_field_offset_sane(p, offset);
 276     fieldDescriptor fd;
 277     bool found = get_field_descriptor(p, offset, &fd);
 278     if (found) {
 279       assert(found, "value field not found");
 280       assert(fd.is_inlined(), "field not flat");
 281     } else {
 282       if (log_is_enabled(Trace, valuetypes)) {
 283         log_trace(valuetypes)("not a field in %s at offset " UINT64_FORMAT_X,
 284                               p->klass()->external_name(), (uint64_t)offset);
 285       }
 286     }
 287   } else if (k->is_flatArray_klass()) {
 288     FlatArrayKlass* vak = FlatArrayKlass::cast(k);
 289     int index = (offset - vak->array_header_in_bytes()) / vak->element_byte_size();
 290     address dest = (address)((flatArrayOop)p)->value_at_addr(index, vak->layout_helper());
 291     assert(dest == (cast_from_oop<address>(p) + offset), "invalid offset");
 292   } else {
 293     ShouldNotReachHere();
 294   }
 295 #endif // ASSERT
 296   if (log_is_enabled(Trace, valuetypes)) {
 297     if (k->is_flatArray_klass()) {
 298       FlatArrayKlass* vak = FlatArrayKlass::cast(k);
 299       int index = (offset - vak->array_header_in_bytes()) / vak->element_byte_size();
 300       address dest = (address)((flatArrayOop)p)->value_at_addr(index, vak->layout_helper());
 301       log_trace(valuetypes)("%s array type %s index %d element size %d offset " UINT64_FORMAT_X " at " INTPTR_FORMAT,
 302                             p->klass()->external_name(), vak->external_name(),
 303                             index, vak->element_byte_size(), (uint64_t)offset, p2i(dest));
 304     } else {
 305       log_trace(valuetypes)("%s field type %s at offset " UINT64_FORMAT_X,
 306                             p->klass()->external_name(), vk->external_name(), (uint64_t)offset);
 307     }
 308   }
 309 }
 310 
 311 // These functions allow a null base pointer with an arbitrary address.
 312 // But if the base pointer is non-null, the offset should make some sense.
 313 // That is, it should be in the range [0, MAX_OBJECT_SIZE].
 314 UNSAFE_ENTRY(jobject, Unsafe_GetReference(JNIEnv *env, jobject unsafe, jobject obj, jlong offset)) {
 315   oop p = JNIHandles::resolve(obj);
 316   assert_field_offset_sane(p, offset);
 317   oop v = HeapAccess<ON_UNKNOWN_OOP_REF>::oop_load_at(p, offset);
 318   return JNIHandles::make_local(THREAD, v);
 319 } UNSAFE_END
 320 
 321 UNSAFE_ENTRY(void, Unsafe_PutReference(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject x_h)) {
 322   oop x = JNIHandles::resolve(x_h);
 323   oop p = JNIHandles::resolve(obj);
 324   assert_field_offset_sane(p, offset);
 325   assert(!p->is_inline_type() || p->mark().is_larval_state(), "must be an object instance or a larval inline type");
 326   HeapAccess<ON_UNKNOWN_OOP_REF>::oop_store_at(p, offset, x);
 327 } UNSAFE_END
 328 
 329 UNSAFE_ENTRY(jlong, Unsafe_ValueHeaderSize(JNIEnv *env, jobject unsafe, jclass c)) {
 330   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(c));
 331   InlineKlass* vk = InlineKlass::cast(k);
 332   return vk->first_field_offset();
 333 } UNSAFE_END
 334 
 335 UNSAFE_ENTRY(jboolean, Unsafe_IsFlattenedField(JNIEnv *env, jobject unsafe, jobject o)) {
 336   oop f = JNIHandles::resolve_non_null(o);
 337   Klass* k = java_lang_Class::as_Klass(java_lang_reflect_Field::clazz(f));
 338   int slot = java_lang_reflect_Field::slot(f);
 339   return InstanceKlass::cast(k)->field_is_inlined(slot);
 340 } UNSAFE_END
 341 
 342 UNSAFE_ENTRY(jboolean, Unsafe_IsFlattenedArray(JNIEnv *env, jobject unsafe, jclass c)) {
 343   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(c));
 344   return k->is_flatArray_klass();
 345 } UNSAFE_END
 346 
 347 UNSAFE_ENTRY(jobject, Unsafe_UninitializedDefaultValue(JNIEnv *env, jobject unsafe, jclass vc)) {
 348   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(vc));
 349   InlineKlass* vk = InlineKlass::cast(k);
 350   oop v = vk->default_value();
 351   return JNIHandles::make_local(THREAD, v);
 352 } UNSAFE_END
 353 
 354 UNSAFE_ENTRY(jobject, Unsafe_GetValue(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jclass vc)) {
 355   oop base = JNIHandles::resolve(obj);
 356   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(vc));
 357   InlineKlass* vk = InlineKlass::cast(k);
 358   assert_and_log_unsafe_value_access(base, offset, vk);
 359   Handle base_h(THREAD, base);
 360   oop v = vk->read_inlined_field(base_h(), offset, CHECK_NULL);
 361   return JNIHandles::make_local(THREAD, v);
 362 } UNSAFE_END
 363 
 364 UNSAFE_ENTRY(void, Unsafe_PutValue(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jclass vc, jobject value)) {
 365   oop base = JNIHandles::resolve(obj);
 366   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(vc));
 367   InlineKlass* vk = InlineKlass::cast(k);
 368   assert(!base->is_inline_type() || base->mark().is_larval_state(), "must be an object instance or a larval inline type");
 369   assert_and_log_unsafe_value_access(base, offset, vk);
 370   oop v = JNIHandles::resolve(value);
 371   vk->write_inlined_field(base, offset, v, CHECK);
 372 } UNSAFE_END
 373 
 374 UNSAFE_ENTRY(jobject, Unsafe_MakePrivateBuffer(JNIEnv *env, jobject unsafe, jobject value)) {
 375   oop v = JNIHandles::resolve_non_null(value);
 376   assert(v->is_inline_type(), "must be an inline type instance");
 377   Handle vh(THREAD, v);
 378   InlineKlass* vk = InlineKlass::cast(v->klass());
 379   instanceOop new_value = vk->allocate_instance_buffer(CHECK_NULL);
 380   vk->inline_copy_oop_to_new_oop(vh(),  new_value);
 381   markWord mark = new_value->mark();
 382   new_value->set_mark(mark.enter_larval_state());
 383   return JNIHandles::make_local(THREAD, new_value);
 384 } UNSAFE_END
 385 
 386 UNSAFE_ENTRY(jobject, Unsafe_FinishPrivateBuffer(JNIEnv *env, jobject unsafe, jobject value)) {
 387   oop v = JNIHandles::resolve(value);
 388   assert(v->mark().is_larval_state(), "must be a larval value");
 389   markWord mark = v->mark();
 390   v->set_mark(mark.exit_larval_state());
 391   return JNIHandles::make_local(THREAD, v);
 392 } UNSAFE_END
 393 
 394 UNSAFE_ENTRY(jobject, Unsafe_GetReferenceVolatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset)) {
 395   oop p = JNIHandles::resolve(obj);
 396   assert_field_offset_sane(p, offset);
 397   oop v = HeapAccess<MO_SEQ_CST | ON_UNKNOWN_OOP_REF>::oop_load_at(p, offset);
 398   return JNIHandles::make_local(THREAD, v);
 399 } UNSAFE_END
 400 
 401 UNSAFE_ENTRY(void, Unsafe_PutReferenceVolatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject x_h)) {
 402   oop x = JNIHandles::resolve(x_h);
 403   oop p = JNIHandles::resolve(obj);
 404   assert_field_offset_sane(p, offset);
 405   HeapAccess<MO_SEQ_CST | ON_UNKNOWN_OOP_REF>::oop_store_at(p, offset, x);
 406 } UNSAFE_END
 407 
 408 UNSAFE_ENTRY(jobject, Unsafe_GetUncompressedObject(JNIEnv *env, jobject unsafe, jlong addr)) {
 409   oop v = *(oop*) (address) addr;
 410   return JNIHandles::make_local(THREAD, v);
 411 } UNSAFE_END
 412 
 413 #define DEFINE_GETSETOOP(java_type, Type) \
 414  \
 415 UNSAFE_ENTRY(java_type, Unsafe_Get##Type(JNIEnv *env, jobject unsafe, jobject obj, jlong offset)) { \
 416   return MemoryAccess<java_type>(thread, obj, offset).get(); \
 417 } UNSAFE_END \
 418  \
 419 UNSAFE_ENTRY(void, Unsafe_Put##Type(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, java_type x)) { \
 420   MemoryAccess<java_type>(thread, obj, offset).put(x); \
 421 } UNSAFE_END \
 422  \
 423 // END DEFINE_GETSETOOP.
 424 
 425 DEFINE_GETSETOOP(jboolean, Boolean)
 426 DEFINE_GETSETOOP(jbyte, Byte)
 427 DEFINE_GETSETOOP(jshort, Short);
 428 DEFINE_GETSETOOP(jchar, Char);
 429 DEFINE_GETSETOOP(jint, Int);
 430 DEFINE_GETSETOOP(jlong, Long);
 431 DEFINE_GETSETOOP(jfloat, Float);
 432 DEFINE_GETSETOOP(jdouble, Double);
 433 
 434 #undef DEFINE_GETSETOOP
 435 
 436 #define DEFINE_GETSETOOP_VOLATILE(java_type, Type) \
 437  \
 438 UNSAFE_ENTRY(java_type, Unsafe_Get##Type##Volatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset)) { \
 439   return MemoryAccess<java_type>(thread, obj, offset).get_volatile(); \
 440 } UNSAFE_END \
 441  \
 442 UNSAFE_ENTRY(void, Unsafe_Put##Type##Volatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, java_type x)) { \
 443   MemoryAccess<java_type>(thread, obj, offset).put_volatile(x); \
 444 } UNSAFE_END \
 445  \
 446 // END DEFINE_GETSETOOP_VOLATILE.
 447 
 448 DEFINE_GETSETOOP_VOLATILE(jboolean, Boolean)
 449 DEFINE_GETSETOOP_VOLATILE(jbyte, Byte)
 450 DEFINE_GETSETOOP_VOLATILE(jshort, Short);
 451 DEFINE_GETSETOOP_VOLATILE(jchar, Char);
 452 DEFINE_GETSETOOP_VOLATILE(jint, Int);
 453 DEFINE_GETSETOOP_VOLATILE(jlong, Long);
 454 DEFINE_GETSETOOP_VOLATILE(jfloat, Float);
 455 DEFINE_GETSETOOP_VOLATILE(jdouble, Double);
 456 
 457 #undef DEFINE_GETSETOOP_VOLATILE
 458 
 459 UNSAFE_LEAF(void, Unsafe_FullFence(JNIEnv *env, jobject unsafe)) {
 460   OrderAccess::fence();
 461 } UNSAFE_END
 462 
 463 ////// Allocation requests
 464 
 465 UNSAFE_ENTRY(jobject, Unsafe_AllocateInstance(JNIEnv *env, jobject unsafe, jclass cls)) {
 466   JvmtiVMObjectAllocEventCollector oam;
 467   instanceOop i = InstanceKlass::allocate_instance(JNIHandles::resolve_non_null(cls), CHECK_NULL);
 468   return JNIHandles::make_local(THREAD, i);
 469 } UNSAFE_END
 470 
 471 UNSAFE_ENTRY(jlong, Unsafe_AllocateMemory0(JNIEnv *env, jobject unsafe, jlong size)) {
 472   size_t sz = (size_t)size;
 473 
 474   assert(is_aligned(sz, HeapWordSize), "sz not aligned");
 475 
 476   void* x = os::malloc(sz, mtOther);
 477 
 478   return addr_to_java(x);
 479 } UNSAFE_END
 480 
 481 UNSAFE_ENTRY(jlong, Unsafe_ReallocateMemory0(JNIEnv *env, jobject unsafe, jlong addr, jlong size)) {
 482   void* p = addr_from_java(addr);
 483   size_t sz = (size_t)size;
 484 
 485   assert(is_aligned(sz, HeapWordSize), "sz not aligned");
 486 
 487   void* x = os::realloc(p, sz, mtOther);
 488 
 489   return addr_to_java(x);
 490 } UNSAFE_END
 491 
 492 UNSAFE_ENTRY(void, Unsafe_FreeMemory0(JNIEnv *env, jobject unsafe, jlong addr)) {
 493   void* p = addr_from_java(addr);
 494 
 495   os::free(p);
 496 } UNSAFE_END
 497 
 498 UNSAFE_ENTRY(void, Unsafe_SetMemory0(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jlong size, jbyte value)) {
 499   size_t sz = (size_t)size;
 500 
 501   oop base = JNIHandles::resolve(obj);
 502   void* p = index_oop_from_field_offset_long(base, offset);
 503 
 504   Copy::fill_to_memory_atomic(p, sz, value);
 505 } UNSAFE_END
 506 
 507 UNSAFE_ENTRY(void, Unsafe_CopyMemory0(JNIEnv *env, jobject unsafe, jobject srcObj, jlong srcOffset, jobject dstObj, jlong dstOffset, jlong size)) {
 508   size_t sz = (size_t)size;
 509 
 510   oop srcp = JNIHandles::resolve(srcObj);
 511   oop dstp = JNIHandles::resolve(dstObj);
 512 
 513   void* src = index_oop_from_field_offset_long(srcp, srcOffset);
 514   void* dst = index_oop_from_field_offset_long(dstp, dstOffset);
 515   {
 516     GuardUnsafeAccess guard(thread);
 517     if (StubRoutines::unsafe_arraycopy() != NULL) {
 518       MACOS_AARCH64_ONLY(ThreadWXEnable wx(WXExec, thread));
 519       StubRoutines::UnsafeArrayCopy_stub()(src, dst, sz);
 520     } else {
 521       Copy::conjoint_memory_atomic(src, dst, sz);
 522     }
 523   }
 524 } UNSAFE_END
 525 
 526 // This function is a leaf since if the source and destination are both in native memory
 527 // the copy may potentially be very large, and we don't want to disable GC if we can avoid it.
 528 // If either source or destination (or both) are on the heap, the function will enter VM using
 529 // JVM_ENTRY_FROM_LEAF
 530 UNSAFE_LEAF(void, Unsafe_CopySwapMemory0(JNIEnv *env, jobject unsafe, jobject srcObj, jlong srcOffset, jobject dstObj, jlong dstOffset, jlong size, jlong elemSize)) {
 531   size_t sz = (size_t)size;
 532   size_t esz = (size_t)elemSize;
 533 
 534   if (srcObj == NULL && dstObj == NULL) {
 535     // Both src & dst are in native memory
 536     address src = (address)srcOffset;
 537     address dst = (address)dstOffset;
 538 
 539     {
 540       JavaThread* thread = JavaThread::thread_from_jni_environment(env);
 541       GuardUnsafeAccess guard(thread);
 542       Copy::conjoint_swap(src, dst, sz, esz);
 543     }
 544   } else {
 545     // At least one of src/dst are on heap, transition to VM to access raw pointers
 546 
 547     JVM_ENTRY_FROM_LEAF(env, void, Unsafe_CopySwapMemory0) {
 548       oop srcp = JNIHandles::resolve(srcObj);
 549       oop dstp = JNIHandles::resolve(dstObj);
 550 
 551       address src = (address)index_oop_from_field_offset_long(srcp, srcOffset);
 552       address dst = (address)index_oop_from_field_offset_long(dstp, dstOffset);
 553 
 554       {
 555         GuardUnsafeAccess guard(thread);
 556         Copy::conjoint_swap(src, dst, sz, esz);
 557       }
 558     } JVM_END
 559   }
 560 } UNSAFE_END
 561 
 562 UNSAFE_LEAF (void, Unsafe_WriteBack0(JNIEnv *env, jobject unsafe, jlong line)) {
 563   assert(VM_Version::supports_data_cache_line_flush(), "should not get here");
 564 #ifdef ASSERT
 565   if (TraceMemoryWriteback) {
 566     tty->print_cr("Unsafe: writeback 0x%p", addr_from_java(line));
 567   }
 568 #endif
 569 
 570   MACOS_AARCH64_ONLY(ThreadWXEnable wx(WXExec, Thread::current()));
 571   assert(StubRoutines::data_cache_writeback() != NULL, "sanity");
 572   (StubRoutines::DataCacheWriteback_stub())(addr_from_java(line));
 573 } UNSAFE_END
 574 
 575 static void doWriteBackSync0(bool is_pre)
 576 {
 577   MACOS_AARCH64_ONLY(ThreadWXEnable wx(WXExec, Thread::current()));
 578   assert(StubRoutines::data_cache_writeback_sync() != NULL, "sanity");
 579   (StubRoutines::DataCacheWritebackSync_stub())(is_pre);
 580 }
 581 
 582 UNSAFE_LEAF (void, Unsafe_WriteBackPreSync0(JNIEnv *env, jobject unsafe)) {
 583   assert(VM_Version::supports_data_cache_line_flush(), "should not get here");
 584 #ifdef ASSERT
 585   if (TraceMemoryWriteback) {
 586       tty->print_cr("Unsafe: writeback pre-sync");
 587   }
 588 #endif
 589 
 590   doWriteBackSync0(true);
 591 } UNSAFE_END
 592 
 593 UNSAFE_LEAF (void, Unsafe_WriteBackPostSync0(JNIEnv *env, jobject unsafe)) {
 594   assert(VM_Version::supports_data_cache_line_flush(), "should not get here");
 595 #ifdef ASSERT
 596   if (TraceMemoryWriteback) {
 597     tty->print_cr("Unsafe: writeback pre-sync");
 598   }
 599 #endif
 600 
 601   doWriteBackSync0(false);
 602 } UNSAFE_END
 603 
 604 ////// Random queries
 605 
 606 static jlong find_field_offset(jclass clazz, jstring name, TRAPS) {
 607   assert(clazz != NULL, "clazz must not be NULL");
 608   assert(name != NULL, "name must not be NULL");
 609 
 610   ResourceMark rm(THREAD);
 611   char *utf_name = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(name));
 612 
 613   InstanceKlass* k = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(clazz)));
 614 
 615   jint offset = -1;
 616   for (JavaFieldStream fs(k); !fs.done(); fs.next()) {
 617     Symbol *name = fs.name();
 618     if (name->equals(utf_name)) {
 619       offset = fs.offset();
 620       break;
 621     }
 622   }
 623   if (offset < 0) {
 624     THROW_0(vmSymbols::java_lang_InternalError());
 625   }
 626   return field_offset_from_byte_offset(offset);
 627 }
 628 
 629 static jlong find_field_offset(jobject field, int must_be_static, TRAPS) {
 630   assert(field != NULL, "field must not be NULL");
 631 
 632   oop reflected   = JNIHandles::resolve_non_null(field);
 633   oop mirror      = java_lang_reflect_Field::clazz(reflected);
 634   Klass* k        = java_lang_Class::as_Klass(mirror);
 635   int slot        = java_lang_reflect_Field::slot(reflected);
 636   int modifiers   = java_lang_reflect_Field::modifiers(reflected);
 637 
 638   if (must_be_static >= 0) {
 639     int really_is_static = ((modifiers & JVM_ACC_STATIC) != 0);
 640     if (must_be_static != really_is_static) {
 641       THROW_0(vmSymbols::java_lang_IllegalArgumentException());
 642     }
 643   }
 644 
 645   int offset = InstanceKlass::cast(k)->field_offset(slot);
 646   return field_offset_from_byte_offset(offset);
 647 }
 648 
 649 UNSAFE_ENTRY(jlong, Unsafe_ObjectFieldOffset0(JNIEnv *env, jobject unsafe, jobject field)) {
 650   return find_field_offset(field, 0, THREAD);
 651 } UNSAFE_END
 652 
 653 UNSAFE_ENTRY(jlong, Unsafe_ObjectFieldOffset1(JNIEnv *env, jobject unsafe, jclass c, jstring name)) {
 654   return find_field_offset(c, name, THREAD);
 655 } UNSAFE_END
 656 
 657 UNSAFE_ENTRY(jlong, Unsafe_StaticFieldOffset0(JNIEnv *env, jobject unsafe, jobject field)) {
 658   return find_field_offset(field, 1, THREAD);
 659 } UNSAFE_END
 660 
 661 UNSAFE_ENTRY(jobject, Unsafe_StaticFieldBase0(JNIEnv *env, jobject unsafe, jobject field)) {
 662   assert(field != NULL, "field must not be NULL");
 663 
 664   // Note:  In this VM implementation, a field address is always a short
 665   // offset from the base of a klass metaobject.  Thus, the full dynamic
 666   // range of the return type is never used.  However, some implementations
 667   // might put the static field inside an array shared by many classes,
 668   // or even at a fixed address, in which case the address could be quite
 669   // large.  In that last case, this function would return NULL, since
 670   // the address would operate alone, without any base pointer.
 671 
 672   oop reflected   = JNIHandles::resolve_non_null(field);
 673   oop mirror      = java_lang_reflect_Field::clazz(reflected);
 674   int modifiers   = java_lang_reflect_Field::modifiers(reflected);
 675 
 676   if ((modifiers & JVM_ACC_STATIC) == 0) {
 677     THROW_0(vmSymbols::java_lang_IllegalArgumentException());
 678   }
 679 
 680   return JNIHandles::make_local(THREAD, mirror);
 681 } UNSAFE_END
 682 
 683 UNSAFE_ENTRY(void, Unsafe_EnsureClassInitialized0(JNIEnv *env, jobject unsafe, jobject clazz)) {
 684   assert(clazz != NULL, "clazz must not be NULL");
 685 
 686   oop mirror = JNIHandles::resolve_non_null(clazz);
 687 
 688   Klass* klass = java_lang_Class::as_Klass(mirror);
 689   if (klass != NULL && klass->should_be_initialized()) {
 690     InstanceKlass* k = InstanceKlass::cast(klass);
 691     k->initialize(CHECK);
 692   }
 693 }
 694 UNSAFE_END
 695 
 696 UNSAFE_ENTRY(jboolean, Unsafe_ShouldBeInitialized0(JNIEnv *env, jobject unsafe, jobject clazz)) {
 697   assert(clazz != NULL, "clazz must not be NULL");
 698 
 699   oop mirror = JNIHandles::resolve_non_null(clazz);
 700   Klass* klass = java_lang_Class::as_Klass(mirror);
 701 
 702   if (klass != NULL && klass->should_be_initialized()) {
 703     return true;
 704   }
 705 
 706   return false;
 707 }
 708 UNSAFE_END
 709 
 710 static void getBaseAndScale(int& base, int& scale, jclass clazz, TRAPS) {
 711   assert(clazz != NULL, "clazz must not be NULL");
 712 
 713   oop mirror = JNIHandles::resolve_non_null(clazz);
 714   Klass* k = java_lang_Class::as_Klass(mirror);
 715 
 716   if (k == NULL || !k->is_array_klass()) {
 717     THROW(vmSymbols::java_lang_InvalidClassException());
 718   } else if (k->is_objArray_klass()) {
 719     base  = arrayOopDesc::base_offset_in_bytes(T_OBJECT);
 720     scale = heapOopSize;
 721   } else if (k->is_typeArray_klass()) {
 722     TypeArrayKlass* tak = TypeArrayKlass::cast(k);
 723     base  = tak->array_header_in_bytes();
 724     assert(base == arrayOopDesc::base_offset_in_bytes(tak->element_type()), "array_header_size semantics ok");
 725     scale = (1 << tak->log2_element_size());
 726   } else if (k->is_flatArray_klass()) {
 727     FlatArrayKlass* vak = FlatArrayKlass::cast(k);
 728     InlineKlass* vklass = vak->element_klass();
 729     base = vak->array_header_in_bytes();
 730     scale = vak->element_byte_size();
 731   } else {
 732     ShouldNotReachHere();
 733   }
 734 }
 735 
 736 UNSAFE_ENTRY(jint, Unsafe_ArrayBaseOffset0(JNIEnv *env, jobject unsafe, jclass clazz)) {
 737   int base = 0, scale = 0;
 738   getBaseAndScale(base, scale, clazz, CHECK_0);
 739 
 740   return field_offset_from_byte_offset(base);
 741 } UNSAFE_END
 742 
 743 
 744 UNSAFE_ENTRY(jint, Unsafe_ArrayIndexScale0(JNIEnv *env, jobject unsafe, jclass clazz)) {
 745   int base = 0, scale = 0;
 746   getBaseAndScale(base, scale, clazz, CHECK_0);
 747 
 748   // This VM packs both fields and array elements down to the byte.
 749   // But watch out:  If this changes, so that array references for
 750   // a given primitive type (say, T_BOOLEAN) use different memory units
 751   // than fields, this method MUST return zero for such arrays.
 752   // For example, the VM used to store sub-word sized fields in full
 753   // words in the object layout, so that accessors like getByte(Object,int)
 754   // did not really do what one might expect for arrays.  Therefore,
 755   // this function used to report a zero scale factor, so that the user
 756   // would know not to attempt to access sub-word array elements.
 757   // // Code for unpacked fields:
 758   // if (scale < wordSize)  return 0;
 759 
 760   // The following allows for a pretty general fieldOffset cookie scheme,
 761   // but requires it to be linear in byte offset.
 762   return field_offset_from_byte_offset(scale) - field_offset_from_byte_offset(0);
 763 } UNSAFE_END
 764 
 765 
 766 UNSAFE_ENTRY(jlong, Unsafe_GetObjectSize0(JNIEnv* env, jobject o, jobject obj))
 767   oop p = JNIHandles::resolve(obj);
 768   return p->size() * HeapWordSize;
 769 UNSAFE_END
 770 
 771 
 772 static inline void throw_new(JNIEnv *env, const char *ename) {
 773   jclass cls = env->FindClass(ename);
 774   if (env->ExceptionCheck()) {
 775     env->ExceptionClear();
 776     tty->print_cr("Unsafe: cannot throw %s because FindClass has failed", ename);
 777     return;
 778   }
 779 
 780   env->ThrowNew(cls, NULL);
 781 }
 782 
 783 static jclass Unsafe_DefineClass_impl(JNIEnv *env, jstring name, jbyteArray data, int offset, int length, jobject loader, jobject pd) {
 784   // Code lifted from JDK 1.3 ClassLoader.c
 785 
 786   jbyte *body;
 787   char *utfName = NULL;
 788   jclass result = 0;
 789   char buf[128];
 790 
 791   assert(data != NULL, "Class bytes must not be NULL");
 792   assert(length >= 0, "length must not be negative: %d", length);
 793 
 794   if (UsePerfData) {
 795     ClassLoader::unsafe_defineClassCallCounter()->inc();
 796   }
 797 
 798   body = NEW_C_HEAP_ARRAY_RETURN_NULL(jbyte, length, mtInternal);
 799   if (body == NULL) {
 800     throw_new(env, "java/lang/OutOfMemoryError");
 801     return 0;
 802   }
 803 
 804   env->GetByteArrayRegion(data, offset, length, body);
 805   if (env->ExceptionOccurred()) {
 806     goto free_body;
 807   }
 808 
 809   if (name != NULL) {
 810     uint len = env->GetStringUTFLength(name);
 811     int unicode_len = env->GetStringLength(name);
 812 
 813     if (len >= sizeof(buf)) {
 814       utfName = NEW_C_HEAP_ARRAY_RETURN_NULL(char, len + 1, mtInternal);
 815       if (utfName == NULL) {
 816         throw_new(env, "java/lang/OutOfMemoryError");
 817         goto free_body;
 818       }
 819     } else {
 820       utfName = buf;
 821     }
 822 
 823     env->GetStringUTFRegion(name, 0, unicode_len, utfName);
 824 
 825     for (uint i = 0; i < len; i++) {
 826       if (utfName[i] == '.')   utfName[i] = '/';
 827     }
 828   }
 829 
 830   result = JVM_DefineClass(env, utfName, loader, body, length, pd);
 831 
 832   if (utfName && utfName != buf) {
 833     FREE_C_HEAP_ARRAY(char, utfName);
 834   }
 835 
 836  free_body:
 837   FREE_C_HEAP_ARRAY(jbyte, body);
 838   return result;
 839 }
 840 
 841 
 842 UNSAFE_ENTRY(jclass, Unsafe_DefineClass0(JNIEnv *env, jobject unsafe, jstring name, jbyteArray data, int offset, int length, jobject loader, jobject pd)) {
 843   ThreadToNativeFromVM ttnfv(thread);
 844 
 845   return Unsafe_DefineClass_impl(env, name, data, offset, length, loader, pd);
 846 } UNSAFE_END
 847 
 848 
 849 UNSAFE_ENTRY(void, Unsafe_ThrowException(JNIEnv *env, jobject unsafe, jthrowable thr)) {
 850   ThreadToNativeFromVM ttnfv(thread);
 851   env->Throw(thr);
 852 } UNSAFE_END
 853 
 854 // JSR166 ------------------------------------------------------------------
 855 
 856 UNSAFE_ENTRY(jobject, Unsafe_CompareAndExchangeReference(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject e_h, jobject x_h)) {
 857   oop x = JNIHandles::resolve(x_h);
 858   oop e = JNIHandles::resolve(e_h);
 859   oop p = JNIHandles::resolve(obj);
 860   assert_field_offset_sane(p, offset);
 861   oop res = HeapAccess<ON_UNKNOWN_OOP_REF>::oop_atomic_cmpxchg_at(p, (ptrdiff_t)offset, e, x);
 862   return JNIHandles::make_local(THREAD, res);
 863 } UNSAFE_END
 864 
 865 UNSAFE_ENTRY(jint, Unsafe_CompareAndExchangeInt(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jint e, jint x)) {
 866   oop p = JNIHandles::resolve(obj);
 867   volatile jint* addr = (volatile jint*)index_oop_from_field_offset_long(p, offset);
 868   return Atomic::cmpxchg(addr, e, x);
 869 } UNSAFE_END
 870 
 871 UNSAFE_ENTRY(jlong, Unsafe_CompareAndExchangeLong(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jlong e, jlong x)) {
 872   oop p = JNIHandles::resolve(obj);
 873   volatile jlong* addr = (volatile jlong*)index_oop_from_field_offset_long(p, offset);
 874   return Atomic::cmpxchg(addr, e, x);
 875 } UNSAFE_END
 876 
 877 UNSAFE_ENTRY(jboolean, Unsafe_CompareAndSetReference(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject e_h, jobject x_h)) {
 878   oop x = JNIHandles::resolve(x_h);
 879   oop e = JNIHandles::resolve(e_h);
 880   oop p = JNIHandles::resolve(obj);
 881   assert_field_offset_sane(p, offset);
 882   oop ret = HeapAccess<ON_UNKNOWN_OOP_REF>::oop_atomic_cmpxchg_at(p, (ptrdiff_t)offset, e, x);
 883   return ret == e;
 884 } UNSAFE_END
 885 
 886 UNSAFE_ENTRY(jboolean, Unsafe_CompareAndSetInt(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jint e, jint x)) {
 887   oop p = JNIHandles::resolve(obj);
 888   volatile jint* addr = (volatile jint*)index_oop_from_field_offset_long(p, offset);
 889   return Atomic::cmpxchg(addr, e, x) == e;
 890 } UNSAFE_END
 891 
 892 UNSAFE_ENTRY(jboolean, Unsafe_CompareAndSetLong(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jlong e, jlong x)) {
 893   oop p = JNIHandles::resolve(obj);
 894   volatile jlong* addr = (volatile jlong*)index_oop_from_field_offset_long(p, offset);
 895   return Atomic::cmpxchg(addr, e, x) == e;
 896 } UNSAFE_END
 897 
 898 static void post_thread_park_event(EventThreadPark* event, const oop obj, jlong timeout_nanos, jlong until_epoch_millis) {
 899   assert(event != NULL, "invariant");
 900   assert(event->should_commit(), "invariant");
 901   event->set_parkedClass((obj != NULL) ? obj->klass() : NULL);
 902   event->set_timeout(timeout_nanos);
 903   event->set_until(until_epoch_millis);
 904   event->set_address((obj != NULL) ? (u8)cast_from_oop<uintptr_t>(obj) : 0);
 905   event->commit();
 906 }
 907 
 908 UNSAFE_ENTRY(void, Unsafe_Park(JNIEnv *env, jobject unsafe, jboolean isAbsolute, jlong time)) {
 909   HOTSPOT_THREAD_PARK_BEGIN((uintptr_t) thread->parker(), (int) isAbsolute, time);
 910   EventThreadPark event;
 911 
 912   JavaThreadParkedState jtps(thread, time != 0);
 913   thread->parker()->park(isAbsolute != 0, time);
 914   if (event.should_commit()) {
 915     const oop obj = thread->current_park_blocker();
 916     if (time == 0) {
 917       post_thread_park_event(&event, obj, min_jlong, min_jlong);
 918     } else {
 919       if (isAbsolute != 0) {
 920         post_thread_park_event(&event, obj, min_jlong, time);
 921       } else {
 922         post_thread_park_event(&event, obj, time, min_jlong);
 923       }
 924     }
 925   }
 926   HOTSPOT_THREAD_PARK_END((uintptr_t) thread->parker());
 927 } UNSAFE_END
 928 
 929 UNSAFE_ENTRY(void, Unsafe_Unpark(JNIEnv *env, jobject unsafe, jobject jthread)) {
 930   if (jthread != NULL) {
 931     ThreadsListHandle tlh;
 932     JavaThread* thr = NULL;
 933     oop java_thread = NULL;
 934     (void) tlh.cv_internal_thread_to_JavaThread(jthread, &thr, &java_thread);
 935     if (java_thread != NULL) {
 936       // This is a valid oop.
 937       if (thr != NULL) {
 938         // The JavaThread is alive.
 939         Parker* p = thr->parker();
 940         HOTSPOT_THREAD_UNPARK((uintptr_t) p);
 941         p->unpark();
 942       }
 943     }
 944   } // ThreadsListHandle is destroyed here.
 945 
 946 } UNSAFE_END
 947 
 948 UNSAFE_ENTRY(jint, Unsafe_GetLoadAverage0(JNIEnv *env, jobject unsafe, jdoubleArray loadavg, jint nelem)) {
 949   const int max_nelem = 3;
 950   double la[max_nelem];
 951   jint ret;
 952 
 953   typeArrayOop a = typeArrayOop(JNIHandles::resolve_non_null(loadavg));
 954   assert(a->is_typeArray(), "must be type array");
 955 
 956   ret = os::loadavg(la, nelem);
 957   if (ret == -1) {
 958     return -1;
 959   }
 960 
 961   // if successful, ret is the number of samples actually retrieved.
 962   assert(ret >= 0 && ret <= max_nelem, "Unexpected loadavg return value");
 963   switch(ret) {
 964     case 3: a->double_at_put(2, (jdouble)la[2]); // fall through
 965     case 2: a->double_at_put(1, (jdouble)la[1]); // fall through
 966     case 1: a->double_at_put(0, (jdouble)la[0]); break;
 967   }
 968 
 969   return ret;
 970 } UNSAFE_END
 971 
 972 
 973 /// JVM_RegisterUnsafeMethods
 974 
 975 #define ADR "J"
 976 
 977 #define LANG "Ljava/lang/"
 978 
 979 #define OBJ LANG "Object;"
 980 #define CLS LANG "Class;"
 981 #define FLD LANG "reflect/Field;"
 982 #define THR LANG "Throwable;"
 983 
 984 #define DC_Args  LANG "String;[BII" LANG "ClassLoader;" "Ljava/security/ProtectionDomain;"
 985 #define DAC_Args CLS "[B[" OBJ
 986 
 987 #define CC (char*)  /*cast a literal from (const char*)*/
 988 #define FN_PTR(f) CAST_FROM_FN_PTR(void*, &f)
 989 
 990 #define DECLARE_GETPUTOOP(Type, Desc) \
 991     {CC "get"  #Type,      CC "(" OBJ "J)" #Desc,                 FN_PTR(Unsafe_Get##Type)}, \
 992     {CC "put"  #Type,      CC "(" OBJ "J" #Desc ")V",             FN_PTR(Unsafe_Put##Type)}, \
 993     {CC "get"  #Type "Volatile",      CC "(" OBJ "J)" #Desc,      FN_PTR(Unsafe_Get##Type##Volatile)}, \
 994     {CC "put"  #Type "Volatile",      CC "(" OBJ "J" #Desc ")V",  FN_PTR(Unsafe_Put##Type##Volatile)}
 995 
 996 
 997 static JNINativeMethod jdk_internal_misc_Unsafe_methods[] = {
 998     {CC "getReference",         CC "(" OBJ "J)" OBJ "",   FN_PTR(Unsafe_GetReference)},
 999     {CC "putReference",         CC "(" OBJ "J" OBJ ")V",  FN_PTR(Unsafe_PutReference)},
1000     {CC "getReferenceVolatile", CC "(" OBJ "J)" OBJ,      FN_PTR(Unsafe_GetReferenceVolatile)},
1001     {CC "putReferenceVolatile", CC "(" OBJ "J" OBJ ")V",  FN_PTR(Unsafe_PutReferenceVolatile)},
1002 
1003     {CC "isFlattenedArray", CC "(" CLS ")Z",                     FN_PTR(Unsafe_IsFlattenedArray)},
1004     {CC "isFlattenedField0", CC "(" OBJ ")Z",                    FN_PTR(Unsafe_IsFlattenedField)},
1005     {CC "getValue",         CC "(" OBJ "J" CLS ")" OBJ,          FN_PTR(Unsafe_GetValue)},
1006     {CC "putValue",         CC "(" OBJ "J" CLS OBJ ")V",         FN_PTR(Unsafe_PutValue)},
1007     {CC "uninitializedDefaultValue", CC "(" CLS ")" OBJ,         FN_PTR(Unsafe_UninitializedDefaultValue)},
1008     {CC "makePrivateBuffer",     CC "(" OBJ ")" OBJ,             FN_PTR(Unsafe_MakePrivateBuffer)},
1009     {CC "finishPrivateBuffer",   CC "(" OBJ ")" OBJ,             FN_PTR(Unsafe_FinishPrivateBuffer)},
1010     {CC "valueHeaderSize",       CC "(" CLS ")J",                FN_PTR(Unsafe_ValueHeaderSize)},
1011 
1012     {CC "getUncompressedObject", CC "(" ADR ")" OBJ,  FN_PTR(Unsafe_GetUncompressedObject)},
1013 
1014     DECLARE_GETPUTOOP(Boolean, Z),
1015     DECLARE_GETPUTOOP(Byte, B),
1016     DECLARE_GETPUTOOP(Short, S),
1017     DECLARE_GETPUTOOP(Char, C),
1018     DECLARE_GETPUTOOP(Int, I),
1019     DECLARE_GETPUTOOP(Long, J),
1020     DECLARE_GETPUTOOP(Float, F),
1021     DECLARE_GETPUTOOP(Double, D),
1022 
1023     {CC "allocateMemory0",    CC "(J)" ADR,              FN_PTR(Unsafe_AllocateMemory0)},
1024     {CC "reallocateMemory0",  CC "(" ADR "J)" ADR,       FN_PTR(Unsafe_ReallocateMemory0)},
1025     {CC "freeMemory0",        CC "(" ADR ")V",           FN_PTR(Unsafe_FreeMemory0)},
1026 
1027     {CC "objectFieldOffset0", CC "(" FLD ")J",           FN_PTR(Unsafe_ObjectFieldOffset0)},
1028     {CC "objectFieldOffset1", CC "(" CLS LANG "String;)J", FN_PTR(Unsafe_ObjectFieldOffset1)},
1029     {CC "staticFieldOffset0", CC "(" FLD ")J",           FN_PTR(Unsafe_StaticFieldOffset0)},
1030     {CC "staticFieldBase0",   CC "(" FLD ")" OBJ,        FN_PTR(Unsafe_StaticFieldBase0)},
1031     {CC "ensureClassInitialized0", CC "(" CLS ")V",      FN_PTR(Unsafe_EnsureClassInitialized0)},
1032     {CC "arrayBaseOffset0",   CC "(" CLS ")I",           FN_PTR(Unsafe_ArrayBaseOffset0)},
1033     {CC "arrayIndexScale0",   CC "(" CLS ")I",           FN_PTR(Unsafe_ArrayIndexScale0)},
1034     {CC "getObjectSize0",     CC "(Ljava/lang/Object;)J", FN_PTR(Unsafe_GetObjectSize0)},
1035 
1036     {CC "defineClass0",       CC "(" DC_Args ")" CLS,    FN_PTR(Unsafe_DefineClass0)},
1037     {CC "allocateInstance",   CC "(" CLS ")" OBJ,        FN_PTR(Unsafe_AllocateInstance)},
1038     {CC "throwException",     CC "(" THR ")V",           FN_PTR(Unsafe_ThrowException)},
1039     {CC "compareAndSetReference",CC "(" OBJ "J" OBJ "" OBJ ")Z", FN_PTR(Unsafe_CompareAndSetReference)},
1040     {CC "compareAndSetInt",   CC "(" OBJ "J""I""I"")Z",  FN_PTR(Unsafe_CompareAndSetInt)},
1041     {CC "compareAndSetLong",  CC "(" OBJ "J""J""J"")Z",  FN_PTR(Unsafe_CompareAndSetLong)},
1042     {CC "compareAndExchangeReference", CC "(" OBJ "J" OBJ "" OBJ ")" OBJ, FN_PTR(Unsafe_CompareAndExchangeReference)},
1043     {CC "compareAndExchangeInt",  CC "(" OBJ "J""I""I"")I", FN_PTR(Unsafe_CompareAndExchangeInt)},
1044     {CC "compareAndExchangeLong", CC "(" OBJ "J""J""J"")J", FN_PTR(Unsafe_CompareAndExchangeLong)},
1045 
1046     {CC "park",               CC "(ZJ)V",                FN_PTR(Unsafe_Park)},
1047     {CC "unpark",             CC "(" OBJ ")V",           FN_PTR(Unsafe_Unpark)},
1048 
1049     {CC "getLoadAverage0",    CC "([DI)I",               FN_PTR(Unsafe_GetLoadAverage0)},
1050 
1051     {CC "copyMemory0",        CC "(" OBJ "J" OBJ "JJ)V", FN_PTR(Unsafe_CopyMemory0)},
1052     {CC "copySwapMemory0",    CC "(" OBJ "J" OBJ "JJJ)V", FN_PTR(Unsafe_CopySwapMemory0)},
1053     {CC "writeback0",         CC "(" "J" ")V",           FN_PTR(Unsafe_WriteBack0)},
1054     {CC "writebackPreSync0",  CC "()V",                  FN_PTR(Unsafe_WriteBackPreSync0)},
1055     {CC "writebackPostSync0", CC "()V",                  FN_PTR(Unsafe_WriteBackPostSync0)},
1056     {CC "setMemory0",         CC "(" OBJ "JJB)V",        FN_PTR(Unsafe_SetMemory0)},
1057 
1058     {CC "shouldBeInitialized0", CC "(" CLS ")Z",         FN_PTR(Unsafe_ShouldBeInitialized0)},
1059 
1060     {CC "fullFence",          CC "()V",                  FN_PTR(Unsafe_FullFence)},
1061 };
1062 
1063 #undef CC
1064 #undef FN_PTR
1065 
1066 #undef ADR
1067 #undef LANG
1068 #undef OBJ
1069 #undef CLS
1070 #undef FLD
1071 #undef THR
1072 #undef DC_Args
1073 #undef DAC_Args
1074 
1075 #undef DECLARE_GETPUTOOP
1076 
1077 
1078 // This function is exported, used by NativeLookup.
1079 // The Unsafe_xxx functions above are called only from the interpreter.
1080 // The optimizer looks at names and signatures to recognize
1081 // individual functions.
1082 
1083 JVM_ENTRY(void, JVM_RegisterJDKInternalMiscUnsafeMethods(JNIEnv *env, jclass unsafeclass)) {
1084   ThreadToNativeFromVM ttnfv(thread);
1085 
1086   int ok = env->RegisterNatives(unsafeclass, jdk_internal_misc_Unsafe_methods, sizeof(jdk_internal_misc_Unsafe_methods)/sizeof(JNINativeMethod));
1087   guarantee(ok == 0, "register jdk.internal.misc.Unsafe natives");
1088 } JVM_END