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