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