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