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