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/vmSymbols.hpp"
  27 #include "utilities/macros.hpp"
  28 #if INCLUDE_ALL_GCS
  29 #include "gc_implementation/g1/g1SATBCardTableModRefBS.hpp"
  30 #endif // INCLUDE_ALL_GCS
  31 #include "jfr/jfrEvents.hpp"
  32 #include "memory/allocation.inline.hpp"
  33 #include "prims/jni.h"
  34 #include "prims/jvm.h"
  35 #include "runtime/globals.hpp"
  36 #include "runtime/interfaceSupport.hpp"
  37 #include "runtime/prefetch.inline.hpp"
  38 #include "runtime/orderAccess.inline.hpp"
  39 #include "runtime/reflection.hpp"
  40 #include "runtime/synchronizer.hpp"
  41 #include "services/threadService.hpp"
  42 #include "utilities/copy.hpp"
  43 #include "utilities/dtrace.hpp"
  44 
  45 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
  46 
  47 /*
  48  *      Implementation of class sun.misc.Unsafe
  49  */
  50 
  51 #ifndef USDT2
  52 HS_DTRACE_PROBE_DECL3(hotspot, thread__park__begin, uintptr_t, int, long long);
  53 HS_DTRACE_PROBE_DECL1(hotspot, thread__park__end, uintptr_t);
  54 HS_DTRACE_PROBE_DECL1(hotspot, thread__unpark, uintptr_t);
  55 #endif /* !USDT2 */
  56 
  57 #define MAX_OBJECT_SIZE \
  58   ( arrayOopDesc::header_size(T_DOUBLE) * HeapWordSize \
  59     + ((julong)max_jint * sizeof(double)) )
  60 
  61 
  62 #define UNSAFE_ENTRY(result_type, header) \
  63   JVM_ENTRY(result_type, header)
  64 
  65 // Can't use UNSAFE_LEAF because it has the signature of a straight
  66 // call into the runtime (just like JVM_LEAF, funny that) but it's
  67 // called like a Java Native and thus the wrapper built for it passes
  68 // arguments like a JNI call.  It expects those arguments to be popped
  69 // from the stack on Intel like all good JNI args are, and adjusts the
  70 // stack according.  Since the JVM_LEAF call expects no extra
  71 // arguments the stack isn't popped in the C code, is pushed by the
  72 // wrapper and we get sick.
  73 //#define UNSAFE_LEAF(result_type, header) \
  74 //  JVM_LEAF(result_type, header)
  75 
  76 #define UNSAFE_END JVM_END
  77 
  78 #define UnsafeWrapper(arg) /*nothing, for the present*/
  79 
  80 
  81 inline void* addr_from_java(jlong addr) {
  82   // This assert fails in a variety of ways on 32-bit systems.
  83   // It is impossible to predict whether native code that converts
  84   // pointers to longs will sign-extend or zero-extend the addresses.
  85   //assert(addr == (uintptr_t)addr, "must not be odd high bits");
  86   return (void*)(uintptr_t)addr;
  87 }
  88 
  89 inline jlong addr_to_java(void* p) {
  90   assert(p == (void*)(uintptr_t)p, "must not be odd high bits");
  91   return (uintptr_t)p;
  92 }
  93 
  94 
  95 // Note: The VM's obj_field and related accessors use byte-scaled
  96 // ("unscaled") offsets, just as the unsafe methods do.
  97 
  98 // However, the method Unsafe.fieldOffset explicitly declines to
  99 // guarantee this.  The field offset values manipulated by the Java user
 100 // through the Unsafe API are opaque cookies that just happen to be byte
 101 // offsets.  We represent this state of affairs by passing the cookies
 102 // through conversion functions when going between the VM and the Unsafe API.
 103 // The conversion functions just happen to be no-ops at present.
 104 
 105 inline jlong field_offset_to_byte_offset(jlong field_offset) {
 106   return field_offset;
 107 }
 108 
 109 inline jlong field_offset_from_byte_offset(jlong byte_offset) {
 110   return byte_offset;
 111 }
 112 
 113 inline jint invocation_key_from_method_slot(jint slot) {
 114   return slot;
 115 }
 116 
 117 inline jint invocation_key_to_method_slot(jint key) {
 118   return key;
 119 }
 120 
 121 inline void* index_oop_from_field_offset_long(oop p, jlong field_offset) {
 122   jlong byte_offset = field_offset_to_byte_offset(field_offset);
 123 #ifdef ASSERT
 124   if (p != NULL) {
 125     assert(byte_offset >= 0 && byte_offset <= (jlong)MAX_OBJECT_SIZE, "sane offset");
 126     if (byte_offset == (jint)byte_offset) {
 127       void* ptr_plus_disp = (address)p + byte_offset;
 128       assert((void*)p->obj_field_addr<oop>((jint)byte_offset) == ptr_plus_disp,
 129              "raw [ptr+disp] must be consistent with oop::field_base");
 130     }
 131     jlong p_size = HeapWordSize * (jlong)(p->size());
 132     assert(byte_offset < p_size, err_msg("Unsafe access: offset " INT64_FORMAT " > object's size " INT64_FORMAT, byte_offset, p_size));
 133   }
 134 #endif
 135   if (sizeof(char*) == sizeof(jint))    // (this constant folds!)
 136     return (address)p + (jint) byte_offset;
 137   else
 138     return (address)p +        byte_offset;
 139 }
 140 
 141 // Externally callable versions:
 142 // (Use these in compiler intrinsics which emulate unsafe primitives.)
 143 jlong Unsafe_field_offset_to_byte_offset(jlong field_offset) {
 144   return field_offset;
 145 }
 146 jlong Unsafe_field_offset_from_byte_offset(jlong byte_offset) {
 147   return byte_offset;
 148 }
 149 jint Unsafe_invocation_key_from_method_slot(jint slot) {
 150   return invocation_key_from_method_slot(slot);
 151 }
 152 jint Unsafe_invocation_key_to_method_slot(jint key) {
 153   return invocation_key_to_method_slot(key);
 154 }
 155 
 156 
 157 ///// Data in the Java heap.
 158 
 159 #define truncate_jboolean(x) ((x) & 1)
 160 #define truncate_jbyte(x) (x)
 161 #define truncate_jshort(x) (x)
 162 #define truncate_jchar(x) (x)
 163 #define truncate_jint(x) (x)
 164 #define truncate_jlong(x) (x)
 165 #define truncate_jfloat(x) (x)
 166 #define truncate_jdouble(x) (x)
 167 
 168 #define GET_FIELD(obj, offset, type_name, v) \
 169   oop p = JNIHandles::resolve(obj); \
 170   type_name v = *(type_name*)index_oop_from_field_offset_long(p, offset)
 171 
 172 #define SET_FIELD(obj, offset, type_name, x) \
 173   oop p = JNIHandles::resolve(obj); \
 174   *(type_name*)index_oop_from_field_offset_long(p, offset) = truncate_##type_name(x)
 175 
 176 #define GET_FIELD_VOLATILE(obj, offset, type_name, v) \
 177   oop p = JNIHandles::resolve(obj); \
 178   if (support_IRIW_for_not_multiple_copy_atomic_cpu) { \
 179     OrderAccess::fence(); \
 180   } \
 181   volatile type_name v = OrderAccess::load_acquire((volatile type_name*)index_oop_from_field_offset_long(p, offset));
 182 
 183 #define SET_FIELD_VOLATILE(obj, offset, type_name, x) \
 184   oop p = JNIHandles::resolve(obj); \
 185   OrderAccess::release_store_fence((volatile type_name*)index_oop_from_field_offset_long(p, offset), truncate_##type_name(x));
 186 
 187 // Macros for oops that check UseCompressedOops
 188 
 189 #define GET_OOP_FIELD(obj, offset, v) \
 190   oop p = JNIHandles::resolve(obj);   \
 191   oop v;                              \
 192   if (UseCompressedOops) {            \
 193     narrowOop n = *(narrowOop*)index_oop_from_field_offset_long(p, offset); \
 194     v = oopDesc::decode_heap_oop(n);                                \
 195   } else {                            \
 196     v = *(oop*)index_oop_from_field_offset_long(p, offset);                 \
 197   }
 198 
 199 
 200 // Get/SetObject must be special-cased, since it works with handles.
 201 
 202 // We could be accessing the referent field in a reference
 203 // object. If G1 is enabled then we need to register non-null
 204 // referent with the SATB barrier.
 205 
 206 #if INCLUDE_ALL_GCS
 207 static bool is_java_lang_ref_Reference_access(oop o, jlong offset) {
 208   if (offset == java_lang_ref_Reference::referent_offset && o != NULL) {
 209     Klass* k = o->klass();
 210     if (InstanceKlass::cast(k)->reference_type() != REF_NONE) {
 211       assert(InstanceKlass::cast(k)->is_subclass_of(SystemDictionary::Reference_klass()), "sanity");
 212       return true;
 213     }
 214   }
 215  return false;
 216 }
 217 #endif
 218 
 219 static void ensure_satb_referent_alive(oop o, jlong offset, oop v) {
 220 #if INCLUDE_ALL_GCS
 221   if (UseG1GC && v != NULL && is_java_lang_ref_Reference_access(o, offset)) {
 222     G1SATBCardTableModRefBS::enqueue(v);
 223   }
 224 #endif
 225 }
 226 
 227 // The xxx140 variants for backward compatibility do not allow a full-width offset.
 228 UNSAFE_ENTRY(jobject, Unsafe_GetObject140(JNIEnv *env, jobject unsafe, jobject obj, jint offset))
 229   UnsafeWrapper("Unsafe_GetObject");
 230   if (obj == NULL)  THROW_0(vmSymbols::java_lang_NullPointerException());
 231   GET_OOP_FIELD(obj, offset, v)
 232 
 233   ensure_satb_referent_alive(p, offset, v);
 234 
 235   return JNIHandles::make_local(env, v);
 236 UNSAFE_END
 237 
 238 UNSAFE_ENTRY(void, Unsafe_SetObject140(JNIEnv *env, jobject unsafe, jobject obj, jint offset, jobject x_h))
 239   UnsafeWrapper("Unsafe_SetObject");
 240   if (obj == NULL)  THROW(vmSymbols::java_lang_NullPointerException());
 241   oop x = JNIHandles::resolve(x_h);
 242   //SET_FIELD(obj, offset, oop, x);
 243   oop p = JNIHandles::resolve(obj);
 244   if (UseCompressedOops) {
 245     if (x != NULL) {
 246       // If there is a heap base pointer, we are obliged to emit a store barrier.
 247       oop_store((narrowOop*)index_oop_from_field_offset_long(p, offset), x);
 248     } else {
 249       narrowOop n = oopDesc::encode_heap_oop_not_null(x);
 250       *(narrowOop*)index_oop_from_field_offset_long(p, offset) = n;
 251     }
 252   } else {
 253     if (x != NULL) {
 254       // If there is a heap base pointer, we are obliged to emit a store barrier.
 255       oop_store((oop*)index_oop_from_field_offset_long(p, offset), x);
 256     } else {
 257       *(oop*)index_oop_from_field_offset_long(p, offset) = x;
 258     }
 259   }
 260 UNSAFE_END
 261 
 262 // The normal variants allow a null base pointer with an arbitrary address.
 263 // But if the base pointer is non-null, the offset should make some sense.
 264 // That is, it should be in the range [0, MAX_OBJECT_SIZE].
 265 UNSAFE_ENTRY(jobject, Unsafe_GetObject(JNIEnv *env, jobject unsafe, jobject obj, jlong offset))
 266   UnsafeWrapper("Unsafe_GetObject");
 267   GET_OOP_FIELD(obj, offset, v)
 268 
 269   ensure_satb_referent_alive(p, offset, v);
 270 
 271   return JNIHandles::make_local(env, v);
 272 UNSAFE_END
 273 
 274 UNSAFE_ENTRY(void, Unsafe_SetObject(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject x_h))
 275   UnsafeWrapper("Unsafe_SetObject");
 276   oop x = JNIHandles::resolve(x_h);
 277   oop p = JNIHandles::resolve(obj);
 278   if (UseCompressedOops) {
 279     oop_store((narrowOop*)index_oop_from_field_offset_long(p, offset), x);
 280   } else {
 281     oop_store((oop*)index_oop_from_field_offset_long(p, offset), x);
 282   }
 283 UNSAFE_END
 284 
 285 UNSAFE_ENTRY(jobject, Unsafe_GetObjectVolatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset))
 286   UnsafeWrapper("Unsafe_GetObjectVolatile");
 287   oop p = JNIHandles::resolve(obj);
 288   void* addr = index_oop_from_field_offset_long(p, offset);
 289   volatile oop v;
 290   if (UseCompressedOops) {
 291     volatile narrowOop n = *(volatile narrowOop*) addr;
 292     (void)const_cast<oop&>(v = oopDesc::decode_heap_oop(n));
 293   } else {
 294     (void)const_cast<oop&>(v = *(volatile oop*) addr);
 295   }
 296 
 297   ensure_satb_referent_alive(p, offset, v);
 298 
 299   OrderAccess::acquire();
 300   return JNIHandles::make_local(env, v);
 301 UNSAFE_END
 302 
 303 UNSAFE_ENTRY(void, Unsafe_SetObjectVolatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject x_h))
 304   UnsafeWrapper("Unsafe_SetObjectVolatile");
 305   oop x = JNIHandles::resolve(x_h);
 306   oop p = JNIHandles::resolve(obj);
 307   void* addr = index_oop_from_field_offset_long(p, offset);
 308   OrderAccess::release();
 309   if (UseCompressedOops) {
 310     oop_store((narrowOop*)addr, x);
 311   } else {
 312     oop_store((oop*)addr, x);
 313   }
 314   OrderAccess::fence();
 315 UNSAFE_END
 316 
 317 #ifndef SUPPORTS_NATIVE_CX8
 318 
 319 // VM_Version::supports_cx8() is a surrogate for 'supports atomic long memory ops'.
 320 //
 321 // On platforms which do not support atomic compare-and-swap of jlong (8 byte)
 322 // values we have to use a lock-based scheme to enforce atomicity. This has to be
 323 // applied to all Unsafe operations that set the value of a jlong field. Even so
 324 // the compareAndSwapLong operation will not be atomic with respect to direct stores
 325 // to the field from Java code. It is important therefore that any Java code that
 326 // utilizes these Unsafe jlong operations does not perform direct stores. To permit
 327 // direct loads of the field from Java code we must also use Atomic::store within the
 328 // locked regions. And for good measure, in case there are direct stores, we also
 329 // employ Atomic::load within those regions. Note that the field in question must be
 330 // volatile and so must have atomic load/store accesses applied at the Java level.
 331 //
 332 // The locking scheme could utilize a range of strategies for controlling the locking
 333 // granularity: from a lock per-field through to a single global lock. The latter is
 334 // the simplest and is used for the current implementation. Note that the Java object
 335 // that contains the field, can not, in general, be used for locking. To do so can lead
 336 // to deadlocks as we may introduce locking into what appears to the Java code to be a
 337 // lock-free path.
 338 //
 339 // As all the locked-regions are very short and themselves non-blocking we can treat
 340 // them as leaf routines and elide safepoint checks (ie we don't perform any thread
 341 // state transitions even when blocking for the lock). Note that if we do choose to
 342 // add safepoint checks and thread state transitions, we must ensure that we calculate
 343 // the address of the field _after_ we have acquired the lock, else the object may have
 344 // been moved by the GC
 345 
 346 UNSAFE_ENTRY(jlong, Unsafe_GetLongVolatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset))
 347   UnsafeWrapper("Unsafe_GetLongVolatile");
 348   {
 349     if (VM_Version::supports_cx8()) {
 350       GET_FIELD_VOLATILE(obj, offset, jlong, v);
 351       return v;
 352     }
 353     else {
 354       Handle p (THREAD, JNIHandles::resolve(obj));
 355       jlong* addr = (jlong*)(index_oop_from_field_offset_long(p(), offset));
 356       MutexLockerEx mu(UnsafeJlong_lock, Mutex::_no_safepoint_check_flag);
 357       jlong value = Atomic::load(addr);
 358       return value;
 359     }
 360   }
 361 UNSAFE_END
 362 
 363 UNSAFE_ENTRY(void, Unsafe_SetLongVolatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jlong x))
 364   UnsafeWrapper("Unsafe_SetLongVolatile");
 365   {
 366     if (VM_Version::supports_cx8()) {
 367       SET_FIELD_VOLATILE(obj, offset, jlong, x);
 368     }
 369     else {
 370       Handle p (THREAD, JNIHandles::resolve(obj));
 371       jlong* addr = (jlong*)(index_oop_from_field_offset_long(p(), offset));
 372       MutexLockerEx mu(UnsafeJlong_lock, Mutex::_no_safepoint_check_flag);
 373       Atomic::store(x, addr);
 374     }
 375   }
 376 UNSAFE_END
 377 
 378 #endif // not SUPPORTS_NATIVE_CX8
 379 
 380 #define DEFINE_GETSETOOP(jboolean, Boolean) \
 381  \
 382 UNSAFE_ENTRY(jboolean, Unsafe_Get##Boolean##140(JNIEnv *env, jobject unsafe, jobject obj, jint offset)) \
 383   UnsafeWrapper("Unsafe_Get"#Boolean); \
 384   if (obj == NULL)  THROW_0(vmSymbols::java_lang_NullPointerException()); \
 385   GET_FIELD(obj, offset, jboolean, v); \
 386   return v; \
 387 UNSAFE_END \
 388  \
 389 UNSAFE_ENTRY(void, Unsafe_Set##Boolean##140(JNIEnv *env, jobject unsafe, jobject obj, jint offset, jboolean x)) \
 390   UnsafeWrapper("Unsafe_Set"#Boolean); \
 391   if (obj == NULL)  THROW(vmSymbols::java_lang_NullPointerException()); \
 392   SET_FIELD(obj, offset, jboolean, x); \
 393 UNSAFE_END \
 394  \
 395 UNSAFE_ENTRY(jboolean, Unsafe_Get##Boolean(JNIEnv *env, jobject unsafe, jobject obj, jlong offset)) \
 396   UnsafeWrapper("Unsafe_Get"#Boolean); \
 397   GET_FIELD(obj, offset, jboolean, v); \
 398   return v; \
 399 UNSAFE_END \
 400  \
 401 UNSAFE_ENTRY(void, Unsafe_Set##Boolean(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jboolean x)) \
 402   UnsafeWrapper("Unsafe_Set"#Boolean); \
 403   SET_FIELD(obj, offset, jboolean, x); \
 404 UNSAFE_END \
 405  \
 406 // END DEFINE_GETSETOOP.
 407 
 408 DEFINE_GETSETOOP(jboolean, Boolean)
 409 DEFINE_GETSETOOP(jbyte, Byte)
 410 DEFINE_GETSETOOP(jshort, Short);
 411 DEFINE_GETSETOOP(jchar, Char);
 412 DEFINE_GETSETOOP(jint, Int);
 413 DEFINE_GETSETOOP(jlong, Long);
 414 DEFINE_GETSETOOP(jfloat, Float);
 415 DEFINE_GETSETOOP(jdouble, Double);
 416 
 417 #undef DEFINE_GETSETOOP
 418 
 419 #define DEFINE_GETSETOOP_VOLATILE(jboolean, Boolean) \
 420  \
 421 UNSAFE_ENTRY(jboolean, Unsafe_Get##Boolean##Volatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset)) \
 422   UnsafeWrapper("Unsafe_Get"#Boolean); \
 423   GET_FIELD_VOLATILE(obj, offset, jboolean, v); \
 424   return v; \
 425 UNSAFE_END \
 426  \
 427 UNSAFE_ENTRY(void, Unsafe_Set##Boolean##Volatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jboolean x)) \
 428   UnsafeWrapper("Unsafe_Set"#Boolean); \
 429   SET_FIELD_VOLATILE(obj, offset, jboolean, x); \
 430 UNSAFE_END \
 431  \
 432 // END DEFINE_GETSETOOP_VOLATILE.
 433 
 434 DEFINE_GETSETOOP_VOLATILE(jboolean, Boolean)
 435 DEFINE_GETSETOOP_VOLATILE(jbyte, Byte)
 436 DEFINE_GETSETOOP_VOLATILE(jshort, Short);
 437 DEFINE_GETSETOOP_VOLATILE(jchar, Char);
 438 DEFINE_GETSETOOP_VOLATILE(jint, Int);
 439 DEFINE_GETSETOOP_VOLATILE(jfloat, Float);
 440 DEFINE_GETSETOOP_VOLATILE(jdouble, Double);
 441 
 442 #ifdef SUPPORTS_NATIVE_CX8
 443 DEFINE_GETSETOOP_VOLATILE(jlong, Long);
 444 #endif
 445 
 446 #undef DEFINE_GETSETOOP_VOLATILE
 447 
 448 // The non-intrinsified versions of setOrdered just use setVolatile
 449 
 450 UNSAFE_ENTRY(void, Unsafe_SetOrderedInt(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jint x))
 451   UnsafeWrapper("Unsafe_SetOrderedInt");
 452   SET_FIELD_VOLATILE(obj, offset, jint, x);
 453 UNSAFE_END
 454 
 455 UNSAFE_ENTRY(void, Unsafe_SetOrderedObject(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject x_h))
 456   UnsafeWrapper("Unsafe_SetOrderedObject");
 457   oop x = JNIHandles::resolve(x_h);
 458   oop p = JNIHandles::resolve(obj);
 459   void* addr = index_oop_from_field_offset_long(p, offset);
 460   OrderAccess::release();
 461   if (UseCompressedOops) {
 462     oop_store((narrowOop*)addr, x);
 463   } else {
 464     oop_store((oop*)addr, x);
 465   }
 466   OrderAccess::fence();
 467 UNSAFE_END
 468 
 469 UNSAFE_ENTRY(void, Unsafe_SetOrderedLong(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jlong x))
 470   UnsafeWrapper("Unsafe_SetOrderedLong");
 471 #ifdef SUPPORTS_NATIVE_CX8
 472   SET_FIELD_VOLATILE(obj, offset, jlong, x);
 473 #else
 474   // Keep old code for platforms which may not have atomic long (8 bytes) instructions
 475   {
 476     if (VM_Version::supports_cx8()) {
 477       SET_FIELD_VOLATILE(obj, offset, jlong, x);
 478     }
 479     else {
 480       Handle p (THREAD, JNIHandles::resolve(obj));
 481       jlong* addr = (jlong*)(index_oop_from_field_offset_long(p(), offset));
 482       MutexLockerEx mu(UnsafeJlong_lock, Mutex::_no_safepoint_check_flag);
 483       Atomic::store(x, addr);
 484     }
 485   }
 486 #endif
 487 UNSAFE_END
 488 
 489 UNSAFE_ENTRY(void, Unsafe_LoadFence(JNIEnv *env, jobject unsafe))
 490   UnsafeWrapper("Unsafe_LoadFence");
 491   OrderAccess::acquire();
 492 UNSAFE_END
 493 
 494 UNSAFE_ENTRY(void, Unsafe_StoreFence(JNIEnv *env, jobject unsafe))
 495   UnsafeWrapper("Unsafe_StoreFence");
 496   OrderAccess::release();
 497 UNSAFE_END
 498 
 499 UNSAFE_ENTRY(void, Unsafe_FullFence(JNIEnv *env, jobject unsafe))
 500   UnsafeWrapper("Unsafe_FullFence");
 501   OrderAccess::fence();
 502 UNSAFE_END
 503 
 504 ////// Data in the C heap.
 505 
 506 // Note:  These do not throw NullPointerException for bad pointers.
 507 // They just crash.  Only a oop base pointer can generate a NullPointerException.
 508 //
 509 #define DEFINE_GETSETNATIVE(java_type, Type, native_type) \
 510  \
 511 UNSAFE_ENTRY(java_type, Unsafe_GetNative##Type(JNIEnv *env, jobject unsafe, jlong addr)) \
 512   UnsafeWrapper("Unsafe_GetNative"#Type); \
 513   void* p = addr_from_java(addr); \
 514   JavaThread* t = JavaThread::current(); \
 515   t->set_doing_unsafe_access(true); \
 516   java_type x = *(volatile native_type*)p; \
 517   t->set_doing_unsafe_access(false); \
 518   return x; \
 519 UNSAFE_END \
 520  \
 521 UNSAFE_ENTRY(void, Unsafe_SetNative##Type(JNIEnv *env, jobject unsafe, jlong addr, java_type x)) \
 522   UnsafeWrapper("Unsafe_SetNative"#Type); \
 523   JavaThread* t = JavaThread::current(); \
 524   t->set_doing_unsafe_access(true); \
 525   void* p = addr_from_java(addr); \
 526   *(volatile native_type*)p = x; \
 527   t->set_doing_unsafe_access(false); \
 528 UNSAFE_END \
 529  \
 530 // END DEFINE_GETSETNATIVE.
 531 
 532 DEFINE_GETSETNATIVE(jbyte, Byte, signed char)
 533 DEFINE_GETSETNATIVE(jshort, Short, signed short);
 534 DEFINE_GETSETNATIVE(jchar, Char, unsigned short);
 535 DEFINE_GETSETNATIVE(jint, Int, jint);
 536 // no long -- handled specially
 537 DEFINE_GETSETNATIVE(jfloat, Float, float);
 538 DEFINE_GETSETNATIVE(jdouble, Double, double);
 539 
 540 #undef DEFINE_GETSETNATIVE
 541 
 542 UNSAFE_ENTRY(jlong, Unsafe_GetNativeLong(JNIEnv *env, jobject unsafe, jlong addr))
 543   UnsafeWrapper("Unsafe_GetNativeLong");
 544   JavaThread* t = JavaThread::current();
 545   // We do it this way to avoid problems with access to heap using 64
 546   // bit loads, as jlong in heap could be not 64-bit aligned, and on
 547   // some CPUs (SPARC) it leads to SIGBUS.
 548   t->set_doing_unsafe_access(true);
 549   void* p = addr_from_java(addr);
 550   jlong x;
 551   if (((intptr_t)p & 7) == 0) {
 552     // jlong is aligned, do a volatile access
 553     x = *(volatile jlong*)p;
 554   } else {
 555     jlong_accessor acc;
 556     acc.words[0] = ((volatile jint*)p)[0];
 557     acc.words[1] = ((volatile jint*)p)[1];
 558     x = acc.long_value;
 559   }
 560   t->set_doing_unsafe_access(false);
 561   return x;
 562 UNSAFE_END
 563 
 564 UNSAFE_ENTRY(void, Unsafe_SetNativeLong(JNIEnv *env, jobject unsafe, jlong addr, jlong x))
 565   UnsafeWrapper("Unsafe_SetNativeLong");
 566   JavaThread* t = JavaThread::current();
 567   // see comment for Unsafe_GetNativeLong
 568   t->set_doing_unsafe_access(true);
 569   void* p = addr_from_java(addr);
 570   if (((intptr_t)p & 7) == 0) {
 571     // jlong is aligned, do a volatile access
 572     *(volatile jlong*)p = x;
 573   } else {
 574     jlong_accessor acc;
 575     acc.long_value = x;
 576     ((volatile jint*)p)[0] = acc.words[0];
 577     ((volatile jint*)p)[1] = acc.words[1];
 578   }
 579   t->set_doing_unsafe_access(false);
 580 UNSAFE_END
 581 
 582 
 583 UNSAFE_ENTRY(jlong, Unsafe_GetNativeAddress(JNIEnv *env, jobject unsafe, jlong addr))
 584   UnsafeWrapper("Unsafe_GetNativeAddress");
 585   void* p = addr_from_java(addr);
 586   return addr_to_java(*(void**)p);
 587 UNSAFE_END
 588 
 589 UNSAFE_ENTRY(void, Unsafe_SetNativeAddress(JNIEnv *env, jobject unsafe, jlong addr, jlong x))
 590   UnsafeWrapper("Unsafe_SetNativeAddress");
 591   void* p = addr_from_java(addr);
 592   *(void**)p = addr_from_java(x);
 593 UNSAFE_END
 594 
 595 
 596 ////// Allocation requests
 597 
 598 UNSAFE_ENTRY(jobject, Unsafe_AllocateInstance(JNIEnv *env, jobject unsafe, jclass cls))
 599   UnsafeWrapper("Unsafe_AllocateInstance");
 600   {
 601     ThreadToNativeFromVM ttnfv(thread);
 602     return env->AllocObject(cls);
 603   }
 604 UNSAFE_END
 605 
 606 UNSAFE_ENTRY(jlong, Unsafe_AllocateMemory(JNIEnv *env, jobject unsafe, jlong size))
 607   UnsafeWrapper("Unsafe_AllocateMemory");
 608   size_t sz = (size_t)size;
 609   if (sz != (julong)size || size < 0) {
 610     THROW_0(vmSymbols::java_lang_IllegalArgumentException());
 611   }
 612   if (sz == 0) {
 613     return 0;
 614   }
 615   sz = round_to(sz, HeapWordSize);
 616   void* x = os::malloc(sz, mtInternal);
 617   if (x == NULL) {
 618     THROW_0(vmSymbols::java_lang_OutOfMemoryError());
 619   }
 620   //Copy::fill_to_words((HeapWord*)x, sz / HeapWordSize);
 621   return addr_to_java(x);
 622 UNSAFE_END
 623 
 624 UNSAFE_ENTRY(jlong, Unsafe_ReallocateMemory(JNIEnv *env, jobject unsafe, jlong addr, jlong size))
 625   UnsafeWrapper("Unsafe_ReallocateMemory");
 626   void* p = addr_from_java(addr);
 627   size_t sz = (size_t)size;
 628   if (sz != (julong)size || size < 0) {
 629     THROW_0(vmSymbols::java_lang_IllegalArgumentException());
 630   }
 631   if (sz == 0) {
 632     os::free(p);
 633     return 0;
 634   }
 635   sz = round_to(sz, HeapWordSize);
 636   void* x = (p == NULL) ? os::malloc(sz, mtInternal) : os::realloc(p, sz, mtInternal);
 637   if (x == NULL) {
 638     THROW_0(vmSymbols::java_lang_OutOfMemoryError());
 639   }
 640   return addr_to_java(x);
 641 UNSAFE_END
 642 
 643 UNSAFE_ENTRY(void, Unsafe_FreeMemory(JNIEnv *env, jobject unsafe, jlong addr))
 644   UnsafeWrapper("Unsafe_FreeMemory");
 645   void* p = addr_from_java(addr);
 646   if (p == NULL) {
 647     return;
 648   }
 649   os::free(p);
 650 UNSAFE_END
 651 
 652 UNSAFE_ENTRY(void, Unsafe_SetMemory(JNIEnv *env, jobject unsafe, jlong addr, jlong size, jbyte value))
 653   UnsafeWrapper("Unsafe_SetMemory");
 654   size_t sz = (size_t)size;
 655   if (sz != (julong)size || size < 0) {
 656     THROW(vmSymbols::java_lang_IllegalArgumentException());
 657   }
 658   char* p = (char*) addr_from_java(addr);
 659   Copy::fill_to_memory_atomic(p, sz, value);
 660 UNSAFE_END
 661 
 662 UNSAFE_ENTRY(void, Unsafe_SetMemory2(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jlong size, jbyte value))
 663   UnsafeWrapper("Unsafe_SetMemory");
 664   size_t sz = (size_t)size;
 665   if (sz != (julong)size || size < 0) {
 666     THROW(vmSymbols::java_lang_IllegalArgumentException());
 667   }
 668   oop base = JNIHandles::resolve(obj);
 669   void* p = index_oop_from_field_offset_long(base, offset);
 670   Copy::fill_to_memory_atomic(p, sz, value);
 671 UNSAFE_END
 672 
 673 UNSAFE_ENTRY(void, Unsafe_CopyMemory(JNIEnv *env, jobject unsafe, jlong srcAddr, jlong dstAddr, jlong size))
 674   UnsafeWrapper("Unsafe_CopyMemory");
 675   if (size == 0) {
 676     return;
 677   }
 678   size_t sz = (size_t)size;
 679   if (sz != (julong)size || size < 0) {
 680     THROW(vmSymbols::java_lang_IllegalArgumentException());
 681   }
 682   void* src = addr_from_java(srcAddr);
 683   void* dst = addr_from_java(dstAddr);
 684   Copy::conjoint_memory_atomic(src, dst, sz);
 685 UNSAFE_END
 686 
 687 UNSAFE_ENTRY(void, Unsafe_CopyMemory2(JNIEnv *env, jobject unsafe, jobject srcObj, jlong srcOffset, jobject dstObj, jlong dstOffset, jlong size))
 688   UnsafeWrapper("Unsafe_CopyMemory");
 689   if (size == 0) {
 690     return;
 691   }
 692   size_t sz = (size_t)size;
 693   if (sz != (julong)size || size < 0) {
 694     THROW(vmSymbols::java_lang_IllegalArgumentException());
 695   }
 696   oop srcp = JNIHandles::resolve(srcObj);
 697   oop dstp = JNIHandles::resolve(dstObj);
 698   if (dstp != NULL && !dstp->is_typeArray()) {
 699     // NYI:  This works only for non-oop arrays at present.
 700     // Generalizing it would be reasonable, but requires card marking.
 701     // Also, autoboxing a Long from 0L in copyMemory(x,y, 0L,z, n) would be bad.
 702     THROW(vmSymbols::java_lang_IllegalArgumentException());
 703   }
 704   void* src = index_oop_from_field_offset_long(srcp, srcOffset);
 705   void* dst = index_oop_from_field_offset_long(dstp, dstOffset);
 706   Copy::conjoint_memory_atomic(src, dst, sz);
 707 UNSAFE_END
 708 
 709 
 710 ////// Random queries
 711 
 712 // See comment at file start about UNSAFE_LEAF
 713 //UNSAFE_LEAF(jint, Unsafe_AddressSize())
 714 UNSAFE_ENTRY(jint, Unsafe_AddressSize(JNIEnv *env, jobject unsafe))
 715   UnsafeWrapper("Unsafe_AddressSize");
 716   return sizeof(void*);
 717 UNSAFE_END
 718 
 719 // See comment at file start about UNSAFE_LEAF
 720 //UNSAFE_LEAF(jint, Unsafe_PageSize())
 721 UNSAFE_ENTRY(jint, Unsafe_PageSize(JNIEnv *env, jobject unsafe))
 722   UnsafeWrapper("Unsafe_PageSize");
 723   return os::vm_page_size();
 724 UNSAFE_END
 725 
 726 jint find_field_offset(jobject field, int must_be_static, TRAPS) {
 727   if (field == NULL) {
 728     THROW_0(vmSymbols::java_lang_NullPointerException());
 729   }
 730 
 731   oop reflected   = JNIHandles::resolve_non_null(field);
 732   oop mirror      = java_lang_reflect_Field::clazz(reflected);
 733   Klass* k      = java_lang_Class::as_Klass(mirror);
 734   int slot        = java_lang_reflect_Field::slot(reflected);
 735   int modifiers   = java_lang_reflect_Field::modifiers(reflected);
 736 
 737   if (must_be_static >= 0) {
 738     int really_is_static = ((modifiers & JVM_ACC_STATIC) != 0);
 739     if (must_be_static != really_is_static) {
 740       THROW_0(vmSymbols::java_lang_IllegalArgumentException());
 741     }
 742   }
 743 
 744   int offset = InstanceKlass::cast(k)->field_offset(slot);
 745   return field_offset_from_byte_offset(offset);
 746 }
 747 
 748 UNSAFE_ENTRY(jlong, Unsafe_ObjectFieldOffset(JNIEnv *env, jobject unsafe, jobject field))
 749   UnsafeWrapper("Unsafe_ObjectFieldOffset");
 750   return find_field_offset(field, 0, THREAD);
 751 UNSAFE_END
 752 
 753 UNSAFE_ENTRY(jlong, Unsafe_StaticFieldOffset(JNIEnv *env, jobject unsafe, jobject field))
 754   UnsafeWrapper("Unsafe_StaticFieldOffset");
 755   return find_field_offset(field, 1, THREAD);
 756 UNSAFE_END
 757 
 758 UNSAFE_ENTRY(jobject, Unsafe_StaticFieldBaseFromField(JNIEnv *env, jobject unsafe, jobject field))
 759   UnsafeWrapper("Unsafe_StaticFieldBase");
 760   // Note:  In this VM implementation, a field address is always a short
 761   // offset from the base of a a klass metaobject.  Thus, the full dynamic
 762   // range of the return type is never used.  However, some implementations
 763   // might put the static field inside an array shared by many classes,
 764   // or even at a fixed address, in which case the address could be quite
 765   // large.  In that last case, this function would return NULL, since
 766   // the address would operate alone, without any base pointer.
 767 
 768   if (field == NULL)  THROW_0(vmSymbols::java_lang_NullPointerException());
 769 
 770   oop reflected   = JNIHandles::resolve_non_null(field);
 771   oop mirror      = java_lang_reflect_Field::clazz(reflected);
 772   int modifiers   = java_lang_reflect_Field::modifiers(reflected);
 773 
 774   if ((modifiers & JVM_ACC_STATIC) == 0) {
 775     THROW_0(vmSymbols::java_lang_IllegalArgumentException());
 776   }
 777 
 778   return JNIHandles::make_local(env, mirror);
 779 UNSAFE_END
 780 
 781 //@deprecated
 782 UNSAFE_ENTRY(jint, Unsafe_FieldOffset(JNIEnv *env, jobject unsafe, jobject field))
 783   UnsafeWrapper("Unsafe_FieldOffset");
 784   // tries (but fails) to be polymorphic between static and non-static:
 785   jlong offset = find_field_offset(field, -1, THREAD);
 786   guarantee(offset == (jint)offset, "offset fits in 32 bits");
 787   return (jint)offset;
 788 UNSAFE_END
 789 
 790 //@deprecated
 791 UNSAFE_ENTRY(jobject, Unsafe_StaticFieldBaseFromClass(JNIEnv *env, jobject unsafe, jobject clazz))
 792   UnsafeWrapper("Unsafe_StaticFieldBase");
 793   if (clazz == NULL) {
 794     THROW_0(vmSymbols::java_lang_NullPointerException());
 795   }
 796   return JNIHandles::make_local(env, JNIHandles::resolve_non_null(clazz));
 797 UNSAFE_END
 798 
 799 UNSAFE_ENTRY(void, Unsafe_EnsureClassInitialized(JNIEnv *env, jobject unsafe, jobject clazz)) {
 800   UnsafeWrapper("Unsafe_EnsureClassInitialized");
 801   if (clazz == NULL) {
 802     THROW(vmSymbols::java_lang_NullPointerException());
 803   }
 804   oop mirror = JNIHandles::resolve_non_null(clazz);
 805 
 806   Klass* klass = java_lang_Class::as_Klass(mirror);
 807   if (klass != NULL && klass->should_be_initialized()) {
 808     InstanceKlass* k = InstanceKlass::cast(klass);
 809     k->initialize(CHECK);
 810   }
 811 }
 812 UNSAFE_END
 813 
 814 UNSAFE_ENTRY(jboolean, Unsafe_ShouldBeInitialized(JNIEnv *env, jobject unsafe, jobject clazz)) {
 815   UnsafeWrapper("Unsafe_ShouldBeInitialized");
 816   if (clazz == NULL) {
 817     THROW_(vmSymbols::java_lang_NullPointerException(), false);
 818   }
 819   oop mirror = JNIHandles::resolve_non_null(clazz);
 820   Klass* klass = java_lang_Class::as_Klass(mirror);
 821   if (klass != NULL && klass->should_be_initialized()) {
 822     return true;
 823   }
 824   return false;
 825 }
 826 UNSAFE_END
 827 
 828 static void getBaseAndScale(int& base, int& scale, jclass acls, TRAPS) {
 829   if (acls == NULL) {
 830     THROW(vmSymbols::java_lang_NullPointerException());
 831   }
 832   oop      mirror = JNIHandles::resolve_non_null(acls);
 833   Klass* k      = java_lang_Class::as_Klass(mirror);
 834   if (k == NULL || !k->oop_is_array()) {
 835     THROW(vmSymbols::java_lang_InvalidClassException());
 836   } else if (k->oop_is_objArray()) {
 837     base  = arrayOopDesc::base_offset_in_bytes(T_OBJECT);
 838     scale = heapOopSize;
 839   } else if (k->oop_is_typeArray()) {
 840     TypeArrayKlass* tak = TypeArrayKlass::cast(k);
 841     base  = tak->array_header_in_bytes();
 842     assert(base == arrayOopDesc::base_offset_in_bytes(tak->element_type()), "array_header_size semantics ok");
 843     scale = (1 << tak->log2_element_size());
 844   } else {
 845     ShouldNotReachHere();
 846   }
 847 }
 848 
 849 UNSAFE_ENTRY(jint, Unsafe_ArrayBaseOffset(JNIEnv *env, jobject unsafe, jclass acls))
 850   UnsafeWrapper("Unsafe_ArrayBaseOffset");
 851   int base = 0, scale = 0;
 852   getBaseAndScale(base, scale, acls, CHECK_0);
 853   return field_offset_from_byte_offset(base);
 854 UNSAFE_END
 855 
 856 
 857 UNSAFE_ENTRY(jint, Unsafe_ArrayIndexScale(JNIEnv *env, jobject unsafe, jclass acls))
 858   UnsafeWrapper("Unsafe_ArrayIndexScale");
 859   int base = 0, scale = 0;
 860   getBaseAndScale(base, scale, acls, CHECK_0);
 861   // This VM packs both fields and array elements down to the byte.
 862   // But watch out:  If this changes, so that array references for
 863   // a given primitive type (say, T_BOOLEAN) use different memory units
 864   // than fields, this method MUST return zero for such arrays.
 865   // For example, the VM used to store sub-word sized fields in full
 866   // words in the object layout, so that accessors like getByte(Object,int)
 867   // did not really do what one might expect for arrays.  Therefore,
 868   // this function used to report a zero scale factor, so that the user
 869   // would know not to attempt to access sub-word array elements.
 870   // // Code for unpacked fields:
 871   // if (scale < wordSize)  return 0;
 872 
 873   // The following allows for a pretty general fieldOffset cookie scheme,
 874   // but requires it to be linear in byte offset.
 875   return field_offset_from_byte_offset(scale) - field_offset_from_byte_offset(0);
 876 UNSAFE_END
 877 
 878 
 879 static inline void throw_new(JNIEnv *env, const char *ename) {
 880   char buf[100];
 881   strcpy(buf, "java/lang/");
 882   strcat(buf, ename);
 883   jclass cls = env->FindClass(buf);
 884   if (env->ExceptionCheck()) {
 885     env->ExceptionClear();
 886     tty->print_cr("Unsafe: cannot throw %s because FindClass has failed", buf);
 887     return;
 888   }
 889   char* msg = NULL;
 890   env->ThrowNew(cls, msg);
 891 }
 892 
 893 static jclass Unsafe_DefineClass_impl(JNIEnv *env, jstring name, jbyteArray data, int offset, int length, jobject loader, jobject pd) {
 894   {
 895     // Code lifted from JDK 1.3 ClassLoader.c
 896 
 897     jbyte *body;
 898     char *utfName;
 899     jclass result = 0;
 900     char buf[128];
 901 
 902     if (UsePerfData) {
 903       ClassLoader::unsafe_defineClassCallCounter()->inc();
 904     }
 905 
 906     if (data == NULL) {
 907         throw_new(env, "NullPointerException");
 908         return 0;
 909     }
 910 
 911     /* Work around 4153825. malloc crashes on Solaris when passed a
 912      * negative size.
 913      */
 914     if (length < 0) {
 915         throw_new(env, "ArrayIndexOutOfBoundsException");
 916         return 0;
 917     }
 918 
 919     body = NEW_C_HEAP_ARRAY(jbyte, length, mtInternal);
 920 
 921     if (body == 0) {
 922         throw_new(env, "OutOfMemoryError");
 923         return 0;
 924     }
 925 
 926     env->GetByteArrayRegion(data, offset, length, body);
 927 
 928     if (env->ExceptionOccurred())
 929         goto free_body;
 930 
 931     if (name != NULL) {
 932         uint len = env->GetStringUTFLength(name);
 933         int unicode_len = env->GetStringLength(name);
 934         if (len >= sizeof(buf)) {
 935             utfName = NEW_C_HEAP_ARRAY(char, len + 1, mtInternal);
 936             if (utfName == NULL) {
 937                 throw_new(env, "OutOfMemoryError");
 938                 goto free_body;
 939             }
 940         } else {
 941             utfName = buf;
 942         }
 943         env->GetStringUTFRegion(name, 0, unicode_len, utfName);
 944         //VerifyFixClassname(utfName);
 945         for (uint i = 0; i < len; i++) {
 946           if (utfName[i] == '.')   utfName[i] = '/';
 947         }
 948     } else {
 949         utfName = NULL;
 950     }
 951 
 952     result = JVM_DefineClass(env, utfName, loader, body, length, pd);
 953 
 954     if (utfName && utfName != buf)
 955         FREE_C_HEAP_ARRAY(char, utfName, mtInternal);
 956 
 957  free_body:
 958     FREE_C_HEAP_ARRAY(jbyte, body, mtInternal);
 959     return result;
 960   }
 961 }
 962 
 963 
 964 UNSAFE_ENTRY(jclass, Unsafe_DefineClass(JNIEnv *env, jobject unsafe, jstring name, jbyteArray data, int offset, int length, jobject loader, jobject pd))
 965   UnsafeWrapper("Unsafe_DefineClass");
 966   {
 967     ThreadToNativeFromVM ttnfv(thread);
 968     return Unsafe_DefineClass_impl(env, name, data, offset, length, loader, pd);
 969   }
 970 UNSAFE_END
 971 
 972 
 973 UNSAFE_ENTRY(jclass, Unsafe_DefineClass0(JNIEnv *env, jobject unsafe, jstring name, jbyteArray data, int offset, int length))
 974   UnsafeWrapper("Unsafe_DefineClass");
 975   {
 976     ThreadToNativeFromVM ttnfv(thread);
 977 
 978     int depthFromDefineClass0 = 1;
 979     jclass  caller = JVM_GetCallerClass(env, depthFromDefineClass0);
 980     jobject loader = (caller == NULL) ? NULL : JVM_GetClassLoader(env, caller);
 981     jobject pd     = (caller == NULL) ? NULL : JVM_GetProtectionDomain(env, caller);
 982 
 983     return Unsafe_DefineClass_impl(env, name, data, offset, length, loader, pd);
 984   }
 985 UNSAFE_END
 986 
 987 
 988 #define DAC_Args CLS"[B["OBJ
 989 // define a class but do not make it known to the class loader or system dictionary
 990 // - host_class:  supplies context for linkage, access control, protection domain, and class loader
 991 // - data:  bytes of a class file, a raw memory address (length gives the number of bytes)
 992 // - cp_patches:  where non-null entries exist, they replace corresponding CP entries in data
 993 
 994 // When you load an anonymous class U, it works as if you changed its name just before loading,
 995 // to a name that you will never use again.  Since the name is lost, no other class can directly
 996 // link to any member of U.  Just after U is loaded, the only way to use it is reflectively,
 997 // through java.lang.Class methods like Class.newInstance.
 998 
 999 // Access checks for linkage sites within U continue to follow the same rules as for named classes.
1000 // The package of an anonymous class is given by the package qualifier on the name under which it was loaded.
1001 // An anonymous class also has special privileges to access any member of its host class.
1002 // This is the main reason why this loading operation is unsafe.  The purpose of this is to
1003 // allow language implementations to simulate "open classes"; a host class in effect gets
1004 // new code when an anonymous class is loaded alongside it.  A less convenient but more
1005 // standard way to do this is with reflection, which can also be set to ignore access
1006 // restrictions.
1007 
1008 // Access into an anonymous class is possible only through reflection.  Therefore, there
1009 // are no special access rules for calling into an anonymous class.  The relaxed access
1010 // rule for the host class is applied in the opposite direction:  A host class reflectively
1011 // access one of its anonymous classes.
1012 
1013 // If you load the same bytecodes twice, you get two different classes.  You can reload
1014 // the same bytecodes with or without varying CP patches.
1015 
1016 // By using the CP patching array, you can have a new anonymous class U2 refer to an older one U1.
1017 // The bytecodes for U2 should refer to U1 by a symbolic name (doesn't matter what the name is).
1018 // The CONSTANT_Class entry for that name can be patched to refer directly to U1.
1019 
1020 // This allows, for example, U2 to use U1 as a superclass or super-interface, or as
1021 // an outer class (so that U2 is an anonymous inner class of anonymous U1).
1022 // It is not possible for a named class, or an older anonymous class, to refer by
1023 // name (via its CP) to a newer anonymous class.
1024 
1025 // CP patching may also be used to modify (i.e., hack) the names of methods, classes,
1026 // or type descriptors used in the loaded anonymous class.
1027 
1028 // Finally, CP patching may be used to introduce "live" objects into the constant pool,
1029 // instead of "dead" strings.  A compiled statement like println((Object)"hello") can
1030 // be changed to println(greeting), where greeting is an arbitrary object created before
1031 // the anonymous class is loaded.  This is useful in dynamic languages, in which
1032 // various kinds of metaobjects must be introduced as constants into bytecode.
1033 // Note the cast (Object), which tells the verifier to expect an arbitrary object,
1034 // not just a literal string.  For such ldc instructions, the verifier uses the
1035 // type Object instead of String, if the loaded constant is not in fact a String.
1036 
1037 static instanceKlassHandle
1038 Unsafe_DefineAnonymousClass_impl(JNIEnv *env,
1039                                  jclass host_class, jbyteArray data, jobjectArray cp_patches_jh,
1040                                  HeapWord* *temp_alloc,
1041                                  TRAPS) {
1042 
1043   if (UsePerfData) {
1044     ClassLoader::unsafe_defineClassCallCounter()->inc();
1045   }
1046 
1047   if (data == NULL) {
1048     THROW_0(vmSymbols::java_lang_NullPointerException());
1049   }
1050 
1051   jint length = typeArrayOop(JNIHandles::resolve_non_null(data))->length();
1052   jint word_length = (length + sizeof(HeapWord)-1) / sizeof(HeapWord);
1053   HeapWord* body = NEW_C_HEAP_ARRAY(HeapWord, word_length, mtInternal);
1054   if (body == NULL) {
1055     THROW_0(vmSymbols::java_lang_OutOfMemoryError());
1056   }
1057 
1058   // caller responsible to free it:
1059   (*temp_alloc) = body;
1060 
1061   {
1062     jbyte* array_base = typeArrayOop(JNIHandles::resolve_non_null(data))->byte_at_addr(0);
1063     Copy::conjoint_words((HeapWord*) array_base, body, word_length);
1064   }
1065 
1066   u1* class_bytes = (u1*) body;
1067   int class_bytes_length = (int) length;
1068   if (class_bytes_length < 0)  class_bytes_length = 0;
1069   if (class_bytes == NULL
1070       || host_class == NULL
1071       || length != class_bytes_length)
1072     THROW_0(vmSymbols::java_lang_IllegalArgumentException());
1073 
1074   objArrayHandle cp_patches_h;
1075   if (cp_patches_jh != NULL) {
1076     oop p = JNIHandles::resolve_non_null(cp_patches_jh);
1077     if (!p->is_objArray())
1078       THROW_0(vmSymbols::java_lang_IllegalArgumentException());
1079     cp_patches_h = objArrayHandle(THREAD, (objArrayOop)p);
1080   }
1081 
1082   KlassHandle host_klass(THREAD, java_lang_Class::as_Klass(JNIHandles::resolve_non_null(host_class)));
1083   const char* host_source = host_klass->external_name();
1084   Handle      host_loader(THREAD, host_klass->class_loader());
1085   Handle      host_domain(THREAD, host_klass->protection_domain());
1086 
1087   GrowableArray<Handle>* cp_patches = NULL;
1088   if (cp_patches_h.not_null()) {
1089     int alen = cp_patches_h->length();
1090     for (int i = alen-1; i >= 0; i--) {
1091       oop p = cp_patches_h->obj_at(i);
1092       if (p != NULL) {
1093         Handle patch(THREAD, p);
1094         if (cp_patches == NULL)
1095           cp_patches = new GrowableArray<Handle>(i+1, i+1, Handle());
1096         cp_patches->at_put(i, patch);
1097       }
1098     }
1099   }
1100 
1101   ClassFileStream st(class_bytes, class_bytes_length, (char*) host_source);
1102 
1103   instanceKlassHandle anon_klass;
1104   {
1105     Symbol* no_class_name = NULL;
1106     Klass* anonk = SystemDictionary::parse_stream(no_class_name,
1107                                                     host_loader, host_domain,
1108                                                     &st, host_klass, cp_patches,
1109                                                     CHECK_NULL);
1110     if (anonk == NULL)  return NULL;
1111     anon_klass = instanceKlassHandle(THREAD, anonk);
1112   }
1113 
1114   return anon_klass;
1115 }
1116 
1117 UNSAFE_ENTRY(jclass, Unsafe_DefineAnonymousClass(JNIEnv *env, jobject unsafe, jclass host_class, jbyteArray data, jobjectArray cp_patches_jh))
1118 {
1119   instanceKlassHandle anon_klass;
1120   jobject res_jh = NULL;
1121 
1122   UnsafeWrapper("Unsafe_DefineAnonymousClass");
1123   ResourceMark rm(THREAD);
1124 
1125   HeapWord* temp_alloc = NULL;
1126 
1127   anon_klass = Unsafe_DefineAnonymousClass_impl(env, host_class, data,
1128                                                 cp_patches_jh,
1129                                                    &temp_alloc, THREAD);
1130   if (anon_klass() != NULL)
1131     res_jh = JNIHandles::make_local(env, anon_klass->java_mirror());
1132 
1133   // try/finally clause:
1134   if (temp_alloc != NULL) {
1135     FREE_C_HEAP_ARRAY(HeapWord, temp_alloc, mtInternal);
1136   }
1137 
1138   // The anonymous class loader data has been artificially been kept alive to
1139   // this point.   The mirror and any instances of this class have to keep
1140   // it alive afterwards.
1141   if (anon_klass() != NULL) {
1142     anon_klass->class_loader_data()->set_keep_alive(false);
1143   }
1144 
1145   // let caller initialize it as needed...
1146 
1147   return (jclass) res_jh;
1148 }
1149 UNSAFE_END
1150 
1151 
1152 
1153 UNSAFE_ENTRY(void, Unsafe_MonitorEnter(JNIEnv *env, jobject unsafe, jobject jobj))
1154   UnsafeWrapper("Unsafe_MonitorEnter");
1155   {
1156     if (jobj == NULL) {
1157       THROW(vmSymbols::java_lang_NullPointerException());
1158     }
1159     Handle obj(thread, JNIHandles::resolve_non_null(jobj));
1160     ObjectSynchronizer::jni_enter(obj, CHECK);
1161   }
1162 UNSAFE_END
1163 
1164 
1165 UNSAFE_ENTRY(jboolean, Unsafe_TryMonitorEnter(JNIEnv *env, jobject unsafe, jobject jobj))
1166   UnsafeWrapper("Unsafe_TryMonitorEnter");
1167   {
1168     if (jobj == NULL) {
1169       THROW_(vmSymbols::java_lang_NullPointerException(), JNI_FALSE);
1170     }
1171     Handle obj(thread, JNIHandles::resolve_non_null(jobj));
1172     bool res = ObjectSynchronizer::jni_try_enter(obj, CHECK_0);
1173     return (res ? JNI_TRUE : JNI_FALSE);
1174   }
1175 UNSAFE_END
1176 
1177 
1178 UNSAFE_ENTRY(void, Unsafe_MonitorExit(JNIEnv *env, jobject unsafe, jobject jobj))
1179   UnsafeWrapper("Unsafe_MonitorExit");
1180   {
1181     if (jobj == NULL) {
1182       THROW(vmSymbols::java_lang_NullPointerException());
1183     }
1184     Handle obj(THREAD, JNIHandles::resolve_non_null(jobj));
1185     ObjectSynchronizer::jni_exit(obj(), CHECK);
1186   }
1187 UNSAFE_END
1188 
1189 
1190 UNSAFE_ENTRY(void, Unsafe_ThrowException(JNIEnv *env, jobject unsafe, jthrowable thr))
1191   UnsafeWrapper("Unsafe_ThrowException");
1192   {
1193     ThreadToNativeFromVM ttnfv(thread);
1194     env->Throw(thr);
1195   }
1196 UNSAFE_END
1197 
1198 // JSR166 ------------------------------------------------------------------
1199 
1200 UNSAFE_ENTRY(jboolean, Unsafe_CompareAndSwapObject(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject e_h, jobject x_h))
1201   UnsafeWrapper("Unsafe_CompareAndSwapObject");
1202   oop x = JNIHandles::resolve(x_h);
1203   oop e = JNIHandles::resolve(e_h);
1204   oop p = JNIHandles::resolve(obj);
1205   HeapWord* addr = (HeapWord *)index_oop_from_field_offset_long(p, offset);
1206   oop res = oopDesc::atomic_compare_exchange_oop(x, addr, e, true);
1207   jboolean success  = (res == e);
1208   if (success)
1209     update_barrier_set((void*)addr, x);
1210   return success;
1211 UNSAFE_END
1212 
1213 UNSAFE_ENTRY(jboolean, Unsafe_CompareAndSwapInt(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jint e, jint x))
1214   UnsafeWrapper("Unsafe_CompareAndSwapInt");
1215   oop p = JNIHandles::resolve(obj);
1216   jint* addr = (jint *) index_oop_from_field_offset_long(p, offset);
1217   return (jint)(Atomic::cmpxchg(x, addr, e)) == e;
1218 UNSAFE_END
1219 
1220 UNSAFE_ENTRY(jboolean, Unsafe_CompareAndSwapLong(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jlong e, jlong x))
1221   UnsafeWrapper("Unsafe_CompareAndSwapLong");
1222   Handle p (THREAD, JNIHandles::resolve(obj));
1223   jlong* addr = (jlong*)(index_oop_from_field_offset_long(p(), offset));
1224 #ifdef SUPPORTS_NATIVE_CX8
1225   return (jlong)(Atomic::cmpxchg(x, addr, e)) == e;
1226 #else
1227   if (VM_Version::supports_cx8())
1228     return (jlong)(Atomic::cmpxchg(x, addr, e)) == e;
1229   else {
1230     jboolean success = false;
1231     MutexLockerEx mu(UnsafeJlong_lock, Mutex::_no_safepoint_check_flag);
1232     jlong val = Atomic::load(addr);
1233     if (val == e) { Atomic::store(x, addr); success = true; }
1234     return success;
1235   }
1236 #endif
1237 UNSAFE_END
1238 
1239 static void post_thread_park_event(EventThreadPark* event, const oop obj, jlong timeout) {
1240   assert(event != NULL, "invariant");
1241   assert(event->should_commit(), "invariant");
1242   event->set_parkedClass((obj != NULL) ? obj->klass() : NULL);
1243   event->set_timeout(timeout);
1244   event->set_address((obj != NULL) ? (u8)cast_from_oop<uintptr_t>(obj) : 0);
1245   event->commit();
1246 }
1247 
1248 UNSAFE_ENTRY(void, Unsafe_Park(JNIEnv *env, jobject unsafe, jboolean isAbsolute, jlong time))
1249   UnsafeWrapper("Unsafe_Park");
1250   EventThreadPark event;
1251 #ifndef USDT2
1252   HS_DTRACE_PROBE3(hotspot, thread__park__begin, thread->parker(), (int) isAbsolute, time);
1253 #else /* USDT2 */
1254    HOTSPOT_THREAD_PARK_BEGIN(
1255                              (uintptr_t) thread->parker(), (int) isAbsolute, time);
1256 #endif /* USDT2 */
1257   JavaThreadParkedState jtps(thread, time != 0);
1258   thread->parker()->park(isAbsolute != 0, time);
1259 #ifndef USDT2
1260   HS_DTRACE_PROBE1(hotspot, thread__park__end, thread->parker());
1261 #else /* USDT2 */
1262   HOTSPOT_THREAD_PARK_END(
1263                           (uintptr_t) thread->parker());
1264 #endif /* USDT2 */
1265   if (event.should_commit()) {
1266     post_thread_park_event(&event, thread->current_park_blocker(), time);
1267   }
1268 UNSAFE_END
1269 
1270 UNSAFE_ENTRY(void, Unsafe_Unpark(JNIEnv *env, jobject unsafe, jobject jthread))
1271   UnsafeWrapper("Unsafe_Unpark");
1272   Parker* p = NULL;
1273   if (jthread != NULL) {
1274     oop java_thread = JNIHandles::resolve_non_null(jthread);
1275     if (java_thread != NULL) {
1276       jlong lp = java_lang_Thread::park_event(java_thread);
1277       if (lp != 0) {
1278         // This cast is OK even though the jlong might have been read
1279         // non-atomically on 32bit systems, since there, one word will
1280         // always be zero anyway and the value set is always the same
1281         p = (Parker*)addr_from_java(lp);
1282       } else {
1283         // Grab lock if apparently null or using older version of library
1284         MutexLocker mu(Threads_lock);
1285         java_thread = JNIHandles::resolve_non_null(jthread);
1286         if (java_thread != NULL) {
1287           JavaThread* thr = java_lang_Thread::thread(java_thread);
1288           if (thr != NULL) {
1289             p = thr->parker();
1290             if (p != NULL) { // Bind to Java thread for next time.
1291               java_lang_Thread::set_park_event(java_thread, addr_to_java(p));
1292             }
1293           }
1294         }
1295       }
1296     }
1297   }
1298   if (p != NULL) {
1299 #ifndef USDT2
1300     HS_DTRACE_PROBE1(hotspot, thread__unpark, p);
1301 #else /* USDT2 */
1302     HOTSPOT_THREAD_UNPARK(
1303                           (uintptr_t) p);
1304 #endif /* USDT2 */
1305     p->unpark();
1306   }
1307 UNSAFE_END
1308 
1309 UNSAFE_ENTRY(jint, Unsafe_Loadavg(JNIEnv *env, jobject unsafe, jdoubleArray loadavg, jint nelem))
1310   UnsafeWrapper("Unsafe_Loadavg");
1311   const int max_nelem = 3;
1312   double la[max_nelem];
1313   jint ret;
1314 
1315   typeArrayOop a = typeArrayOop(JNIHandles::resolve_non_null(loadavg));
1316   assert(a->is_typeArray(), "must be type array");
1317 
1318   if (nelem < 0 || nelem > max_nelem || a->length() < nelem) {
1319     ThreadToNativeFromVM ttnfv(thread);
1320     throw_new(env, "ArrayIndexOutOfBoundsException");
1321     return -1;
1322   }
1323 
1324   ret = os::loadavg(la, nelem);
1325   if (ret == -1) return -1;
1326 
1327   // if successful, ret is the number of samples actually retrieved.
1328   assert(ret >= 0 && ret <= max_nelem, "Unexpected loadavg return value");
1329   switch(ret) {
1330     case 3: a->double_at_put(2, (jdouble)la[2]); // fall through
1331     case 2: a->double_at_put(1, (jdouble)la[1]); // fall through
1332     case 1: a->double_at_put(0, (jdouble)la[0]); break;
1333   }
1334   return ret;
1335 UNSAFE_END
1336 
1337 UNSAFE_ENTRY(void, Unsafe_PrefetchRead(JNIEnv* env, jclass ignored, jobject obj, jlong offset))
1338   UnsafeWrapper("Unsafe_PrefetchRead");
1339   oop p = JNIHandles::resolve(obj);
1340   void* addr = index_oop_from_field_offset_long(p, 0);
1341   Prefetch::read(addr, (intx)offset);
1342 UNSAFE_END
1343 
1344 UNSAFE_ENTRY(void, Unsafe_PrefetchWrite(JNIEnv* env, jclass ignored, jobject obj, jlong offset))
1345   UnsafeWrapper("Unsafe_PrefetchWrite");
1346   oop p = JNIHandles::resolve(obj);
1347   void* addr = index_oop_from_field_offset_long(p, 0);
1348   Prefetch::write(addr, (intx)offset);
1349 UNSAFE_END
1350 
1351 
1352 /// JVM_RegisterUnsafeMethods
1353 
1354 #define ADR "J"
1355 
1356 #define LANG "Ljava/lang/"
1357 
1358 #define OBJ LANG "Object;"
1359 #define CLS LANG "Class;"
1360 #define CTR LANG "reflect/Constructor;"
1361 #define FLD LANG "reflect/Field;"
1362 #define MTH LANG "reflect/Method;"
1363 #define THR LANG "Throwable;"
1364 
1365 #define DC0_Args LANG "String;[BII"
1366 #define DC_Args  DC0_Args LANG "ClassLoader;" "Ljava/security/ProtectionDomain;"
1367 
1368 #define CC (char*)  /*cast a literal from (const char*)*/
1369 #define FN_PTR(f) CAST_FROM_FN_PTR(void*, &f)
1370 
1371 // define deprecated accessors for compabitility with 1.4.0
1372 #define DECLARE_GETSETOOP_140(Boolean, Z) \
1373     {CC "get" #Boolean,      CC "(" OBJ "I)" #Z,      FN_PTR(Unsafe_Get##Boolean##140)}, \
1374     {CC "put" #Boolean,      CC "(" OBJ "I" #Z ")V",   FN_PTR(Unsafe_Set##Boolean##140)}
1375 
1376 // Note:  In 1.4.1, getObject and kin take both int and long offsets.
1377 #define DECLARE_GETSETOOP_141(Boolean, Z) \
1378     {CC "get" #Boolean,      CC "(" OBJ "J)" #Z,      FN_PTR(Unsafe_Get##Boolean)}, \
1379     {CC "put" #Boolean,      CC "(" OBJ "J" #Z ")V",   FN_PTR(Unsafe_Set##Boolean)}
1380 
1381 // Note:  In 1.5.0, there are volatile versions too
1382 #define DECLARE_GETSETOOP(Boolean, Z) \
1383     {CC "get" #Boolean,      CC "(" OBJ "J)" #Z,      FN_PTR(Unsafe_Get##Boolean)}, \
1384     {CC "put" #Boolean,      CC "(" OBJ "J" #Z ")V",   FN_PTR(Unsafe_Set##Boolean)}, \
1385     {CC "get" #Boolean "Volatile",      CC "(" OBJ "J)" #Z,      FN_PTR(Unsafe_Get##Boolean##Volatile)}, \
1386     {CC "put" #Boolean "Volatile",      CC "(" OBJ "J" #Z ")V",   FN_PTR(Unsafe_Set##Boolean##Volatile)}
1387 
1388 
1389 #define DECLARE_GETSETNATIVE(Byte, B) \
1390     {CC "get" #Byte,         CC "(" ADR ")" #B,       FN_PTR(Unsafe_GetNative##Byte)}, \
1391     {CC "put" #Byte,         CC "(" ADR#B ")V",      FN_PTR(Unsafe_SetNative##Byte)}
1392 
1393 
1394 
1395 // These are the methods for 1.4.0
1396 static JNINativeMethod methods_140[] = {
1397     {CC "getObject",        CC "(" OBJ "I)" OBJ "",   FN_PTR(Unsafe_GetObject140)},
1398     {CC "putObject",        CC "(" OBJ "I" OBJ ")V",  FN_PTR(Unsafe_SetObject140)},
1399 
1400     DECLARE_GETSETOOP_140(Boolean, Z),
1401     DECLARE_GETSETOOP_140(Byte, B),
1402     DECLARE_GETSETOOP_140(Short, S),
1403     DECLARE_GETSETOOP_140(Char, C),
1404     DECLARE_GETSETOOP_140(Int, I),
1405     DECLARE_GETSETOOP_140(Long, J),
1406     DECLARE_GETSETOOP_140(Float, F),
1407     DECLARE_GETSETOOP_140(Double, D),
1408 
1409     DECLARE_GETSETNATIVE(Byte, B),
1410     DECLARE_GETSETNATIVE(Short, S),
1411     DECLARE_GETSETNATIVE(Char, C),
1412     DECLARE_GETSETNATIVE(Int, I),
1413     DECLARE_GETSETNATIVE(Long, J),
1414     DECLARE_GETSETNATIVE(Float, F),
1415     DECLARE_GETSETNATIVE(Double, D),
1416 
1417     {CC "getAddress",         CC "(" ADR ")" ADR,             FN_PTR(Unsafe_GetNativeAddress)},
1418     {CC "putAddress",         CC "(" ADR "" ADR ")V",          FN_PTR(Unsafe_SetNativeAddress)},
1419 
1420     {CC "allocateMemory",     CC "(J)" ADR,                 FN_PTR(Unsafe_AllocateMemory)},
1421     {CC "reallocateMemory",   CC "(" ADR "J)" ADR,            FN_PTR(Unsafe_ReallocateMemory)},
1422     {CC "freeMemory",         CC "(" ADR ")V",               FN_PTR(Unsafe_FreeMemory)},
1423 
1424     {CC "fieldOffset",        CC "(" FLD ")I",               FN_PTR(Unsafe_FieldOffset)},
1425     {CC "staticFieldBase",    CC "(" CLS ")" OBJ,             FN_PTR(Unsafe_StaticFieldBaseFromClass)},
1426     {CC "ensureClassInitialized",CC "(" CLS ")V",            FN_PTR(Unsafe_EnsureClassInitialized)},
1427     {CC "arrayBaseOffset",    CC "(" CLS ")I",               FN_PTR(Unsafe_ArrayBaseOffset)},
1428     {CC "arrayIndexScale",    CC "(" CLS ")I",               FN_PTR(Unsafe_ArrayIndexScale)},
1429     {CC "addressSize",        CC "()I",                    FN_PTR(Unsafe_AddressSize)},
1430     {CC "pageSize",           CC "()I",                    FN_PTR(Unsafe_PageSize)},
1431 
1432     {CC "defineClass",        CC "(" DC0_Args ")" CLS,        FN_PTR(Unsafe_DefineClass0)},
1433     {CC "defineClass",        CC "(" DC_Args ")" CLS,         FN_PTR(Unsafe_DefineClass)},
1434     {CC "allocateInstance",   CC "(" CLS ")" OBJ,             FN_PTR(Unsafe_AllocateInstance)},
1435     {CC "monitorEnter",       CC "(" OBJ ")V",               FN_PTR(Unsafe_MonitorEnter)},
1436     {CC "monitorExit",        CC "(" OBJ ")V",               FN_PTR(Unsafe_MonitorExit)},
1437     {CC "throwException",     CC "(" THR ")V",               FN_PTR(Unsafe_ThrowException)}
1438 };
1439 
1440 // These are the methods prior to the JSR 166 changes in 1.5.0
1441 static JNINativeMethod methods_141[] = {
1442     {CC "getObject",        CC "(" OBJ "J)" OBJ "",   FN_PTR(Unsafe_GetObject)},
1443     {CC "putObject",        CC "(" OBJ "J" OBJ ")V",  FN_PTR(Unsafe_SetObject)},
1444 
1445     DECLARE_GETSETOOP_141(Boolean, Z),
1446     DECLARE_GETSETOOP_141(Byte, B),
1447     DECLARE_GETSETOOP_141(Short, S),
1448     DECLARE_GETSETOOP_141(Char, C),
1449     DECLARE_GETSETOOP_141(Int, I),
1450     DECLARE_GETSETOOP_141(Long, J),
1451     DECLARE_GETSETOOP_141(Float, F),
1452     DECLARE_GETSETOOP_141(Double, D),
1453 
1454     DECLARE_GETSETNATIVE(Byte, B),
1455     DECLARE_GETSETNATIVE(Short, S),
1456     DECLARE_GETSETNATIVE(Char, C),
1457     DECLARE_GETSETNATIVE(Int, I),
1458     DECLARE_GETSETNATIVE(Long, J),
1459     DECLARE_GETSETNATIVE(Float, F),
1460     DECLARE_GETSETNATIVE(Double, D),
1461 
1462     {CC "getAddress",         CC "(" ADR ")" ADR,             FN_PTR(Unsafe_GetNativeAddress)},
1463     {CC "putAddress",         CC "(" ADR "" ADR ")V",          FN_PTR(Unsafe_SetNativeAddress)},
1464 
1465     {CC "allocateMemory",     CC "(J)" ADR,                 FN_PTR(Unsafe_AllocateMemory)},
1466     {CC "reallocateMemory",   CC "(" ADR "J)" ADR,            FN_PTR(Unsafe_ReallocateMemory)},
1467     {CC "freeMemory",         CC "(" ADR ")V",               FN_PTR(Unsafe_FreeMemory)},
1468 
1469     {CC "objectFieldOffset",  CC "(" FLD ")J",               FN_PTR(Unsafe_ObjectFieldOffset)},
1470     {CC "staticFieldOffset",  CC "(" FLD ")J",               FN_PTR(Unsafe_StaticFieldOffset)},
1471     {CC "staticFieldBase",    CC "(" FLD ")" OBJ,             FN_PTR(Unsafe_StaticFieldBaseFromField)},
1472     {CC "ensureClassInitialized",CC "(" CLS ")V",            FN_PTR(Unsafe_EnsureClassInitialized)},
1473     {CC "arrayBaseOffset",    CC "(" CLS ")I",               FN_PTR(Unsafe_ArrayBaseOffset)},
1474     {CC "arrayIndexScale",    CC "(" CLS ")I",               FN_PTR(Unsafe_ArrayIndexScale)},
1475     {CC "addressSize",        CC "()I",                    FN_PTR(Unsafe_AddressSize)},
1476     {CC "pageSize",           CC "()I",                    FN_PTR(Unsafe_PageSize)},
1477 
1478     {CC "defineClass",        CC "(" DC0_Args ")" CLS,        FN_PTR(Unsafe_DefineClass0)},
1479     {CC "defineClass",        CC "(" DC_Args ")" CLS,         FN_PTR(Unsafe_DefineClass)},
1480     {CC "allocateInstance",   CC "(" CLS ")" OBJ,             FN_PTR(Unsafe_AllocateInstance)},
1481     {CC "monitorEnter",       CC "(" OBJ ")V",               FN_PTR(Unsafe_MonitorEnter)},
1482     {CC "monitorExit",        CC "(" OBJ ")V",               FN_PTR(Unsafe_MonitorExit)},
1483     {CC "throwException",     CC "(" THR ")V",               FN_PTR(Unsafe_ThrowException)}
1484 
1485 };
1486 
1487 // These are the methods prior to the JSR 166 changes in 1.6.0
1488 static JNINativeMethod methods_15[] = {
1489     {CC "getObject",        CC "(" OBJ "J)" OBJ "",   FN_PTR(Unsafe_GetObject)},
1490     {CC "putObject",        CC "(" OBJ "J" OBJ ")V",  FN_PTR(Unsafe_SetObject)},
1491     {CC "getObjectVolatile",CC "(" OBJ "J)" OBJ "",   FN_PTR(Unsafe_GetObjectVolatile)},
1492     {CC "putObjectVolatile",CC "(" OBJ "J" OBJ ")V",  FN_PTR(Unsafe_SetObjectVolatile)},
1493 
1494 
1495     DECLARE_GETSETOOP(Boolean, Z),
1496     DECLARE_GETSETOOP(Byte, B),
1497     DECLARE_GETSETOOP(Short, S),
1498     DECLARE_GETSETOOP(Char, C),
1499     DECLARE_GETSETOOP(Int, I),
1500     DECLARE_GETSETOOP(Long, J),
1501     DECLARE_GETSETOOP(Float, F),
1502     DECLARE_GETSETOOP(Double, D),
1503 
1504     DECLARE_GETSETNATIVE(Byte, B),
1505     DECLARE_GETSETNATIVE(Short, S),
1506     DECLARE_GETSETNATIVE(Char, C),
1507     DECLARE_GETSETNATIVE(Int, I),
1508     DECLARE_GETSETNATIVE(Long, J),
1509     DECLARE_GETSETNATIVE(Float, F),
1510     DECLARE_GETSETNATIVE(Double, D),
1511 
1512     {CC "getAddress",         CC "(" ADR ")" ADR,             FN_PTR(Unsafe_GetNativeAddress)},
1513     {CC "putAddress",         CC "(" ADR "" ADR ")V",          FN_PTR(Unsafe_SetNativeAddress)},
1514 
1515     {CC "allocateMemory",     CC "(J)" ADR,                 FN_PTR(Unsafe_AllocateMemory)},
1516     {CC "reallocateMemory",   CC "(" ADR "J)" ADR,            FN_PTR(Unsafe_ReallocateMemory)},
1517     {CC "freeMemory",         CC "(" ADR ")V",               FN_PTR(Unsafe_FreeMemory)},
1518 
1519     {CC "objectFieldOffset",  CC "(" FLD ")J",               FN_PTR(Unsafe_ObjectFieldOffset)},
1520     {CC "staticFieldOffset",  CC "(" FLD ")J",               FN_PTR(Unsafe_StaticFieldOffset)},
1521     {CC "staticFieldBase",    CC "(" FLD ")" OBJ,             FN_PTR(Unsafe_StaticFieldBaseFromField)},
1522     {CC "ensureClassInitialized",CC "(" CLS ")V",            FN_PTR(Unsafe_EnsureClassInitialized)},
1523     {CC "arrayBaseOffset",    CC "(" CLS ")I",               FN_PTR(Unsafe_ArrayBaseOffset)},
1524     {CC "arrayIndexScale",    CC "(" CLS ")I",               FN_PTR(Unsafe_ArrayIndexScale)},
1525     {CC "addressSize",        CC "()I",                    FN_PTR(Unsafe_AddressSize)},
1526     {CC "pageSize",           CC "()I",                    FN_PTR(Unsafe_PageSize)},
1527 
1528     {CC "defineClass",        CC "(" DC0_Args ")" CLS,        FN_PTR(Unsafe_DefineClass0)},
1529     {CC "defineClass",        CC "(" DC_Args ")" CLS,         FN_PTR(Unsafe_DefineClass)},
1530     {CC "allocateInstance",   CC "(" CLS ")" OBJ,             FN_PTR(Unsafe_AllocateInstance)},
1531     {CC "monitorEnter",       CC "(" OBJ ")V",               FN_PTR(Unsafe_MonitorEnter)},
1532     {CC "monitorExit",        CC "(" OBJ ")V",               FN_PTR(Unsafe_MonitorExit)},
1533     {CC "throwException",     CC "(" THR ")V",               FN_PTR(Unsafe_ThrowException)},
1534     {CC "compareAndSwapObject", CC "(" OBJ "J" OBJ "" OBJ ")Z",  FN_PTR(Unsafe_CompareAndSwapObject)},
1535     {CC "compareAndSwapInt",  CC "(" OBJ "J""I""I"")Z",      FN_PTR(Unsafe_CompareAndSwapInt)},
1536     {CC "compareAndSwapLong", CC "(" OBJ "J""J""J"")Z",      FN_PTR(Unsafe_CompareAndSwapLong)},
1537     {CC "park",               CC "(ZJ)V",                  FN_PTR(Unsafe_Park)},
1538     {CC "unpark",             CC "(" OBJ ")V",               FN_PTR(Unsafe_Unpark)}
1539 
1540 };
1541 
1542 // These are the methods for 1.6.0 and 1.7.0
1543 static JNINativeMethod methods_16[] = {
1544     {CC "getObject",        CC "(" OBJ "J)" OBJ "",   FN_PTR(Unsafe_GetObject)},
1545     {CC "putObject",        CC "(" OBJ "J" OBJ ")V",  FN_PTR(Unsafe_SetObject)},
1546     {CC "getObjectVolatile",CC "(" OBJ "J)" OBJ "",   FN_PTR(Unsafe_GetObjectVolatile)},
1547     {CC "putObjectVolatile",CC "(" OBJ "J" OBJ ")V",  FN_PTR(Unsafe_SetObjectVolatile)},
1548 
1549     DECLARE_GETSETOOP(Boolean, Z),
1550     DECLARE_GETSETOOP(Byte, B),
1551     DECLARE_GETSETOOP(Short, S),
1552     DECLARE_GETSETOOP(Char, C),
1553     DECLARE_GETSETOOP(Int, I),
1554     DECLARE_GETSETOOP(Long, J),
1555     DECLARE_GETSETOOP(Float, F),
1556     DECLARE_GETSETOOP(Double, D),
1557 
1558     DECLARE_GETSETNATIVE(Byte, B),
1559     DECLARE_GETSETNATIVE(Short, S),
1560     DECLARE_GETSETNATIVE(Char, C),
1561     DECLARE_GETSETNATIVE(Int, I),
1562     DECLARE_GETSETNATIVE(Long, J),
1563     DECLARE_GETSETNATIVE(Float, F),
1564     DECLARE_GETSETNATIVE(Double, D),
1565 
1566     {CC "getAddress",         CC "(" ADR ")" ADR,             FN_PTR(Unsafe_GetNativeAddress)},
1567     {CC "putAddress",         CC "(" ADR "" ADR ")V",          FN_PTR(Unsafe_SetNativeAddress)},
1568 
1569     {CC "allocateMemory",     CC "(J)" ADR,                 FN_PTR(Unsafe_AllocateMemory)},
1570     {CC "reallocateMemory",   CC "(" ADR "J)" ADR,            FN_PTR(Unsafe_ReallocateMemory)},
1571     {CC "freeMemory",         CC "(" ADR ")V",               FN_PTR(Unsafe_FreeMemory)},
1572 
1573     {CC "objectFieldOffset",  CC "(" FLD ")J",               FN_PTR(Unsafe_ObjectFieldOffset)},
1574     {CC "staticFieldOffset",  CC "(" FLD ")J",               FN_PTR(Unsafe_StaticFieldOffset)},
1575     {CC "staticFieldBase",    CC "(" FLD ")" OBJ,             FN_PTR(Unsafe_StaticFieldBaseFromField)},
1576     {CC "ensureClassInitialized",CC "(" CLS ")V",            FN_PTR(Unsafe_EnsureClassInitialized)},
1577     {CC "arrayBaseOffset",    CC "(" CLS ")I",               FN_PTR(Unsafe_ArrayBaseOffset)},
1578     {CC "arrayIndexScale",    CC "(" CLS ")I",               FN_PTR(Unsafe_ArrayIndexScale)},
1579     {CC "addressSize",        CC "()I",                    FN_PTR(Unsafe_AddressSize)},
1580     {CC "pageSize",           CC "()I",                    FN_PTR(Unsafe_PageSize)},
1581 
1582     {CC "defineClass",        CC "(" DC0_Args ")" CLS,        FN_PTR(Unsafe_DefineClass0)},
1583     {CC "defineClass",        CC "(" DC_Args ")" CLS,         FN_PTR(Unsafe_DefineClass)},
1584     {CC "allocateInstance",   CC "(" CLS ")" OBJ,             FN_PTR(Unsafe_AllocateInstance)},
1585     {CC "monitorEnter",       CC "(" OBJ ")V",               FN_PTR(Unsafe_MonitorEnter)},
1586     {CC "monitorExit",        CC "(" OBJ ")V",               FN_PTR(Unsafe_MonitorExit)},
1587     {CC "tryMonitorEnter",    CC "(" OBJ ")Z",               FN_PTR(Unsafe_TryMonitorEnter)},
1588     {CC "throwException",     CC "(" THR ")V",               FN_PTR(Unsafe_ThrowException)},
1589     {CC "compareAndSwapObject", CC "(" OBJ "J" OBJ "" OBJ ")Z",  FN_PTR(Unsafe_CompareAndSwapObject)},
1590     {CC "compareAndSwapInt",  CC "(" OBJ "J""I""I"")Z",      FN_PTR(Unsafe_CompareAndSwapInt)},
1591     {CC "compareAndSwapLong", CC "(" OBJ "J""J""J"")Z",      FN_PTR(Unsafe_CompareAndSwapLong)},
1592     {CC "putOrderedObject",   CC "(" OBJ "J" OBJ ")V",         FN_PTR(Unsafe_SetOrderedObject)},
1593     {CC "putOrderedInt",      CC "(" OBJ "JI)V",             FN_PTR(Unsafe_SetOrderedInt)},
1594     {CC "putOrderedLong",     CC "(" OBJ "JJ)V",             FN_PTR(Unsafe_SetOrderedLong)},
1595     {CC "park",               CC "(ZJ)V",                  FN_PTR(Unsafe_Park)},
1596     {CC "unpark",             CC "(" OBJ ")V",               FN_PTR(Unsafe_Unpark)}
1597 };
1598 
1599 // These are the methods for 1.8.0
1600 static JNINativeMethod methods_18[] = {
1601     {CC "getObject",        CC "(" OBJ "J)" OBJ "",   FN_PTR(Unsafe_GetObject)},
1602     {CC "putObject",        CC "(" OBJ "J" OBJ ")V",  FN_PTR(Unsafe_SetObject)},
1603     {CC "getObjectVolatile",CC "(" OBJ "J)" OBJ "",   FN_PTR(Unsafe_GetObjectVolatile)},
1604     {CC "putObjectVolatile",CC "(" OBJ "J" OBJ ")V",  FN_PTR(Unsafe_SetObjectVolatile)},
1605 
1606     DECLARE_GETSETOOP(Boolean, Z),
1607     DECLARE_GETSETOOP(Byte, B),
1608     DECLARE_GETSETOOP(Short, S),
1609     DECLARE_GETSETOOP(Char, C),
1610     DECLARE_GETSETOOP(Int, I),
1611     DECLARE_GETSETOOP(Long, J),
1612     DECLARE_GETSETOOP(Float, F),
1613     DECLARE_GETSETOOP(Double, D),
1614 
1615     DECLARE_GETSETNATIVE(Byte, B),
1616     DECLARE_GETSETNATIVE(Short, S),
1617     DECLARE_GETSETNATIVE(Char, C),
1618     DECLARE_GETSETNATIVE(Int, I),
1619     DECLARE_GETSETNATIVE(Long, J),
1620     DECLARE_GETSETNATIVE(Float, F),
1621     DECLARE_GETSETNATIVE(Double, D),
1622 
1623     {CC "getAddress",         CC "(" ADR ")" ADR,             FN_PTR(Unsafe_GetNativeAddress)},
1624     {CC "putAddress",         CC "(" ADR "" ADR ")V",          FN_PTR(Unsafe_SetNativeAddress)},
1625 
1626     {CC "allocateMemory",     CC "(J)" ADR,                 FN_PTR(Unsafe_AllocateMemory)},
1627     {CC "reallocateMemory",   CC "(" ADR "J)" ADR,            FN_PTR(Unsafe_ReallocateMemory)},
1628     {CC "freeMemory",         CC "(" ADR ")V",               FN_PTR(Unsafe_FreeMemory)},
1629 
1630     {CC "objectFieldOffset",  CC "(" FLD ")J",               FN_PTR(Unsafe_ObjectFieldOffset)},
1631     {CC "staticFieldOffset",  CC "(" FLD ")J",               FN_PTR(Unsafe_StaticFieldOffset)},
1632     {CC "staticFieldBase",    CC "(" FLD ")" OBJ,             FN_PTR(Unsafe_StaticFieldBaseFromField)},
1633     {CC "ensureClassInitialized",CC "(" CLS ")V",            FN_PTR(Unsafe_EnsureClassInitialized)},
1634     {CC "arrayBaseOffset",    CC "(" CLS ")I",               FN_PTR(Unsafe_ArrayBaseOffset)},
1635     {CC "arrayIndexScale",    CC "(" CLS ")I",               FN_PTR(Unsafe_ArrayIndexScale)},
1636     {CC "addressSize",        CC "()I",                    FN_PTR(Unsafe_AddressSize)},
1637     {CC "pageSize",           CC "()I",                    FN_PTR(Unsafe_PageSize)},
1638 
1639     {CC "defineClass",        CC "(" DC_Args ")" CLS,         FN_PTR(Unsafe_DefineClass)},
1640     {CC "allocateInstance",   CC "(" CLS ")" OBJ,             FN_PTR(Unsafe_AllocateInstance)},
1641     {CC "monitorEnter",       CC "(" OBJ ")V",               FN_PTR(Unsafe_MonitorEnter)},
1642     {CC "monitorExit",        CC "(" OBJ ")V",               FN_PTR(Unsafe_MonitorExit)},
1643     {CC "tryMonitorEnter",    CC "(" OBJ ")Z",               FN_PTR(Unsafe_TryMonitorEnter)},
1644     {CC "throwException",     CC "(" THR ")V",               FN_PTR(Unsafe_ThrowException)},
1645     {CC "compareAndSwapObject", CC "(" OBJ "J" OBJ "" OBJ ")Z",  FN_PTR(Unsafe_CompareAndSwapObject)},
1646     {CC "compareAndSwapInt",  CC "(" OBJ "J""I""I"")Z",      FN_PTR(Unsafe_CompareAndSwapInt)},
1647     {CC "compareAndSwapLong", CC "(" OBJ "J""J""J"")Z",      FN_PTR(Unsafe_CompareAndSwapLong)},
1648     {CC "putOrderedObject",   CC "(" OBJ "J" OBJ ")V",         FN_PTR(Unsafe_SetOrderedObject)},
1649     {CC "putOrderedInt",      CC "(" OBJ "JI)V",             FN_PTR(Unsafe_SetOrderedInt)},
1650     {CC "putOrderedLong",     CC "(" OBJ "JJ)V",             FN_PTR(Unsafe_SetOrderedLong)},
1651     {CC "park",               CC "(ZJ)V",                  FN_PTR(Unsafe_Park)},
1652     {CC "unpark",             CC "(" OBJ ")V",               FN_PTR(Unsafe_Unpark)}
1653 };
1654 
1655 JNINativeMethod loadavg_method[] = {
1656     {CC "getLoadAverage",     CC "([DI)I",                 FN_PTR(Unsafe_Loadavg)}
1657 };
1658 
1659 JNINativeMethod prefetch_methods[] = {
1660     {CC "prefetchRead",       CC "(" OBJ "J)V",              FN_PTR(Unsafe_PrefetchRead)},
1661     {CC "prefetchWrite",      CC "(" OBJ "J)V",              FN_PTR(Unsafe_PrefetchWrite)},
1662     {CC "prefetchReadStatic", CC "(" OBJ "J)V",              FN_PTR(Unsafe_PrefetchRead)},
1663     {CC "prefetchWriteStatic",CC "(" OBJ "J)V",              FN_PTR(Unsafe_PrefetchWrite)}
1664 };
1665 
1666 JNINativeMethod memcopy_methods_17[] = {
1667     {CC "copyMemory",         CC "(" OBJ "J" OBJ "JJ)V",       FN_PTR(Unsafe_CopyMemory2)},
1668     {CC "setMemory",          CC "(" OBJ "JJB)V",            FN_PTR(Unsafe_SetMemory2)}
1669 };
1670 
1671 JNINativeMethod memcopy_methods_15[] = {
1672     {CC "setMemory",          CC "(" ADR "JB)V",             FN_PTR(Unsafe_SetMemory)},
1673     {CC "copyMemory",         CC "(" ADR ADR "J)V",          FN_PTR(Unsafe_CopyMemory)}
1674 };
1675 
1676 JNINativeMethod anonk_methods[] = {
1677     {CC "defineAnonymousClass", CC "(" DAC_Args ")" CLS,      FN_PTR(Unsafe_DefineAnonymousClass)},
1678 };
1679 
1680 JNINativeMethod lform_methods[] = {
1681     {CC "shouldBeInitialized",CC "(" CLS ")Z",               FN_PTR(Unsafe_ShouldBeInitialized)},
1682 };
1683 
1684 JNINativeMethod fence_methods[] = {
1685     {CC "loadFence",          CC "()V",                    FN_PTR(Unsafe_LoadFence)},
1686     {CC "storeFence",         CC "()V",                    FN_PTR(Unsafe_StoreFence)},
1687     {CC "fullFence",          CC "()V",                    FN_PTR(Unsafe_FullFence)},
1688 };
1689 
1690 #undef CC
1691 #undef FN_PTR
1692 
1693 #undef ADR
1694 #undef LANG
1695 #undef OBJ
1696 #undef CLS
1697 #undef CTR
1698 #undef FLD
1699 #undef MTH
1700 #undef THR
1701 #undef DC0_Args
1702 #undef DC_Args
1703 
1704 #undef DECLARE_GETSETOOP
1705 #undef DECLARE_GETSETNATIVE
1706 
1707 
1708 /**
1709  * Helper method to register native methods.
1710  */
1711 static bool register_natives(const char* message, JNIEnv* env, jclass clazz, const JNINativeMethod* methods, jint nMethods) {
1712   int status = env->RegisterNatives(clazz, methods, nMethods);
1713   if (status < 0 || env->ExceptionOccurred()) {
1714     if (PrintMiscellaneous && (Verbose || WizardMode)) {
1715       tty->print_cr("Unsafe:  failed registering %s", message);
1716     }
1717     env->ExceptionClear();
1718     return false;
1719   } else {
1720     if (PrintMiscellaneous && (Verbose || WizardMode)) {
1721       tty->print_cr("Unsafe:  successfully registered %s", message);
1722     }
1723     return true;
1724   }
1725 }
1726 
1727 
1728 // This one function is exported, used by NativeLookup.
1729 // The Unsafe_xxx functions above are called only from the interpreter.
1730 // The optimizer looks at names and signatures to recognize
1731 // individual functions.
1732 
1733 JVM_ENTRY(void, JVM_RegisterUnsafeMethods(JNIEnv *env, jclass unsafecls))
1734   UnsafeWrapper("JVM_RegisterUnsafeMethods");
1735   {
1736     ThreadToNativeFromVM ttnfv(thread);
1737 
1738     // Unsafe methods
1739     {
1740       bool success = false;
1741       // We need to register the 1.6 methods first because the 1.8 methods would register fine on 1.7 and 1.6
1742       if (!success) {
1743         success = register_natives("1.6 methods",   env, unsafecls, methods_16,  sizeof(methods_16)/sizeof(JNINativeMethod));
1744       }
1745       if (!success) {
1746         success = register_natives("1.8 methods",   env, unsafecls, methods_18,  sizeof(methods_18)/sizeof(JNINativeMethod));
1747       }
1748       if (!success) {
1749         success = register_natives("1.5 methods",   env, unsafecls, methods_15,  sizeof(methods_15)/sizeof(JNINativeMethod));
1750       }
1751       if (!success) {
1752         success = register_natives("1.4.1 methods", env, unsafecls, methods_141, sizeof(methods_141)/sizeof(JNINativeMethod));
1753       }
1754       if (!success) {
1755         success = register_natives("1.4.0 methods", env, unsafecls, methods_140, sizeof(methods_140)/sizeof(JNINativeMethod));
1756       }
1757       guarantee(success, "register unsafe natives");
1758     }
1759 
1760     // Unsafe.getLoadAverage
1761     register_natives("1.6 loadavg method", env, unsafecls, loadavg_method, sizeof(loadavg_method)/sizeof(JNINativeMethod));
1762 
1763     // Prefetch methods
1764     register_natives("1.6 prefetch methods", env, unsafecls, prefetch_methods, sizeof(prefetch_methods)/sizeof(JNINativeMethod));
1765 
1766     // Memory copy methods
1767     {
1768       bool success = false;
1769       if (!success) {
1770         success = register_natives("1.7 memory copy methods", env, unsafecls, memcopy_methods_17, sizeof(memcopy_methods_17)/sizeof(JNINativeMethod));
1771       }
1772       if (!success) {
1773         success = register_natives("1.5 memory copy methods", env, unsafecls, memcopy_methods_15, sizeof(memcopy_methods_15)/sizeof(JNINativeMethod));
1774       }
1775     }
1776 
1777     // Unsafe.defineAnonymousClass
1778     if (EnableInvokeDynamic) {
1779       register_natives("1.7 define anonymous class method", env, unsafecls, anonk_methods, sizeof(anonk_methods)/sizeof(JNINativeMethod));
1780     }
1781 
1782     // Unsafe.shouldBeInitialized
1783     if (EnableInvokeDynamic) {
1784       register_natives("1.7 LambdaForm support", env, unsafecls, lform_methods, sizeof(lform_methods)/sizeof(JNINativeMethod));
1785     }
1786 
1787     // Fence methods
1788     register_natives("1.8 fence methods", env, unsafecls, fence_methods, sizeof(fence_methods)/sizeof(JNINativeMethod));
1789   }
1790 JVM_END