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