1 /*
   2  * Copyright (c) 2000, 2019, 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/vmSymbols.hpp"
  31 #include "jfr/jfrEvents.hpp"
  32 #include "memory/allocation.inline.hpp"
  33 #include "memory/resourceArea.hpp"
  34 #include "logging/log.hpp"
  35 #include "logging/logStream.hpp"
  36 #include "oops/access.inline.hpp"
  37 #include "oops/fieldStreams.hpp"
  38 #include "oops/objArrayOop.inline.hpp"
  39 #include "oops/oop.inline.hpp"
  40 #include "oops/typeArrayOop.inline.hpp"
  41 #include "oops/valueArrayKlass.hpp"
  42 #include "oops/valueArrayOop.inline.hpp"
  43 #include "oops/valueKlass.inline.hpp"
  44 #include "prims/unsafe.hpp"
  45 #include "runtime/atomic.hpp"
  46 #include "runtime/fieldDescriptor.inline.hpp"
  47 #include "runtime/globals.hpp"
  48 #include "runtime/handles.inline.hpp"
  49 #include "runtime/interfaceSupport.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/thread.hpp"
  55 #include "runtime/threadSMR.hpp"
  56 #include "runtime/vm_version.hpp"
  57 #include "services/threadService.hpp"
  58 #include "utilities/align.hpp"
  59 #include "utilities/copy.hpp"
  60 #include "utilities/dtrace.hpp"
  61 #include "utilities/macros.hpp"
  62 
  63 /**
  64  * Implementation of the jdk.internal.misc.Unsafe class
  65  */
  66 
  67 
  68 #define MAX_OBJECT_SIZE \
  69   ( arrayOopDesc::header_size(T_DOUBLE) * HeapWordSize \
  70     + ((julong)max_jint * sizeof(double)) )
  71 
  72 
  73 #define UNSAFE_ENTRY(result_type, header) \
  74   JVM_ENTRY(static result_type, header)
  75 
  76 #define UNSAFE_LEAF(result_type, header) \
  77   JVM_LEAF(static result_type, header)
  78 
  79 #define UNSAFE_END JVM_END
  80 
  81 
  82 static inline void* addr_from_java(jlong addr) {
  83   // This assert fails in a variety of ways on 32-bit systems.
  84   // It is impossible to predict whether native code that converts
  85   // pointers to longs will sign-extend or zero-extend the addresses.
  86   //assert(addr == (uintptr_t)addr, "must not be odd high bits");
  87   return (void*)(uintptr_t)addr;
  88 }
  89 
  90 static inline jlong addr_to_java(void* p) {
  91   assert(p == (void*)(uintptr_t)p, "must not be odd high bits");
  92   return (uintptr_t)p;
  93 }
  94 
  95 
  96 // Note: The VM's obj_field and related accessors use byte-scaled
  97 // ("unscaled") offsets, just as the unsafe methods do.
  98 
  99 // However, the method Unsafe.fieldOffset explicitly declines to
 100 // guarantee this.  The field offset values manipulated by the Java user
 101 // through the Unsafe API are opaque cookies that just happen to be byte
 102 // offsets.  We represent this state of affairs by passing the cookies
 103 // through conversion functions when going between the VM and the Unsafe API.
 104 // The conversion functions just happen to be no-ops at present.
 105 
 106 static inline jlong field_offset_to_byte_offset(jlong field_offset) {
 107   return field_offset;
 108 }
 109 
 110 static inline jlong field_offset_from_byte_offset(jlong byte_offset) {
 111   return byte_offset;
 112 }
 113 
 114 static inline void assert_field_offset_sane(oop p, jlong field_offset) {
 115 #ifdef ASSERT
 116   jlong byte_offset = field_offset_to_byte_offset(field_offset);
 117 
 118   if (p != NULL) {
 119     assert(byte_offset >= 0 && byte_offset <= (jlong)MAX_OBJECT_SIZE, "sane offset");
 120     if (byte_offset == (jint)byte_offset) {
 121       void* ptr_plus_disp = (address)p + byte_offset;
 122       assert(p->field_addr_raw((jint)byte_offset) == ptr_plus_disp,
 123              "raw [ptr+disp] must be consistent with oop::field_addr_raw");
 124     }
 125     jlong p_size = HeapWordSize * (jlong)(p->size());
 126     assert(byte_offset < p_size, "Unsafe access: offset " INT64_FORMAT " > object's size " INT64_FORMAT, (int64_t)byte_offset, (int64_t)p_size);
 127   }
 128 #endif
 129 }
 130 
 131 static inline void* index_oop_from_field_offset_long(oop p, jlong field_offset) {
 132   assert_field_offset_sane(p, field_offset);
 133   jlong byte_offset = field_offset_to_byte_offset(field_offset);
 134 
 135   if (p != NULL) {
 136     p = Access<>::resolve(p);
 137   }
 138 
 139   if (sizeof(char*) == sizeof(jint)) {   // (this constant folds!)
 140     return (address)p + (jint) byte_offset;
 141   } else {
 142     return (address)p +        byte_offset;
 143   }
 144 }
 145 
 146 // Externally callable versions:
 147 // (Use these in compiler intrinsics which emulate unsafe primitives.)
 148 jlong Unsafe_field_offset_to_byte_offset(jlong field_offset) {
 149   return field_offset;
 150 }
 151 jlong Unsafe_field_offset_from_byte_offset(jlong byte_offset) {
 152   return byte_offset;
 153 }
 154 
 155 ///// Data read/writes on the Java heap and in native (off-heap) memory
 156 
 157 /**
 158  * Helper class to wrap memory accesses in JavaThread::doing_unsafe_access()
 159  */
 160 class GuardUnsafeAccess {
 161   JavaThread* _thread;
 162 
 163 public:
 164   GuardUnsafeAccess(JavaThread* thread) : _thread(thread) {
 165     // native/off-heap access which may raise SIGBUS if accessing
 166     // memory mapped file data in a region of the file which has
 167     // been truncated and is now invalid.
 168     _thread->set_doing_unsafe_access(true);
 169   }
 170 
 171   ~GuardUnsafeAccess() {
 172     _thread->set_doing_unsafe_access(false);
 173   }
 174 };
 175 
 176 /**
 177  * Helper class for accessing memory.
 178  *
 179  * Normalizes values and wraps accesses in
 180  * JavaThread::doing_unsafe_access() if needed.
 181  */
 182 template <typename T>
 183 class MemoryAccess : StackObj {
 184   JavaThread* _thread;
 185   oop _obj;
 186   ptrdiff_t _offset;
 187 
 188   // Resolves and returns the address of the memory access.
 189   // This raw memory access may fault, so we make sure it happens within the
 190   // guarded scope by making the access volatile at least. Since the store
 191   // of Thread::set_doing_unsafe_access() is also volatile, these accesses
 192   // can not be reordered by the compiler. Therefore, if the access triggers
 193   // a fault, we will know that Thread::doing_unsafe_access() returns true.
 194   volatile T* addr() {
 195     void* addr = index_oop_from_field_offset_long(_obj, _offset);
 196     return static_cast<volatile T*>(addr);
 197   }
 198 
 199   template <typename U>
 200   U normalize_for_write(U x) {
 201     return x;
 202   }
 203 
 204   jboolean normalize_for_write(jboolean x) {
 205     return x & 1;
 206   }
 207 
 208   template <typename U>
 209   U normalize_for_read(U x) {
 210     return x;
 211   }
 212 
 213   jboolean normalize_for_read(jboolean x) {
 214     return x != 0;
 215   }
 216 
 217 public:
 218   MemoryAccess(JavaThread* thread, jobject obj, jlong offset)
 219     : _thread(thread), _obj(JNIHandles::resolve(obj)), _offset((ptrdiff_t)offset) {
 220     assert_field_offset_sane(_obj, offset);
 221   }
 222 
 223   T get() {
 224     if (_obj == NULL) {
 225       GuardUnsafeAccess guard(_thread);
 226       T ret = RawAccess<>::load(addr());
 227       return normalize_for_read(ret);
 228     } else {
 229       T ret = HeapAccess<>::load_at(_obj, _offset);
 230       return normalize_for_read(ret);
 231     }
 232   }
 233 
 234   void put(T x) {
 235     if (_obj == NULL) {
 236       GuardUnsafeAccess guard(_thread);
 237       RawAccess<>::store(addr(), normalize_for_write(x));
 238     } else {
 239       assert(!_obj->is_value() || _obj->mark().is_larval_state(), "must be an object instance or a larval value");
 240       HeapAccess<>::store_at(_obj, _offset, normalize_for_write(x));
 241     }
 242   }
 243 
 244   T get_volatile() {
 245     if (_obj == NULL) {
 246       GuardUnsafeAccess guard(_thread);
 247       volatile T ret = RawAccess<MO_SEQ_CST>::load(addr());
 248       return normalize_for_read(ret);
 249     } else {
 250       T ret = HeapAccess<MO_SEQ_CST>::load_at(_obj, _offset);
 251       return normalize_for_read(ret);
 252     }
 253   }
 254 
 255   void put_volatile(T x) {
 256     if (_obj == NULL) {
 257       GuardUnsafeAccess guard(_thread);
 258       RawAccess<MO_SEQ_CST>::store(addr(), normalize_for_write(x));
 259     } else {
 260       HeapAccess<MO_SEQ_CST>::store_at(_obj, _offset, normalize_for_write(x));
 261     }
 262   }
 263 };
 264 
 265 #ifdef ASSERT
 266 /*
 267  * Get the field descriptor of the field of the given object at the given offset.
 268  */
 269 static bool get_field_descriptor(oop p, jlong offset, fieldDescriptor* fd) {
 270   bool found = false;
 271   Klass* k = p->klass();
 272   if (k->is_instance_klass()) {
 273     InstanceKlass* ik = InstanceKlass::cast(k);
 274     found = ik->find_field_from_offset((int)offset, false, fd);
 275     if (!found && ik->is_mirror_instance_klass()) {
 276       Klass* k2 = java_lang_Class::as_Klass(p);
 277       if (k2->is_instance_klass()) {
 278         ik = InstanceKlass::cast(k2);
 279         found = ik->find_field_from_offset((int)offset, true, fd);
 280       }
 281     }
 282   }
 283   return found;
 284 }
 285 #endif // ASSERT
 286 
 287 static void assert_and_log_unsafe_value_access(oop p, jlong offset, ValueKlass* vk) {
 288   Klass* k = p->klass();
 289 #ifdef ASSERT
 290   if (k->is_instance_klass()) {
 291     assert_field_offset_sane(p, offset);
 292     fieldDescriptor fd;
 293     bool found = get_field_descriptor(p, offset, &fd);
 294     if (found) {
 295       assert(found, "value field not found");
 296       assert(fd.is_flattened(), "field not flat");
 297     } else {
 298       if (log_is_enabled(Trace, valuetypes)) {
 299         log_trace(valuetypes)("not a field in %s at offset " SIZE_FORMAT_HEX,
 300                               p->klass()->external_name(), offset);
 301       }
 302     }
 303   } else if (k->is_valueArray_klass()) {
 304     ValueArrayKlass* vak = ValueArrayKlass::cast(k);
 305     int index = (offset - vak->array_header_in_bytes()) / vak->element_byte_size();
 306     address dest = (address)((valueArrayOop)p)->value_at_addr(index, vak->layout_helper());
 307     assert(dest == ((address)p) + offset, "invalid offset");
 308   } else {
 309     ShouldNotReachHere();
 310   }
 311 #endif // ASSERT
 312   if (log_is_enabled(Trace, valuetypes)) {
 313     if (k->is_valueArray_klass()) {
 314       ValueArrayKlass* vak = ValueArrayKlass::cast(k);
 315       int index = (offset - vak->array_header_in_bytes()) / vak->element_byte_size();
 316       address dest = (address)((valueArrayOop)p)->value_at_addr(index, vak->layout_helper());
 317       log_trace(valuetypes)("%s array type %s index %d element size %d offset " SIZE_FORMAT_HEX " at " INTPTR_FORMAT,
 318                             p->klass()->external_name(), vak->external_name(),
 319                             index, vak->element_byte_size(), offset, p2i(dest));
 320     } else {
 321       log_trace(valuetypes)("%s field type %s at offset " SIZE_FORMAT_HEX,
 322                             p->klass()->external_name(), vk->external_name(), offset);
 323     }
 324   }
 325 }
 326 
 327 // These functions allow a null base pointer with an arbitrary address.
 328 // But if the base pointer is non-null, the offset should make some sense.
 329 // That is, it should be in the range [0, MAX_OBJECT_SIZE].
 330 UNSAFE_ENTRY(jobject, Unsafe_GetReference(JNIEnv *env, jobject unsafe, jobject obj, jlong offset)) {
 331   oop p = JNIHandles::resolve(obj);
 332   assert_field_offset_sane(p, offset);
 333   oop v = HeapAccess<ON_UNKNOWN_OOP_REF>::oop_load_at(p, offset);
 334   return JNIHandles::make_local(env, v);
 335 } UNSAFE_END
 336 
 337 UNSAFE_ENTRY(void, Unsafe_PutReference(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject x_h)) {
 338   oop x = JNIHandles::resolve(x_h);
 339   oop p = JNIHandles::resolve(obj);
 340   assert_field_offset_sane(p, offset);
 341   assert(!p->is_value() || p->mark().is_larval_state(), "must be an object instance or a larval value");
 342   HeapAccess<ON_UNKNOWN_OOP_REF>::oop_store_at(p, offset, x);
 343 } UNSAFE_END
 344 
 345 UNSAFE_ENTRY(jlong, Unsafe_ValueHeaderSize(JNIEnv *env, jobject unsafe, jclass c)) {
 346   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(c));
 347   ValueKlass* vk = ValueKlass::cast(k);
 348   return vk->first_field_offset();
 349 } UNSAFE_END
 350 
 351 UNSAFE_ENTRY(jboolean, Unsafe_IsFlattenedArray(JNIEnv *env, jobject unsafe, jclass c)) {
 352   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(c));
 353   return k->is_valueArray_klass();
 354 } UNSAFE_END
 355 
 356 UNSAFE_ENTRY(jobject, Unsafe_UninitializedDefaultValue(JNIEnv *env, jobject unsafe, jclass vc)) {
 357   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(vc));
 358   ValueKlass* vk = ValueKlass::cast(k);
 359   oop v = vk->default_value();
 360   return JNIHandles::make_local(env, v);
 361 } UNSAFE_END
 362 
 363 UNSAFE_ENTRY(jobject, Unsafe_GetValue(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jclass vc)) {
 364   oop base = JNIHandles::resolve(obj);
 365   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(vc));
 366   ValueKlass* vk = ValueKlass::cast(k);
 367   assert_and_log_unsafe_value_access(base, offset, vk);
 368   Handle base_h(THREAD, base);
 369   oop v = vk->allocate_instance(CHECK_NULL); // allocate instance
 370   vk->initialize(CHECK_NULL); // If field is a default value, value class might not be initialized yet
 371   vk->value_copy_payload_to_new_oop(((address)(oopDesc*)base_h()) + offset, v);
 372   return JNIHandles::make_local(env, v);
 373 } UNSAFE_END
 374 
 375 UNSAFE_ENTRY(void, Unsafe_PutValue(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jclass vc, jobject value)) {
 376   oop base = JNIHandles::resolve(obj);
 377   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(vc));
 378   ValueKlass* vk = ValueKlass::cast(k);
 379   assert(!base->is_value() || base->mark().is_larval_state(), "must be an object instance or a larval value");
 380   assert_and_log_unsafe_value_access(base, offset, vk);
 381   oop v = JNIHandles::resolve(value);
 382   vk->value_copy_oop_to_payload(v, ((address)(oopDesc*)base) + offset);
 383 } UNSAFE_END
 384 
 385 UNSAFE_ENTRY(jobject, Unsafe_MakePrivateBuffer(JNIEnv *env, jobject unsafe, jobject value)) {
 386   oop v = JNIHandles::resolve_non_null(value);
 387   assert(v->is_value(), "must be a value instance");
 388   Handle vh(THREAD, v);
 389   ValueKlass* vk = ValueKlass::cast(v->klass());
 390   instanceOop new_value = vk->allocate_instance(CHECK_NULL);
 391   vk->value_copy_oop_to_new_oop(vh(),  new_value);
 392   markWord mark = new_value->mark();
 393   new_value->set_mark(mark.enter_larval_state());
 394   return JNIHandles::make_local(env, new_value);
 395 } UNSAFE_END
 396 
 397 UNSAFE_ENTRY(jobject, Unsafe_FinishPrivateBuffer(JNIEnv *env, jobject unsafe, jobject value)) {
 398   oop v = JNIHandles::resolve(value);
 399   assert(v->mark().is_larval_state(), "must be a larval value");
 400   markWord mark = v->mark();
 401   v->set_mark(mark.exit_larval_state());
 402   return JNIHandles::make_local(env, v);
 403 } UNSAFE_END
 404 
 405 UNSAFE_ENTRY(jobject, Unsafe_GetReferenceVolatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset)) {
 406   oop p = JNIHandles::resolve(obj);
 407   assert_field_offset_sane(p, offset);
 408   oop v = HeapAccess<MO_SEQ_CST | ON_UNKNOWN_OOP_REF>::oop_load_at(p, offset);
 409   return JNIHandles::make_local(env, v);
 410 } UNSAFE_END
 411 
 412 UNSAFE_ENTRY(void, Unsafe_PutReferenceVolatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject x_h)) {
 413   oop x = JNIHandles::resolve(x_h);
 414   oop p = JNIHandles::resolve(obj);
 415   assert_field_offset_sane(p, offset);
 416   HeapAccess<MO_SEQ_CST | ON_UNKNOWN_OOP_REF>::oop_store_at(p, offset, x);
 417 } UNSAFE_END
 418 
 419 UNSAFE_ENTRY(jobject, Unsafe_GetUncompressedObject(JNIEnv *env, jobject unsafe, jlong addr)) {
 420   oop v = *(oop*) (address) addr;
 421   return JNIHandles::make_local(env, v);
 422 } UNSAFE_END
 423 
 424 #define DEFINE_GETSETOOP(java_type, Type) \
 425  \
 426 UNSAFE_ENTRY(java_type, Unsafe_Get##Type(JNIEnv *env, jobject unsafe, jobject obj, jlong offset)) { \
 427   return MemoryAccess<java_type>(thread, obj, offset).get(); \
 428 } UNSAFE_END \
 429  \
 430 UNSAFE_ENTRY(void, Unsafe_Put##Type(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, java_type x)) { \
 431   MemoryAccess<java_type>(thread, obj, offset).put(x); \
 432 } UNSAFE_END \
 433  \
 434 // END DEFINE_GETSETOOP.
 435 
 436 DEFINE_GETSETOOP(jboolean, Boolean)
 437 DEFINE_GETSETOOP(jbyte, Byte)
 438 DEFINE_GETSETOOP(jshort, Short);
 439 DEFINE_GETSETOOP(jchar, Char);
 440 DEFINE_GETSETOOP(jint, Int);
 441 DEFINE_GETSETOOP(jlong, Long);
 442 DEFINE_GETSETOOP(jfloat, Float);
 443 DEFINE_GETSETOOP(jdouble, Double);
 444 
 445 #undef DEFINE_GETSETOOP
 446 
 447 #define DEFINE_GETSETOOP_VOLATILE(java_type, Type) \
 448  \
 449 UNSAFE_ENTRY(java_type, Unsafe_Get##Type##Volatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset)) { \
 450   return MemoryAccess<java_type>(thread, obj, offset).get_volatile(); \
 451 } UNSAFE_END \
 452  \
 453 UNSAFE_ENTRY(void, Unsafe_Put##Type##Volatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, java_type x)) { \
 454   MemoryAccess<java_type>(thread, obj, offset).put_volatile(x); \
 455 } UNSAFE_END \
 456  \
 457 // END DEFINE_GETSETOOP_VOLATILE.
 458 
 459 DEFINE_GETSETOOP_VOLATILE(jboolean, Boolean)
 460 DEFINE_GETSETOOP_VOLATILE(jbyte, Byte)
 461 DEFINE_GETSETOOP_VOLATILE(jshort, Short);
 462 DEFINE_GETSETOOP_VOLATILE(jchar, Char);
 463 DEFINE_GETSETOOP_VOLATILE(jint, Int);
 464 DEFINE_GETSETOOP_VOLATILE(jlong, Long);
 465 DEFINE_GETSETOOP_VOLATILE(jfloat, Float);
 466 DEFINE_GETSETOOP_VOLATILE(jdouble, Double);
 467 
 468 #undef DEFINE_GETSETOOP_VOLATILE
 469 
 470 UNSAFE_LEAF(void, Unsafe_LoadFence(JNIEnv *env, jobject unsafe)) {
 471   OrderAccess::acquire();
 472 } UNSAFE_END
 473 
 474 UNSAFE_LEAF(void, Unsafe_StoreFence(JNIEnv *env, jobject unsafe)) {
 475   OrderAccess::release();
 476 } UNSAFE_END
 477 
 478 UNSAFE_LEAF(void, Unsafe_FullFence(JNIEnv *env, jobject unsafe)) {
 479   OrderAccess::fence();
 480 } UNSAFE_END
 481 
 482 ////// Allocation requests
 483 
 484 UNSAFE_ENTRY(jobject, Unsafe_AllocateInstance(JNIEnv *env, jobject unsafe, jclass cls)) {
 485   ThreadToNativeFromVM ttnfv(thread);
 486   return env->AllocObject(cls);
 487 } UNSAFE_END
 488 
 489 UNSAFE_ENTRY(jlong, Unsafe_AllocateMemory0(JNIEnv *env, jobject unsafe, jlong size)) {
 490   size_t sz = (size_t)size;
 491 
 492   sz = align_up(sz, HeapWordSize);
 493   void* x = os::malloc(sz, mtOther);
 494 
 495   return addr_to_java(x);
 496 } UNSAFE_END
 497 
 498 UNSAFE_ENTRY(jlong, Unsafe_ReallocateMemory0(JNIEnv *env, jobject unsafe, jlong addr, jlong size)) {
 499   void* p = addr_from_java(addr);
 500   size_t sz = (size_t)size;
 501   sz = align_up(sz, HeapWordSize);
 502 
 503   void* x = os::realloc(p, sz, mtOther);
 504 
 505   return addr_to_java(x);
 506 } UNSAFE_END
 507 
 508 UNSAFE_ENTRY(void, Unsafe_FreeMemory0(JNIEnv *env, jobject unsafe, jlong addr)) {
 509   void* p = addr_from_java(addr);
 510 
 511   os::free(p);
 512 } UNSAFE_END
 513 
 514 UNSAFE_ENTRY(void, Unsafe_SetMemory0(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jlong size, jbyte value)) {
 515   size_t sz = (size_t)size;
 516 
 517   oop base = JNIHandles::resolve(obj);
 518   void* p = index_oop_from_field_offset_long(base, offset);
 519 
 520   Copy::fill_to_memory_atomic(p, sz, value);
 521 } UNSAFE_END
 522 
 523 UNSAFE_ENTRY(void, Unsafe_CopyMemory0(JNIEnv *env, jobject unsafe, jobject srcObj, jlong srcOffset, jobject dstObj, jlong dstOffset, jlong size)) {
 524   size_t sz = (size_t)size;
 525 
 526   oop srcp = JNIHandles::resolve(srcObj);
 527   oop dstp = JNIHandles::resolve(dstObj);
 528 
 529   void* src = index_oop_from_field_offset_long(srcp, srcOffset);
 530   void* dst = index_oop_from_field_offset_long(dstp, dstOffset);
 531   {
 532     GuardUnsafeAccess guard(thread);
 533     if (StubRoutines::unsafe_arraycopy() != NULL) {
 534       StubRoutines::UnsafeArrayCopy_stub()(src, dst, sz);
 535     } else {
 536       Copy::conjoint_memory_atomic(src, dst, sz);
 537     }
 538   }
 539 } UNSAFE_END
 540 
 541 // This function is a leaf since if the source and destination are both in native memory
 542 // the copy may potentially be very large, and we don't want to disable GC if we can avoid it.
 543 // If either source or destination (or both) are on the heap, the function will enter VM using
 544 // JVM_ENTRY_FROM_LEAF
 545 UNSAFE_LEAF(void, Unsafe_CopySwapMemory0(JNIEnv *env, jobject unsafe, jobject srcObj, jlong srcOffset, jobject dstObj, jlong dstOffset, jlong size, jlong elemSize)) {
 546   size_t sz = (size_t)size;
 547   size_t esz = (size_t)elemSize;
 548 
 549   if (srcObj == NULL && dstObj == NULL) {
 550     // Both src & dst are in native memory
 551     address src = (address)srcOffset;
 552     address dst = (address)dstOffset;
 553 
 554     {
 555       JavaThread* thread = JavaThread::thread_from_jni_environment(env);
 556       GuardUnsafeAccess guard(thread);
 557       Copy::conjoint_swap(src, dst, sz, esz);
 558     }
 559   } else {
 560     // At least one of src/dst are on heap, transition to VM to access raw pointers
 561 
 562     JVM_ENTRY_FROM_LEAF(env, void, Unsafe_CopySwapMemory0) {
 563       oop srcp = JNIHandles::resolve(srcObj);
 564       oop dstp = JNIHandles::resolve(dstObj);
 565 
 566       address src = (address)index_oop_from_field_offset_long(srcp, srcOffset);
 567       address dst = (address)index_oop_from_field_offset_long(dstp, dstOffset);
 568 
 569       {
 570         GuardUnsafeAccess guard(thread);
 571         Copy::conjoint_swap(src, dst, sz, esz);
 572       }
 573     } JVM_END
 574   }
 575 } UNSAFE_END
 576 
 577 UNSAFE_LEAF (void, Unsafe_WriteBack0(JNIEnv *env, jobject unsafe, jlong line)) {
 578   assert(VM_Version::supports_data_cache_line_flush(), "should not get here");
 579 #ifdef ASSERT
 580   if (TraceMemoryWriteback) {
 581     tty->print_cr("Unsafe: writeback 0x%p", addr_from_java(line));
 582   }
 583 #endif
 584 
 585   assert(StubRoutines::data_cache_writeback() != NULL, "sanity");
 586   (StubRoutines::DataCacheWriteback_stub())(addr_from_java(line));
 587 } UNSAFE_END
 588 
 589 static void doWriteBackSync0(bool is_pre)
 590 {
 591   assert(StubRoutines::data_cache_writeback_sync() != NULL, "sanity");
 592   (StubRoutines::DataCacheWritebackSync_stub())(is_pre);
 593 }
 594 
 595 UNSAFE_LEAF (void, Unsafe_WriteBackPreSync0(JNIEnv *env, jobject unsafe)) {
 596   assert(VM_Version::supports_data_cache_line_flush(), "should not get here");
 597 #ifdef ASSERT
 598   if (TraceMemoryWriteback) {
 599       tty->print_cr("Unsafe: writeback pre-sync");
 600   }
 601 #endif
 602 
 603   doWriteBackSync0(true);
 604 } UNSAFE_END
 605 
 606 UNSAFE_LEAF (void, Unsafe_WriteBackPostSync0(JNIEnv *env, jobject unsafe)) {
 607   assert(VM_Version::supports_data_cache_line_flush(), "should not get here");
 608 #ifdef ASSERT
 609   if (TraceMemoryWriteback) {
 610     tty->print_cr("Unsafe: writeback pre-sync");
 611   }
 612 #endif
 613 
 614   doWriteBackSync0(false);
 615 } UNSAFE_END
 616 
 617 ////// Random queries
 618 
 619 static jlong find_field_offset(jclass clazz, jstring name, TRAPS) {
 620   assert(clazz != NULL, "clazz must not be NULL");
 621   assert(name != NULL, "name must not be NULL");
 622 
 623   ResourceMark rm(THREAD);
 624   char *utf_name = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(name));
 625 
 626   InstanceKlass* k = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(clazz)));
 627 
 628   jint offset = -1;
 629   for (JavaFieldStream fs(k); !fs.done(); fs.next()) {
 630     Symbol *name = fs.name();
 631     if (name->equals(utf_name)) {
 632       offset = fs.offset();
 633       break;
 634     }
 635   }
 636   if (offset < 0) {
 637     THROW_0(vmSymbols::java_lang_InternalError());
 638   }
 639   return field_offset_from_byte_offset(offset);
 640 }
 641 
 642 static jlong find_field_offset(jobject field, int must_be_static, TRAPS) {
 643   assert(field != NULL, "field must not be NULL");
 644 
 645   oop reflected   = JNIHandles::resolve_non_null(field);
 646   oop mirror      = java_lang_reflect_Field::clazz(reflected);
 647   Klass* k        = java_lang_Class::as_Klass(mirror);
 648   int slot        = java_lang_reflect_Field::slot(reflected);
 649   int modifiers   = java_lang_reflect_Field::modifiers(reflected);
 650 
 651   if (must_be_static >= 0) {
 652     int really_is_static = ((modifiers & JVM_ACC_STATIC) != 0);
 653     if (must_be_static != really_is_static) {
 654       THROW_0(vmSymbols::java_lang_IllegalArgumentException());
 655     }
 656   }
 657 
 658   int offset = InstanceKlass::cast(k)->field_offset(slot);
 659   return field_offset_from_byte_offset(offset);
 660 }
 661 
 662 UNSAFE_ENTRY(jlong, Unsafe_ObjectFieldOffset0(JNIEnv *env, jobject unsafe, jobject field)) {
 663   return find_field_offset(field, 0, THREAD);
 664 } UNSAFE_END
 665 
 666 UNSAFE_ENTRY(jlong, Unsafe_ObjectFieldOffset1(JNIEnv *env, jobject unsafe, jclass c, jstring name)) {
 667   return find_field_offset(c, name, THREAD);
 668 } UNSAFE_END
 669 
 670 UNSAFE_ENTRY(jlong, Unsafe_StaticFieldOffset0(JNIEnv *env, jobject unsafe, jobject field)) {
 671   return find_field_offset(field, 1, THREAD);
 672 } UNSAFE_END
 673 
 674 UNSAFE_ENTRY(jobject, Unsafe_StaticFieldBase0(JNIEnv *env, jobject unsafe, jobject field)) {
 675   assert(field != NULL, "field must not be NULL");
 676 
 677   // Note:  In this VM implementation, a field address is always a short
 678   // offset from the base of a a klass metaobject.  Thus, the full dynamic
 679   // range of the return type is never used.  However, some implementations
 680   // might put the static field inside an array shared by many classes,
 681   // or even at a fixed address, in which case the address could be quite
 682   // large.  In that last case, this function would return NULL, since
 683   // the address would operate alone, without any base pointer.
 684 
 685   oop reflected   = JNIHandles::resolve_non_null(field);
 686   oop mirror      = java_lang_reflect_Field::clazz(reflected);
 687   int modifiers   = java_lang_reflect_Field::modifiers(reflected);
 688 
 689   if ((modifiers & JVM_ACC_STATIC) == 0) {
 690     THROW_0(vmSymbols::java_lang_IllegalArgumentException());
 691   }
 692 
 693   return JNIHandles::make_local(env, mirror);
 694 } UNSAFE_END
 695 
 696 UNSAFE_ENTRY(void, Unsafe_EnsureClassInitialized0(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 
 701   Klass* klass = java_lang_Class::as_Klass(mirror);
 702   if (klass != NULL && klass->should_be_initialized()) {
 703     InstanceKlass* k = InstanceKlass::cast(klass);
 704     k->initialize(CHECK);
 705   }
 706 }
 707 UNSAFE_END
 708 
 709 UNSAFE_ENTRY(jboolean, Unsafe_ShouldBeInitialized0(JNIEnv *env, jobject unsafe, jobject clazz)) {
 710   assert(clazz != NULL, "clazz must not be NULL");
 711 
 712   oop mirror = JNIHandles::resolve_non_null(clazz);
 713   Klass* klass = java_lang_Class::as_Klass(mirror);
 714 
 715   if (klass != NULL && klass->should_be_initialized()) {
 716     return true;
 717   }
 718 
 719   return false;
 720 }
 721 UNSAFE_END
 722 
 723 static void getBaseAndScale(int& base, int& scale, jclass clazz, TRAPS) {
 724   assert(clazz != NULL, "clazz must not be NULL");
 725 
 726   oop mirror = JNIHandles::resolve_non_null(clazz);
 727   Klass* k = java_lang_Class::as_Klass(mirror);
 728 
 729   if (k == NULL || !k->is_array_klass()) {
 730     THROW(vmSymbols::java_lang_InvalidClassException());
 731   } else if (k->is_objArray_klass()) {
 732     base  = arrayOopDesc::base_offset_in_bytes(T_OBJECT);
 733     scale = heapOopSize;
 734   } else if (k->is_typeArray_klass()) {
 735     TypeArrayKlass* tak = TypeArrayKlass::cast(k);
 736     base  = tak->array_header_in_bytes();
 737     assert(base == arrayOopDesc::base_offset_in_bytes(tak->element_type()), "array_header_size semantics ok");
 738     scale = (1 << tak->log2_element_size());
 739   } else if (k->is_valueArray_klass()) {
 740     ValueArrayKlass* vak = ValueArrayKlass::cast(k);
 741     ValueKlass* vklass = vak->element_klass();
 742     base = vak->array_header_in_bytes();
 743     scale = vak->element_byte_size();
 744   } else {
 745     ShouldNotReachHere();
 746   }
 747 }
 748 
 749 UNSAFE_ENTRY(jint, Unsafe_ArrayBaseOffset0(JNIEnv *env, jobject unsafe, jclass clazz)) {
 750   int base = 0, scale = 0;
 751   getBaseAndScale(base, scale, clazz, CHECK_0);
 752 
 753   return field_offset_from_byte_offset(base);
 754 } UNSAFE_END
 755 
 756 
 757 UNSAFE_ENTRY(jint, Unsafe_ArrayIndexScale0(JNIEnv *env, jobject unsafe, jclass clazz)) {
 758   int base = 0, scale = 0;
 759   getBaseAndScale(base, scale, clazz, CHECK_0);
 760 
 761   // This VM packs both fields and array elements down to the byte.
 762   // But watch out:  If this changes, so that array references for
 763   // a given primitive type (say, T_BOOLEAN) use different memory units
 764   // than fields, this method MUST return zero for such arrays.
 765   // For example, the VM used to store sub-word sized fields in full
 766   // words in the object layout, so that accessors like getByte(Object,int)
 767   // did not really do what one might expect for arrays.  Therefore,
 768   // this function used to report a zero scale factor, so that the user
 769   // would know not to attempt to access sub-word array elements.
 770   // // Code for unpacked fields:
 771   // if (scale < wordSize)  return 0;
 772 
 773   // The following allows for a pretty general fieldOffset cookie scheme,
 774   // but requires it to be linear in byte offset.
 775   return field_offset_from_byte_offset(scale) - field_offset_from_byte_offset(0);
 776 } UNSAFE_END
 777 
 778 
 779 UNSAFE_ENTRY(jlong, Unsafe_GetObjectSize0(JNIEnv* env, jobject o, jobject obj))
 780   oop p = JNIHandles::resolve(obj);
 781   return Universe::heap()->obj_size(p) * HeapWordSize;
 782 UNSAFE_END
 783 
 784 
 785 static inline void throw_new(JNIEnv *env, const char *ename) {
 786   jclass cls = env->FindClass(ename);
 787   if (env->ExceptionCheck()) {
 788     env->ExceptionClear();
 789     tty->print_cr("Unsafe: cannot throw %s because FindClass has failed", ename);
 790     return;
 791   }
 792 
 793   env->ThrowNew(cls, NULL);
 794 }
 795 
 796 static jclass Unsafe_DefineClass_impl(JNIEnv *env, jstring name, jbyteArray data, int offset, int length, jobject loader, jobject pd) {
 797   // Code lifted from JDK 1.3 ClassLoader.c
 798 
 799   jbyte *body;
 800   char *utfName = NULL;
 801   jclass result = 0;
 802   char buf[128];
 803 
 804   assert(data != NULL, "Class bytes must not be NULL");
 805   assert(length >= 0, "length must not be negative: %d", length);
 806 
 807   if (UsePerfData) {
 808     ClassLoader::unsafe_defineClassCallCounter()->inc();
 809   }
 810 
 811   body = NEW_C_HEAP_ARRAY(jbyte, length, mtInternal);
 812   if (body == NULL) {
 813     throw_new(env, "java/lang/OutOfMemoryError");
 814     return 0;
 815   }
 816 
 817   env->GetByteArrayRegion(data, offset, length, body);
 818   if (env->ExceptionOccurred()) {
 819     goto free_body;
 820   }
 821 
 822   if (name != NULL) {
 823     uint len = env->GetStringUTFLength(name);
 824     int unicode_len = env->GetStringLength(name);
 825 
 826     if (len >= sizeof(buf)) {
 827       utfName = NEW_C_HEAP_ARRAY(char, len + 1, mtInternal);
 828       if (utfName == NULL) {
 829         throw_new(env, "java/lang/OutOfMemoryError");
 830         goto free_body;
 831       }
 832     } else {
 833       utfName = buf;
 834     }
 835 
 836     env->GetStringUTFRegion(name, 0, unicode_len, utfName);
 837 
 838     for (uint i = 0; i < len; i++) {
 839       if (utfName[i] == '.')   utfName[i] = '/';
 840     }
 841   }
 842 
 843   result = JVM_DefineClass(env, utfName, loader, body, length, pd);
 844 
 845   if (utfName && utfName != buf) {
 846     FREE_C_HEAP_ARRAY(char, utfName);
 847   }
 848 
 849  free_body:
 850   FREE_C_HEAP_ARRAY(jbyte, body);
 851   return result;
 852 }
 853 
 854 
 855 UNSAFE_ENTRY(jclass, Unsafe_DefineClass0(JNIEnv *env, jobject unsafe, jstring name, jbyteArray data, int offset, int length, jobject loader, jobject pd)) {
 856   ThreadToNativeFromVM ttnfv(thread);
 857 
 858   return Unsafe_DefineClass_impl(env, name, data, offset, length, loader, pd);
 859 } UNSAFE_END
 860 
 861 
 862 // define a class but do not make it known to the class loader or system dictionary
 863 // - host_class:  supplies context for linkage, access control, protection domain, and class loader
 864 //                if host_class is itself anonymous then it is replaced with its host class.
 865 // - data:  bytes of a class file, a raw memory address (length gives the number of bytes)
 866 // - cp_patches:  where non-null entries exist, they replace corresponding CP entries in data
 867 
 868 // When you load an anonymous class U, it works as if you changed its name just before loading,
 869 // to a name that you will never use again.  Since the name is lost, no other class can directly
 870 // link to any member of U.  Just after U is loaded, the only way to use it is reflectively,
 871 // through java.lang.Class methods like Class.newInstance.
 872 
 873 // The package of an anonymous class must either match its host's class's package or be in the
 874 // unnamed package.  If it is in the unnamed package then it will be put in its host class's
 875 // package.
 876 //
 877 
 878 // Access checks for linkage sites within U continue to follow the same rules as for named classes.
 879 // An anonymous class also has special privileges to access any member of its host class.
 880 // This is the main reason why this loading operation is unsafe.  The purpose of this is to
 881 // allow language implementations to simulate "open classes"; a host class in effect gets
 882 // new code when an anonymous class is loaded alongside it.  A less convenient but more
 883 // standard way to do this is with reflection, which can also be set to ignore access
 884 // restrictions.
 885 
 886 // Access into an anonymous class is possible only through reflection.  Therefore, there
 887 // are no special access rules for calling into an anonymous class.  The relaxed access
 888 // rule for the host class is applied in the opposite direction:  A host class reflectively
 889 // access one of its anonymous classes.
 890 
 891 // If you load the same bytecodes twice, you get two different classes.  You can reload
 892 // the same bytecodes with or without varying CP patches.
 893 
 894 // By using the CP patching array, you can have a new anonymous class U2 refer to an older one U1.
 895 // The bytecodes for U2 should refer to U1 by a symbolic name (doesn't matter what the name is).
 896 // The CONSTANT_Class entry for that name can be patched to refer directly to U1.
 897 
 898 // This allows, for example, U2 to use U1 as a superclass or super-interface, or as
 899 // an outer class (so that U2 is an anonymous inner class of anonymous U1).
 900 // It is not possible for a named class, or an older anonymous class, to refer by
 901 // name (via its CP) to a newer anonymous class.
 902 
 903 // CP patching may also be used to modify (i.e., hack) the names of methods, classes,
 904 // or type descriptors used in the loaded anonymous class.
 905 
 906 // Finally, CP patching may be used to introduce "live" objects into the constant pool,
 907 // instead of "dead" strings.  A compiled statement like println((Object)"hello") can
 908 // be changed to println(greeting), where greeting is an arbitrary object created before
 909 // the anonymous class is loaded.  This is useful in dynamic languages, in which
 910 // various kinds of metaobjects must be introduced as constants into bytecode.
 911 // Note the cast (Object), which tells the verifier to expect an arbitrary object,
 912 // not just a literal string.  For such ldc instructions, the verifier uses the
 913 // type Object instead of String, if the loaded constant is not in fact a String.
 914 
 915 static InstanceKlass*
 916 Unsafe_DefineAnonymousClass_impl(JNIEnv *env,
 917                                  jclass host_class, jbyteArray data, jobjectArray cp_patches_jh,
 918                                  u1** temp_alloc,
 919                                  TRAPS) {
 920   assert(host_class != NULL, "host_class must not be NULL");
 921   assert(data != NULL, "data must not be NULL");
 922 
 923   if (UsePerfData) {
 924     ClassLoader::unsafe_defineClassCallCounter()->inc();
 925   }
 926 
 927   jint length = typeArrayOop(JNIHandles::resolve_non_null(data))->length();
 928   assert(length >= 0, "class_bytes_length must not be negative: %d", length);
 929 
 930   int class_bytes_length = (int) length;
 931 
 932   u1* class_bytes = NEW_C_HEAP_ARRAY(u1, length, mtInternal);
 933   if (class_bytes == NULL) {
 934     THROW_0(vmSymbols::java_lang_OutOfMemoryError());
 935   }
 936 
 937   // caller responsible to free it:
 938   *temp_alloc = class_bytes;
 939 
 940   ArrayAccess<>::arraycopy_to_native(arrayOop(JNIHandles::resolve_non_null(data)), typeArrayOopDesc::element_offset<jbyte>(0),
 941                                      reinterpret_cast<jbyte*>(class_bytes), length);
 942 
 943   objArrayHandle cp_patches_h;
 944   if (cp_patches_jh != NULL) {
 945     oop p = JNIHandles::resolve_non_null(cp_patches_jh);
 946     assert(p->is_objArray(), "cp_patches must be an object[]");
 947     cp_patches_h = objArrayHandle(THREAD, (objArrayOop)p);
 948   }
 949 
 950   const Klass* host_klass = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(host_class));
 951 
 952   // Make sure it's the real host class, not another anonymous class.
 953   while (host_klass != NULL && host_klass->is_instance_klass() &&
 954          InstanceKlass::cast(host_klass)->is_unsafe_anonymous()) {
 955     host_klass = InstanceKlass::cast(host_klass)->unsafe_anonymous_host();
 956   }
 957 
 958   // Primitive types have NULL Klass* fields in their java.lang.Class instances.
 959   if (host_klass == NULL) {
 960     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Host class is null");
 961   }
 962 
 963   assert(host_klass->is_instance_klass(), "Host class must be an instance class");
 964 
 965   const char* host_source = host_klass->external_name();
 966   Handle      host_loader(THREAD, host_klass->class_loader());
 967   Handle      host_domain(THREAD, host_klass->protection_domain());
 968 
 969   GrowableArray<Handle>* cp_patches = NULL;
 970 
 971   if (cp_patches_h.not_null()) {
 972     int alen = cp_patches_h->length();
 973 
 974     for (int i = alen-1; i >= 0; i--) {
 975       oop p = cp_patches_h->obj_at(i);
 976       if (p != NULL) {
 977         Handle patch(THREAD, p);
 978 
 979         if (cp_patches == NULL) {
 980           cp_patches = new GrowableArray<Handle>(i+1, i+1, Handle());
 981         }
 982 
 983         cp_patches->at_put(i, patch);
 984       }
 985     }
 986   }
 987 
 988   ClassFileStream st(class_bytes, class_bytes_length, host_source, ClassFileStream::verify);
 989 
 990   Symbol* no_class_name = NULL;
 991   Klass* anonk = SystemDictionary::parse_stream(no_class_name,
 992                                                 host_loader,
 993                                                 host_domain,
 994                                                 &st,
 995                                                 InstanceKlass::cast(host_klass),
 996                                                 cp_patches,
 997                                                 CHECK_NULL);
 998   if (anonk == NULL) {
 999     return NULL;
1000   }
1001 
1002   return InstanceKlass::cast(anonk);
1003 }
1004 
1005 UNSAFE_ENTRY(jclass, Unsafe_DefineAnonymousClass0(JNIEnv *env, jobject unsafe, jclass host_class, jbyteArray data, jobjectArray cp_patches_jh)) {
1006   ResourceMark rm(THREAD);
1007 
1008   jobject res_jh = NULL;
1009   u1* temp_alloc = NULL;
1010 
1011   InstanceKlass* anon_klass = Unsafe_DefineAnonymousClass_impl(env, host_class, data, cp_patches_jh, &temp_alloc, THREAD);
1012   if (anon_klass != NULL) {
1013     res_jh = JNIHandles::make_local(env, anon_klass->java_mirror());
1014   }
1015 
1016   // try/finally clause:
1017   FREE_C_HEAP_ARRAY(u1, temp_alloc);
1018 
1019   // The anonymous class loader data has been artificially been kept alive to
1020   // this point.   The mirror and any instances of this class have to keep
1021   // it alive afterwards.
1022   if (anon_klass != NULL) {
1023     anon_klass->class_loader_data()->dec_keep_alive();
1024   }
1025 
1026   // let caller initialize it as needed...
1027 
1028   return (jclass) res_jh;
1029 } UNSAFE_END
1030 
1031 
1032 
1033 UNSAFE_ENTRY(void, Unsafe_ThrowException(JNIEnv *env, jobject unsafe, jthrowable thr)) {
1034   ThreadToNativeFromVM ttnfv(thread);
1035   env->Throw(thr);
1036 } UNSAFE_END
1037 
1038 // JSR166 ------------------------------------------------------------------
1039 
1040 UNSAFE_ENTRY(jobject, Unsafe_CompareAndExchangeReference(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject e_h, jobject x_h)) {
1041   oop x = JNIHandles::resolve(x_h);
1042   oop e = JNIHandles::resolve(e_h);
1043   oop p = JNIHandles::resolve(obj);
1044   assert_field_offset_sane(p, offset);
1045   oop res = HeapAccess<ON_UNKNOWN_OOP_REF>::oop_atomic_cmpxchg_at(x, p, (ptrdiff_t)offset, e);
1046   return JNIHandles::make_local(env, res);
1047 } UNSAFE_END
1048 
1049 UNSAFE_ENTRY(jint, Unsafe_CompareAndExchangeInt(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jint e, jint x)) {
1050   oop p = JNIHandles::resolve(obj);
1051   if (p == NULL) {
1052     volatile jint* addr = (volatile jint*)index_oop_from_field_offset_long(p, offset);
1053     return RawAccess<>::atomic_cmpxchg(x, addr, e);
1054   } else {
1055     assert_field_offset_sane(p, offset);
1056     return HeapAccess<>::atomic_cmpxchg_at(x, p, (ptrdiff_t)offset, e);
1057   }
1058 } UNSAFE_END
1059 
1060 UNSAFE_ENTRY(jlong, Unsafe_CompareAndExchangeLong(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jlong e, jlong x)) {
1061   oop p = JNIHandles::resolve(obj);
1062   if (p == NULL) {
1063     volatile jlong* addr = (volatile jlong*)index_oop_from_field_offset_long(p, offset);
1064     return RawAccess<>::atomic_cmpxchg(x, addr, e);
1065   } else {
1066     assert_field_offset_sane(p, offset);
1067     return HeapAccess<>::atomic_cmpxchg_at(x, p, (ptrdiff_t)offset, e);
1068   }
1069 } UNSAFE_END
1070 
1071 UNSAFE_ENTRY(jboolean, Unsafe_CompareAndSetReference(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject e_h, jobject x_h)) {
1072   oop x = JNIHandles::resolve(x_h);
1073   oop e = JNIHandles::resolve(e_h);
1074   oop p = JNIHandles::resolve(obj);
1075   assert_field_offset_sane(p, offset);
1076   oop ret = HeapAccess<ON_UNKNOWN_OOP_REF>::oop_atomic_cmpxchg_at(x, p, (ptrdiff_t)offset, e);
1077   return ret == e;
1078 } UNSAFE_END
1079 
1080 UNSAFE_ENTRY(jboolean, Unsafe_CompareAndSetInt(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jint e, jint x)) {
1081   oop p = JNIHandles::resolve(obj);
1082   if (p == NULL) {
1083     volatile jint* addr = (volatile jint*)index_oop_from_field_offset_long(p, offset);
1084     return RawAccess<>::atomic_cmpxchg(x, addr, e) == e;
1085   } else {
1086     assert_field_offset_sane(p, offset);
1087     return HeapAccess<>::atomic_cmpxchg_at(x, p, (ptrdiff_t)offset, e) == e;
1088   }
1089 } UNSAFE_END
1090 
1091 UNSAFE_ENTRY(jboolean, Unsafe_CompareAndSetLong(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jlong e, jlong x)) {
1092   oop p = JNIHandles::resolve(obj);
1093   if (p == NULL) {
1094     volatile jlong* addr = (volatile jlong*)index_oop_from_field_offset_long(p, offset);
1095     return RawAccess<>::atomic_cmpxchg(x, addr, e) == e;
1096   } else {
1097     assert_field_offset_sane(p, offset);
1098     return HeapAccess<>::atomic_cmpxchg_at(x, p, (ptrdiff_t)offset, e) == e;
1099   }
1100 } UNSAFE_END
1101 
1102 static void post_thread_park_event(EventThreadPark* event, const oop obj, jlong timeout_nanos, jlong until_epoch_millis) {
1103   assert(event != NULL, "invariant");
1104   assert(event->should_commit(), "invariant");
1105   event->set_parkedClass((obj != NULL) ? obj->klass() : NULL);
1106   event->set_timeout(timeout_nanos);
1107   event->set_until(until_epoch_millis);
1108   event->set_address((obj != NULL) ? (u8)cast_from_oop<uintptr_t>(obj) : 0);
1109   event->commit();
1110 }
1111 
1112 UNSAFE_ENTRY(void, Unsafe_Park(JNIEnv *env, jobject unsafe, jboolean isAbsolute, jlong time)) {
1113   HOTSPOT_THREAD_PARK_BEGIN((uintptr_t) thread->parker(), (int) isAbsolute, time);
1114   EventThreadPark event;
1115 
1116   JavaThreadParkedState jtps(thread, time != 0);
1117   thread->parker()->park(isAbsolute != 0, time);
1118   if (event.should_commit()) {
1119     const oop obj = thread->current_park_blocker();
1120     if (time == 0) {
1121       post_thread_park_event(&event, obj, min_jlong, min_jlong);
1122     } else {
1123       if (isAbsolute != 0) {
1124         post_thread_park_event(&event, obj, min_jlong, time);
1125       } else {
1126         post_thread_park_event(&event, obj, time, min_jlong);
1127       }
1128     }
1129   }
1130   HOTSPOT_THREAD_PARK_END((uintptr_t) thread->parker());
1131 } UNSAFE_END
1132 
1133 UNSAFE_ENTRY(void, Unsafe_Unpark(JNIEnv *env, jobject unsafe, jobject jthread)) {
1134   Parker* p = NULL;
1135 
1136   if (jthread != NULL) {
1137     ThreadsListHandle tlh;
1138     JavaThread* thr = NULL;
1139     oop java_thread = NULL;
1140     (void) tlh.cv_internal_thread_to_JavaThread(jthread, &thr, &java_thread);
1141     if (java_thread != NULL) {
1142       // This is a valid oop.
1143       if (thr != NULL) {
1144         // The JavaThread is alive.
1145         p = thr->parker();
1146       }
1147     }
1148   } // ThreadsListHandle is destroyed here.
1149 
1150   // 'p' points to type-stable-memory if non-NULL. If the target
1151   // thread terminates before we get here the new user of this
1152   // Parker will get a 'spurious' unpark - which is perfectly valid.
1153   if (p != NULL) {
1154     HOTSPOT_THREAD_UNPARK((uintptr_t) p);
1155     p->unpark();
1156   }
1157 } UNSAFE_END
1158 
1159 UNSAFE_ENTRY(jint, Unsafe_GetLoadAverage0(JNIEnv *env, jobject unsafe, jdoubleArray loadavg, jint nelem)) {
1160   const int max_nelem = 3;
1161   double la[max_nelem];
1162   jint ret;
1163 
1164   typeArrayOop a = typeArrayOop(JNIHandles::resolve_non_null(loadavg));
1165   assert(a->is_typeArray(), "must be type array");
1166 
1167   ret = os::loadavg(la, nelem);
1168   if (ret == -1) {
1169     return -1;
1170   }
1171 
1172   // if successful, ret is the number of samples actually retrieved.
1173   assert(ret >= 0 && ret <= max_nelem, "Unexpected loadavg return value");
1174   switch(ret) {
1175     case 3: a->double_at_put(2, (jdouble)la[2]); // fall through
1176     case 2: a->double_at_put(1, (jdouble)la[1]); // fall through
1177     case 1: a->double_at_put(0, (jdouble)la[0]); break;
1178   }
1179 
1180   return ret;
1181 } UNSAFE_END
1182 
1183 
1184 /// JVM_RegisterUnsafeMethods
1185 
1186 #define ADR "J"
1187 
1188 #define LANG "Ljava/lang/"
1189 
1190 #define OBJ LANG "Object;"
1191 #define CLS LANG "Class;"
1192 #define FLD LANG "reflect/Field;"
1193 #define THR LANG "Throwable;"
1194 
1195 #define DC_Args  LANG "String;[BII" LANG "ClassLoader;" "Ljava/security/ProtectionDomain;"
1196 #define DAC_Args CLS "[B[" OBJ
1197 
1198 #define CC (char*)  /*cast a literal from (const char*)*/
1199 #define FN_PTR(f) CAST_FROM_FN_PTR(void*, &f)
1200 
1201 #define DECLARE_GETPUTOOP(Type, Desc) \
1202     {CC "get"  #Type,      CC "(" OBJ "J)" #Desc,                 FN_PTR(Unsafe_Get##Type)}, \
1203     {CC "put"  #Type,      CC "(" OBJ "J" #Desc ")V",             FN_PTR(Unsafe_Put##Type)}, \
1204     {CC "get"  #Type "Volatile",      CC "(" OBJ "J)" #Desc,      FN_PTR(Unsafe_Get##Type##Volatile)}, \
1205     {CC "put"  #Type "Volatile",      CC "(" OBJ "J" #Desc ")V",  FN_PTR(Unsafe_Put##Type##Volatile)}
1206 
1207 
1208 static JNINativeMethod jdk_internal_misc_Unsafe_methods[] = {
1209     {CC "getReference",         CC "(" OBJ "J)" OBJ "",   FN_PTR(Unsafe_GetReference)},
1210     {CC "putReference",         CC "(" OBJ "J" OBJ ")V",  FN_PTR(Unsafe_PutReference)},
1211     {CC "getReferenceVolatile", CC "(" OBJ "J)" OBJ,      FN_PTR(Unsafe_GetReferenceVolatile)},
1212     {CC "putReferenceVolatile", CC "(" OBJ "J" OBJ ")V",  FN_PTR(Unsafe_PutReferenceVolatile)},
1213 
1214     {CC "isFlattenedArray", CC "(" CLS ")Z",                     FN_PTR(Unsafe_IsFlattenedArray)},
1215     {CC "getValue",         CC "(" OBJ "J" CLS ")" OBJ,          FN_PTR(Unsafe_GetValue)},
1216     {CC "putValue",         CC "(" OBJ "J" CLS OBJ ")V",         FN_PTR(Unsafe_PutValue)},
1217     {CC "uninitializedDefaultValue", CC "(" CLS ")" OBJ,         FN_PTR(Unsafe_UninitializedDefaultValue)},
1218     {CC "makePrivateBuffer",     CC "(" OBJ ")" OBJ,             FN_PTR(Unsafe_MakePrivateBuffer)},
1219     {CC "finishPrivateBuffer",   CC "(" OBJ ")" OBJ,             FN_PTR(Unsafe_FinishPrivateBuffer)},
1220     {CC "valueHeaderSize",       CC "(" CLS ")J",                FN_PTR(Unsafe_ValueHeaderSize)},
1221 
1222     {CC "getUncompressedObject", CC "(" ADR ")" OBJ,  FN_PTR(Unsafe_GetUncompressedObject)},
1223 
1224     DECLARE_GETPUTOOP(Boolean, Z),
1225     DECLARE_GETPUTOOP(Byte, B),
1226     DECLARE_GETPUTOOP(Short, S),
1227     DECLARE_GETPUTOOP(Char, C),
1228     DECLARE_GETPUTOOP(Int, I),
1229     DECLARE_GETPUTOOP(Long, J),
1230     DECLARE_GETPUTOOP(Float, F),
1231     DECLARE_GETPUTOOP(Double, D),
1232 
1233     {CC "allocateMemory0",    CC "(J)" ADR,              FN_PTR(Unsafe_AllocateMemory0)},
1234     {CC "reallocateMemory0",  CC "(" ADR "J)" ADR,       FN_PTR(Unsafe_ReallocateMemory0)},
1235     {CC "freeMemory0",        CC "(" ADR ")V",           FN_PTR(Unsafe_FreeMemory0)},
1236 
1237     {CC "objectFieldOffset0", CC "(" FLD ")J",           FN_PTR(Unsafe_ObjectFieldOffset0)},
1238     {CC "objectFieldOffset1", CC "(" CLS LANG "String;)J", FN_PTR(Unsafe_ObjectFieldOffset1)},
1239     {CC "staticFieldOffset0", CC "(" FLD ")J",           FN_PTR(Unsafe_StaticFieldOffset0)},
1240     {CC "staticFieldBase0",   CC "(" FLD ")" OBJ,        FN_PTR(Unsafe_StaticFieldBase0)},
1241     {CC "ensureClassInitialized0", CC "(" CLS ")V",      FN_PTR(Unsafe_EnsureClassInitialized0)},
1242     {CC "arrayBaseOffset0",   CC "(" CLS ")I",           FN_PTR(Unsafe_ArrayBaseOffset0)},
1243     {CC "arrayIndexScale0",   CC "(" CLS ")I",           FN_PTR(Unsafe_ArrayIndexScale0)},
1244     {CC "getObjectSize0",     CC "(Ljava/lang/Object;)J", FN_PTR(Unsafe_GetObjectSize0)},
1245 
1246     {CC "defineClass0",       CC "(" DC_Args ")" CLS,    FN_PTR(Unsafe_DefineClass0)},
1247     {CC "allocateInstance",   CC "(" CLS ")" OBJ,        FN_PTR(Unsafe_AllocateInstance)},
1248     {CC "throwException",     CC "(" THR ")V",           FN_PTR(Unsafe_ThrowException)},
1249     {CC "compareAndSetReference",CC "(" OBJ "J" OBJ "" OBJ ")Z", FN_PTR(Unsafe_CompareAndSetReference)},
1250     {CC "compareAndSetInt",   CC "(" OBJ "J""I""I"")Z",  FN_PTR(Unsafe_CompareAndSetInt)},
1251     {CC "compareAndSetLong",  CC "(" OBJ "J""J""J"")Z",  FN_PTR(Unsafe_CompareAndSetLong)},
1252     {CC "compareAndExchangeReference", CC "(" OBJ "J" OBJ "" OBJ ")" OBJ, FN_PTR(Unsafe_CompareAndExchangeReference)},
1253     {CC "compareAndExchangeInt",  CC "(" OBJ "J""I""I"")I", FN_PTR(Unsafe_CompareAndExchangeInt)},
1254     {CC "compareAndExchangeLong", CC "(" OBJ "J""J""J"")J", FN_PTR(Unsafe_CompareAndExchangeLong)},
1255 
1256     {CC "park",               CC "(ZJ)V",                FN_PTR(Unsafe_Park)},
1257     {CC "unpark",             CC "(" OBJ ")V",           FN_PTR(Unsafe_Unpark)},
1258 
1259     {CC "getLoadAverage0",    CC "([DI)I",               FN_PTR(Unsafe_GetLoadAverage0)},
1260 
1261     {CC "copyMemory0",        CC "(" OBJ "J" OBJ "JJ)V", FN_PTR(Unsafe_CopyMemory0)},
1262     {CC "copySwapMemory0",    CC "(" OBJ "J" OBJ "JJJ)V", FN_PTR(Unsafe_CopySwapMemory0)},
1263     {CC "writeback0",         CC "(" "J" ")V",           FN_PTR(Unsafe_WriteBack0)},
1264     {CC "writebackPreSync0",  CC "()V",                  FN_PTR(Unsafe_WriteBackPreSync0)},
1265     {CC "writebackPostSync0", CC "()V",                  FN_PTR(Unsafe_WriteBackPostSync0)},
1266     {CC "setMemory0",         CC "(" OBJ "JJB)V",        FN_PTR(Unsafe_SetMemory0)},
1267 
1268     {CC "defineAnonymousClass0", CC "(" DAC_Args ")" CLS, FN_PTR(Unsafe_DefineAnonymousClass0)},
1269 
1270     {CC "shouldBeInitialized0", CC "(" CLS ")Z",         FN_PTR(Unsafe_ShouldBeInitialized0)},
1271 
1272     {CC "loadFence",          CC "()V",                  FN_PTR(Unsafe_LoadFence)},
1273     {CC "storeFence",         CC "()V",                  FN_PTR(Unsafe_StoreFence)},
1274     {CC "fullFence",          CC "()V",                  FN_PTR(Unsafe_FullFence)},
1275 };
1276 
1277 #undef CC
1278 #undef FN_PTR
1279 
1280 #undef ADR
1281 #undef LANG
1282 #undef OBJ
1283 #undef CLS
1284 #undef FLD
1285 #undef THR
1286 #undef DC_Args
1287 #undef DAC_Args
1288 
1289 #undef DECLARE_GETPUTOOP
1290 
1291 
1292 // This function is exported, used by NativeLookup.
1293 // The Unsafe_xxx functions above are called only from the interpreter.
1294 // The optimizer looks at names and signatures to recognize
1295 // individual functions.
1296 
1297 JVM_ENTRY(void, JVM_RegisterJDKInternalMiscUnsafeMethods(JNIEnv *env, jclass unsafeclass)) {
1298   ThreadToNativeFromVM ttnfv(thread);
1299 
1300   int ok = env->RegisterNatives(unsafeclass, jdk_internal_misc_Unsafe_methods, sizeof(jdk_internal_misc_Unsafe_methods)/sizeof(JNINativeMethod));
1301   guarantee(ok == 0, "register jdk.internal.misc.Unsafe natives");
1302 } JVM_END