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 "runtime/atomic.inline.hpp"
  33 #include "runtime/globals.hpp"
  34 #include "runtime/interfaceSupport.hpp"
  35 #include "runtime/orderAccess.inline.hpp"
  36 #include "runtime/reflection.hpp"
  37 #include "runtime/vm_version.hpp"
  38 #include "services/threadService.hpp"
  39 #include "trace/tracing.hpp"
  40 #include "utilities/copy.hpp"
  41 #include "utilities/dtrace.hpp"
  42 #include "utilities/macros.hpp"

  43 #if INCLUDE_ALL_GCS
  44 #include "gc/g1/g1SATBCardTableModRefBS.hpp"
  45 #endif // INCLUDE_ALL_GCS
  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 
 176 // Get/SetObject must be special-cased, since it works with handles.
 177 
 178 // These functions allow a null base pointer with an arbitrary address.
 179 // But if the base pointer is non-null, the offset should make some sense.
 180 // That is, it should be in the range [0, MAX_OBJECT_SIZE].
 181 UNSAFE_ENTRY(jobject, Unsafe_GetObject(JNIEnv *env, jobject unsafe, jobject obj, jlong offset))
 182   UnsafeWrapper("Unsafe_GetObject");
 183   oop p = JNIHandles::resolve(obj);
 184   oop v;
 185   if (UseCompressedOops) {
 186     narrowOop n = *(narrowOop*)index_oop_from_field_offset_long(p, offset);
 187     v = oopDesc::decode_heap_oop(n);
 188   } else {
 189     v = *(oop*)index_oop_from_field_offset_long(p, offset);
 190   }
 191   jobject ret = JNIHandles::make_local(env, v);
 192 #if INCLUDE_ALL_GCS
 193   // We could be accessing the referent field in a reference
 194   // object. If G1 is enabled then we need to register non-null
 195   // referent with the SATB barrier.
 196   if (UseG1GC) {
 197     bool needs_barrier = false;
 198 
 199     if (ret != NULL) {
 200       if (offset == java_lang_ref_Reference::referent_offset && obj != NULL) {
 201         oop o = JNIHandles::resolve(obj);
 202         Klass* k = o->klass();
 203         if (InstanceKlass::cast(k)->reference_type() != REF_NONE) {
 204           assert(InstanceKlass::cast(k)->is_subclass_of(SystemDictionary::Reference_klass()), "sanity");
 205           needs_barrier = true;
 206         }
 207       }
 208     }
 209 
 210     if (needs_barrier) {
 211       oop referent = JNIHandles::resolve(ret);
 212       G1SATBCardTableModRefBS::enqueue(referent);
 213     }
 214   }
 215 #endif // INCLUDE_ALL_GCS
 216   return ret;
 217 UNSAFE_END
 218 
 219 UNSAFE_ENTRY(void, Unsafe_SetObject(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject x_h))
 220   UnsafeWrapper("Unsafe_SetObject");

 221   oop x = JNIHandles::resolve(x_h);
 222   oop p = JNIHandles::resolve(obj);
 223   if (UseCompressedOops) {
 224     oop_store((narrowOop*)index_oop_from_field_offset_long(p, offset), x);
 225   } else {
 226     oop_store((oop*)index_oop_from_field_offset_long(p, offset), x);
 227   }
 228 UNSAFE_END
 229 
 230 UNSAFE_ENTRY(jobject, Unsafe_GetObjectVolatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset))
 231   UnsafeWrapper("Unsafe_GetObjectVolatile");
 232   oop p = JNIHandles::resolve(obj);
 233   void* addr = index_oop_from_field_offset_long(p, offset);
 234   volatile oop v;
 235   if (UseCompressedOops) {
 236     volatile narrowOop n = *(volatile narrowOop*) addr;
 237     (void)const_cast<oop&>(v = oopDesc::decode_heap_oop(n));
 238   } else {
 239     (void)const_cast<oop&>(v = *(volatile oop*) addr);
 240   }
 241   OrderAccess::acquire();
 242   return JNIHandles::make_local(env, v);
 243 UNSAFE_END
 244 
 245 UNSAFE_ENTRY(void, Unsafe_SetObjectVolatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject x_h))
 246   UnsafeWrapper("Unsafe_SetObjectVolatile");

 247   oop x = JNIHandles::resolve(x_h);
 248   oop p = JNIHandles::resolve(obj);
 249   void* addr = index_oop_from_field_offset_long(p, offset);
 250   OrderAccess::release();
 251   if (UseCompressedOops) {
 252     oop_store((narrowOop*)addr, x);
 253   } else {
 254     oop_store((oop*)addr, x);
 255   }
 256   OrderAccess::fence();
 257 UNSAFE_END
 258 
 259 UNSAFE_ENTRY(jobject, Unsafe_GetUncompressedObject(JNIEnv *env, jobject unsafe, jlong addr))
 260   UnsafeWrapper("Unsafe_GetUncompressedObject");
 261   oop v = *(oop*) (address) addr;
 262   return JNIHandles::make_local(env, v);
 263 UNSAFE_END
 264 
 265 UNSAFE_ENTRY(jclass, Unsafe_GetJavaMirror(JNIEnv *env, jobject unsafe, jlong metaspace_klass))
 266   UnsafeWrapper("Unsafe_GetJavaMirror");
 267   Klass* klass = (Klass*) (address) metaspace_klass;
 268   return (jclass) JNIHandles::make_local(klass->java_mirror());
 269 UNSAFE_END
 270 
 271 UNSAFE_ENTRY(jlong, Unsafe_GetKlassPointer(JNIEnv *env, jobject unsafe, jobject obj))
 272   UnsafeWrapper("Unsafe_GetKlassPointer");
 273   oop o = JNIHandles::resolve(obj);
 274   jlong klass = (jlong) (address) o->klass();
 275   return klass;
 276 UNSAFE_END
 277 
 278 #ifndef SUPPORTS_NATIVE_CX8
 279 
 280 // VM_Version::supports_cx8() is a surrogate for 'supports atomic long memory ops'.
 281 //
 282 // On platforms which do not support atomic compare-and-swap of jlong (8 byte)
 283 // values we have to use a lock-based scheme to enforce atomicity. This has to be
 284 // applied to all Unsafe operations that set the value of a jlong field. Even so
 285 // the compareAndSwapLong operation will not be atomic with respect to direct stores
 286 // to the field from Java code. It is important therefore that any Java code that
 287 // utilizes these Unsafe jlong operations does not perform direct stores. To permit
 288 // direct loads of the field from Java code we must also use Atomic::store within the
 289 // locked regions. And for good measure, in case there are direct stores, we also
 290 // employ Atomic::load within those regions. Note that the field in question must be
 291 // volatile and so must have atomic load/store accesses applied at the Java level.
 292 //
 293 // The locking scheme could utilize a range of strategies for controlling the locking
 294 // granularity: from a lock per-field through to a single global lock. The latter is
 295 // the simplest and is used for the current implementation. Note that the Java object
 296 // that contains the field, can not, in general, be used for locking. To do so can lead
 297 // to deadlocks as we may introduce locking into what appears to the Java code to be a
 298 // lock-free path.
 299 //
 300 // As all the locked-regions are very short and themselves non-blocking we can treat
 301 // them as leaf routines and elide safepoint checks (ie we don't perform any thread
 302 // state transitions even when blocking for the lock). Note that if we do choose to
 303 // add safepoint checks and thread state transitions, we must ensure that we calculate
 304 // the address of the field _after_ we have acquired the lock, else the object may have
 305 // been moved by the GC
 306 
 307 UNSAFE_ENTRY(jlong, Unsafe_GetLongVolatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset))
 308   UnsafeWrapper("Unsafe_GetLongVolatile");
 309   {
 310     if (VM_Version::supports_cx8()) {
 311       GET_FIELD_VOLATILE(obj, offset, jlong, v);
 312       return v;
 313     }
 314     else {
 315       Handle p (THREAD, JNIHandles::resolve(obj));
 316       jlong* addr = (jlong*)(index_oop_from_field_offset_long(p(), offset));
 317       MutexLockerEx mu(UnsafeJlong_lock, Mutex::_no_safepoint_check_flag);
 318       jlong value = Atomic::load(addr);
 319       return value;
 320     }
 321   }
 322 UNSAFE_END
 323 
 324 UNSAFE_ENTRY(void, Unsafe_SetLongVolatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jlong x))
 325   UnsafeWrapper("Unsafe_SetLongVolatile");
 326   {
 327     if (VM_Version::supports_cx8()) {
 328       SET_FIELD_VOLATILE(obj, offset, jlong, x);
 329     }
 330     else {
 331       Handle p (THREAD, JNIHandles::resolve(obj));
 332       jlong* addr = (jlong*)(index_oop_from_field_offset_long(p(), offset));
 333       MutexLockerEx mu(UnsafeJlong_lock, Mutex::_no_safepoint_check_flag);
 334       Atomic::store(x, addr);
 335     }
 336   }
 337 UNSAFE_END
 338 
 339 #endif // not SUPPORTS_NATIVE_CX8
 340 
 341 UNSAFE_ENTRY(jboolean, Unsafe_isBigEndian0(JNIEnv *env, jobject unsafe))
 342   UnsafeWrapper("Unsafe_IsBigEndian0");
 343   {
 344 #ifdef VM_LITTLE_ENDIAN
 345     return false;
 346 #else
 347     return true;
 348 #endif
 349   }
 350 UNSAFE_END
 351 
 352 UNSAFE_ENTRY(jint, Unsafe_unalignedAccess0(JNIEnv *env, jobject unsafe))
 353   UnsafeWrapper("Unsafe_UnalignedAccess0");
 354   {
 355     return UseUnalignedAccesses;
 356   }
 357 UNSAFE_END
 358 
 359 #define DEFINE_GETSETOOP(jboolean, Boolean) \
 360  \
 361 UNSAFE_ENTRY(jboolean, Unsafe_Get##Boolean##140(JNIEnv *env, jobject unsafe, jobject obj, jint offset)) \
 362   UnsafeWrapper("Unsafe_Get"#Boolean); \
 363   if (obj == NULL)  THROW_0(vmSymbols::java_lang_NullPointerException()); \
 364   GET_FIELD(obj, offset, jboolean, v); \
 365   return v; \
 366 UNSAFE_END \
 367  \
 368 UNSAFE_ENTRY(void, Unsafe_Set##Boolean##140(JNIEnv *env, jobject unsafe, jobject obj, jint offset, jboolean x)) \
 369   UnsafeWrapper("Unsafe_Set"#Boolean); \
 370   if (obj == NULL)  THROW(vmSymbols::java_lang_NullPointerException()); \
 371   SET_FIELD(obj, offset, jboolean, x); \
 372 UNSAFE_END \
 373  \
 374 UNSAFE_ENTRY(jboolean, Unsafe_Get##Boolean(JNIEnv *env, jobject unsafe, jobject obj, jlong offset)) \
 375   UnsafeWrapper("Unsafe_Get"#Boolean); \
 376   GET_FIELD(obj, offset, jboolean, v); \
 377   return v; \
 378 UNSAFE_END \
 379  \
 380 UNSAFE_ENTRY(void, Unsafe_Set##Boolean(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jboolean x)) \
 381   UnsafeWrapper("Unsafe_Set"#Boolean); \
 382   SET_FIELD(obj, offset, jboolean, x); \
 383 UNSAFE_END \
 384  \
 385 // END DEFINE_GETSETOOP.
 386 
 387 DEFINE_GETSETOOP(jboolean, Boolean)
 388 DEFINE_GETSETOOP(jbyte, Byte)
 389 DEFINE_GETSETOOP(jshort, Short);
 390 DEFINE_GETSETOOP(jchar, Char);
 391 DEFINE_GETSETOOP(jint, Int);
 392 DEFINE_GETSETOOP(jlong, Long);
 393 DEFINE_GETSETOOP(jfloat, Float);
 394 DEFINE_GETSETOOP(jdouble, Double);
 395 
 396 #undef DEFINE_GETSETOOP
 397 
 398 #define DEFINE_GETSETOOP_VOLATILE(jboolean, Boolean) \
 399  \
 400 UNSAFE_ENTRY(jboolean, Unsafe_Get##Boolean##Volatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset)) \
 401   UnsafeWrapper("Unsafe_Get"#Boolean); \
 402   GET_FIELD_VOLATILE(obj, offset, jboolean, v); \
 403   return v; \
 404 UNSAFE_END \
 405  \
 406 UNSAFE_ENTRY(void, Unsafe_Set##Boolean##Volatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jboolean x)) \
 407   UnsafeWrapper("Unsafe_Set"#Boolean); \
 408   SET_FIELD_VOLATILE(obj, offset, jboolean, x); \
 409 UNSAFE_END \
 410  \
 411 // END DEFINE_GETSETOOP_VOLATILE.
 412 
 413 DEFINE_GETSETOOP_VOLATILE(jboolean, Boolean)
 414 DEFINE_GETSETOOP_VOLATILE(jbyte, Byte)
 415 DEFINE_GETSETOOP_VOLATILE(jshort, Short);
 416 DEFINE_GETSETOOP_VOLATILE(jchar, Char);
 417 DEFINE_GETSETOOP_VOLATILE(jint, Int);
 418 DEFINE_GETSETOOP_VOLATILE(jfloat, Float);
 419 DEFINE_GETSETOOP_VOLATILE(jdouble, Double);
 420 
 421 #ifdef SUPPORTS_NATIVE_CX8
 422 DEFINE_GETSETOOP_VOLATILE(jlong, Long);
 423 #endif
 424 
 425 #undef DEFINE_GETSETOOP_VOLATILE
 426 
 427 // The non-intrinsified versions of setOrdered just use setVolatile
 428 
 429 UNSAFE_ENTRY(void, Unsafe_SetOrderedInt(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jint x))
 430   UnsafeWrapper("Unsafe_SetOrderedInt");
 431   SET_FIELD_VOLATILE(obj, offset, jint, x);
 432 UNSAFE_END
 433 
 434 UNSAFE_ENTRY(void, Unsafe_SetOrderedObject(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject x_h))
 435   UnsafeWrapper("Unsafe_SetOrderedObject");
 436   oop x = JNIHandles::resolve(x_h);
 437   oop p = JNIHandles::resolve(obj);
 438   void* addr = index_oop_from_field_offset_long(p, offset);
 439   OrderAccess::release();
 440   if (UseCompressedOops) {
 441     oop_store((narrowOop*)addr, x);
 442   } else {
 443     oop_store((oop*)addr, x);
 444   }
 445   OrderAccess::fence();
 446 UNSAFE_END
 447 
 448 UNSAFE_ENTRY(void, Unsafe_SetOrderedLong(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jlong x))
 449   UnsafeWrapper("Unsafe_SetOrderedLong");
 450 #ifdef SUPPORTS_NATIVE_CX8
 451   SET_FIELD_VOLATILE(obj, offset, jlong, x);
 452 #else
 453   // Keep old code for platforms which may not have atomic long (8 bytes) instructions
 454   {
 455     if (VM_Version::supports_cx8()) {
 456       SET_FIELD_VOLATILE(obj, offset, jlong, x);
 457     }
 458     else {
 459       Handle p (THREAD, JNIHandles::resolve(obj));
 460       jlong* addr = (jlong*)(index_oop_from_field_offset_long(p(), offset));
 461       MutexLockerEx mu(UnsafeJlong_lock, Mutex::_no_safepoint_check_flag);
 462       Atomic::store(x, addr);
 463     }
 464   }
 465 #endif
 466 UNSAFE_END
 467 
 468 UNSAFE_ENTRY(void, Unsafe_LoadFence(JNIEnv *env, jobject unsafe))
 469   UnsafeWrapper("Unsafe_LoadFence");
 470   OrderAccess::acquire();
 471 UNSAFE_END
 472 
 473 UNSAFE_ENTRY(void, Unsafe_StoreFence(JNIEnv *env, jobject unsafe))
 474   UnsafeWrapper("Unsafe_StoreFence");
 475   OrderAccess::release();
 476 UNSAFE_END
 477 
 478 UNSAFE_ENTRY(void, Unsafe_FullFence(JNIEnv *env, jobject unsafe))
 479   UnsafeWrapper("Unsafe_FullFence");
 480   OrderAccess::fence();
 481 UNSAFE_END
 482 
 483 ////// Data in the C heap.
 484 
 485 // Note:  These do not throw NullPointerException for bad pointers.
 486 // They just crash.  Only a oop base pointer can generate a NullPointerException.
 487 //
 488 #define DEFINE_GETSETNATIVE(java_type, Type, native_type) \
 489  \
 490 UNSAFE_ENTRY(java_type, Unsafe_GetNative##Type(JNIEnv *env, jobject unsafe, jlong addr)) \
 491   UnsafeWrapper("Unsafe_GetNative"#Type); \
 492   void* p = addr_from_java(addr); \
 493   JavaThread* t = JavaThread::current(); \
 494   t->set_doing_unsafe_access(true); \
 495   java_type x = *(volatile native_type*)p; \
 496   t->set_doing_unsafe_access(false); \
 497   return x; \
 498 UNSAFE_END \
 499  \
 500 UNSAFE_ENTRY(void, Unsafe_SetNative##Type(JNIEnv *env, jobject unsafe, jlong addr, java_type x)) \
 501   UnsafeWrapper("Unsafe_SetNative"#Type); \
 502   JavaThread* t = JavaThread::current(); \
 503   t->set_doing_unsafe_access(true); \
 504   void* p = addr_from_java(addr); \
 505   *(volatile native_type*)p = x; \
 506   t->set_doing_unsafe_access(false); \
 507 UNSAFE_END \
 508  \
 509 // END DEFINE_GETSETNATIVE.
 510 
 511 DEFINE_GETSETNATIVE(jbyte, Byte, signed char)
 512 DEFINE_GETSETNATIVE(jshort, Short, signed short);
 513 DEFINE_GETSETNATIVE(jchar, Char, unsigned short);
 514 DEFINE_GETSETNATIVE(jint, Int, jint);
 515 // no long -- handled specially
 516 DEFINE_GETSETNATIVE(jfloat, Float, float);
 517 DEFINE_GETSETNATIVE(jdouble, Double, double);
 518 
 519 #undef DEFINE_GETSETNATIVE
 520 
 521 UNSAFE_ENTRY(jlong, Unsafe_GetNativeLong(JNIEnv *env, jobject unsafe, jlong addr))
 522   UnsafeWrapper("Unsafe_GetNativeLong");
 523   JavaThread* t = JavaThread::current();
 524   // We do it this way to avoid problems with access to heap using 64
 525   // bit loads, as jlong in heap could be not 64-bit aligned, and on
 526   // some CPUs (SPARC) it leads to SIGBUS.
 527   t->set_doing_unsafe_access(true);
 528   void* p = addr_from_java(addr);
 529   jlong x;
 530   if (((intptr_t)p & 7) == 0) {
 531     // jlong is aligned, do a volatile access
 532     x = *(volatile jlong*)p;
 533   } else {
 534     jlong_accessor acc;
 535     acc.words[0] = ((volatile jint*)p)[0];
 536     acc.words[1] = ((volatile jint*)p)[1];
 537     x = acc.long_value;
 538   }
 539   t->set_doing_unsafe_access(false);
 540   return x;
 541 UNSAFE_END
 542 
 543 UNSAFE_ENTRY(void, Unsafe_SetNativeLong(JNIEnv *env, jobject unsafe, jlong addr, jlong x))
 544   UnsafeWrapper("Unsafe_SetNativeLong");
 545   JavaThread* t = JavaThread::current();
 546   // see comment for Unsafe_GetNativeLong
 547   t->set_doing_unsafe_access(true);
 548   void* p = addr_from_java(addr);
 549   if (((intptr_t)p & 7) == 0) {
 550     // jlong is aligned, do a volatile access
 551     *(volatile jlong*)p = x;
 552   } else {
 553     jlong_accessor acc;
 554     acc.long_value = x;
 555     ((volatile jint*)p)[0] = acc.words[0];
 556     ((volatile jint*)p)[1] = acc.words[1];
 557   }
 558   t->set_doing_unsafe_access(false);
 559 UNSAFE_END
 560 
 561 
 562 UNSAFE_ENTRY(jlong, Unsafe_GetNativeAddress(JNIEnv *env, jobject unsafe, jlong addr))
 563   UnsafeWrapper("Unsafe_GetNativeAddress");
 564   void* p = addr_from_java(addr);
 565   return addr_to_java(*(void**)p);
 566 UNSAFE_END
 567 
 568 UNSAFE_ENTRY(void, Unsafe_SetNativeAddress(JNIEnv *env, jobject unsafe, jlong addr, jlong x))
 569   UnsafeWrapper("Unsafe_SetNativeAddress");
 570   void* p = addr_from_java(addr);
 571   *(void**)p = addr_from_java(x);
 572 UNSAFE_END
 573 
 574 
 575 ////// Allocation requests
 576 
 577 UNSAFE_ENTRY(jobject, Unsafe_AllocateInstance(JNIEnv *env, jobject unsafe, jclass cls))
 578   UnsafeWrapper("Unsafe_AllocateInstance");
 579   {
 580     ThreadToNativeFromVM ttnfv(thread);
 581     return env->AllocObject(cls);
 582   }
 583 UNSAFE_END
 584 
 585 UNSAFE_ENTRY(jlong, Unsafe_AllocateMemory(JNIEnv *env, jobject unsafe, jlong size))
 586   UnsafeWrapper("Unsafe_AllocateMemory");
 587   size_t sz = (size_t)size;
 588   if (sz != (julong)size || size < 0) {
 589     THROW_0(vmSymbols::java_lang_IllegalArgumentException());
 590   }
 591   if (sz == 0) {
 592     return 0;
 593   }
 594   sz = round_to(sz, HeapWordSize);
 595   void* x = os::malloc(sz, mtInternal);
 596   if (x == NULL) {
 597     THROW_0(vmSymbols::java_lang_OutOfMemoryError());
 598   }
 599   //Copy::fill_to_words((HeapWord*)x, sz / HeapWordSize);
 600   return addr_to_java(x);
 601 UNSAFE_END
 602 
 603 UNSAFE_ENTRY(jlong, Unsafe_ReallocateMemory(JNIEnv *env, jobject unsafe, jlong addr, jlong size))
 604   UnsafeWrapper("Unsafe_ReallocateMemory");
 605   void* p = addr_from_java(addr);
 606   size_t sz = (size_t)size;
 607   if (sz != (julong)size || size < 0) {
 608     THROW_0(vmSymbols::java_lang_IllegalArgumentException());
 609   }
 610   if (sz == 0) {
 611     os::free(p);
 612     return 0;
 613   }
 614   sz = round_to(sz, HeapWordSize);
 615   void* x = (p == NULL) ? os::malloc(sz, mtInternal) : os::realloc(p, sz, mtInternal);
 616   if (x == NULL) {
 617     THROW_0(vmSymbols::java_lang_OutOfMemoryError());
 618   }
 619   return addr_to_java(x);
 620 UNSAFE_END
 621 
 622 UNSAFE_ENTRY(void, Unsafe_FreeMemory(JNIEnv *env, jobject unsafe, jlong addr))
 623   UnsafeWrapper("Unsafe_FreeMemory");
 624   void* p = addr_from_java(addr);
 625   if (p == NULL) {
 626     return;
 627   }
 628   os::free(p);
 629 UNSAFE_END
 630 
 631 UNSAFE_ENTRY(void, Unsafe_SetMemory(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jlong size, jbyte value))
 632   UnsafeWrapper("Unsafe_SetMemory");
 633   size_t sz = (size_t)size;
 634   if (sz != (julong)size || size < 0) {
 635     THROW(vmSymbols::java_lang_IllegalArgumentException());
 636   }
 637   oop base = JNIHandles::resolve(obj);
 638   void* p = index_oop_from_field_offset_long(base, offset);
 639   Copy::fill_to_memory_atomic(p, sz, value);
 640 UNSAFE_END
 641 
 642 UNSAFE_ENTRY(void, Unsafe_CopyMemory(JNIEnv *env, jobject unsafe, jobject srcObj, jlong srcOffset, jobject dstObj, jlong dstOffset, jlong size))
 643   UnsafeWrapper("Unsafe_CopyMemory");
 644   if (size == 0) {
 645     return;
 646   }
 647   size_t sz = (size_t)size;
 648   if (sz != (julong)size || size < 0) {
 649     THROW(vmSymbols::java_lang_IllegalArgumentException());
 650   }
 651   oop srcp = JNIHandles::resolve(srcObj);
 652   oop dstp = JNIHandles::resolve(dstObj);
 653   if (dstp != NULL && !dstp->is_typeArray()) {
 654     // NYI:  This works only for non-oop arrays at present.
 655     // Generalizing it would be reasonable, but requires card marking.
 656     // Also, autoboxing a Long from 0L in copyMemory(x,y, 0L,z, n) would be bad.
 657     THROW(vmSymbols::java_lang_IllegalArgumentException());
 658   }
 659   void* src = index_oop_from_field_offset_long(srcp, srcOffset);
 660   void* dst = index_oop_from_field_offset_long(dstp, dstOffset);
 661   Copy::conjoint_memory_atomic(src, dst, sz);
 662 UNSAFE_END
 663 
 664 
 665 ////// Random queries
 666 
 667 // See comment at file start about UNSAFE_LEAF
 668 //UNSAFE_LEAF(jint, Unsafe_AddressSize())
 669 UNSAFE_ENTRY(jint, Unsafe_AddressSize(JNIEnv *env, jobject unsafe))
 670   UnsafeWrapper("Unsafe_AddressSize");
 671   return sizeof(void*);
 672 UNSAFE_END
 673 
 674 // See comment at file start about UNSAFE_LEAF
 675 //UNSAFE_LEAF(jint, Unsafe_PageSize())
 676 UNSAFE_ENTRY(jint, Unsafe_PageSize(JNIEnv *env, jobject unsafe))
 677   UnsafeWrapper("Unsafe_PageSize");
 678   return os::vm_page_size();
 679 UNSAFE_END
 680 
 681 jint find_field_offset(jobject field, int must_be_static, TRAPS) {
 682   if (field == NULL) {
 683     THROW_0(vmSymbols::java_lang_NullPointerException());
 684   }
 685 
 686   oop reflected   = JNIHandles::resolve_non_null(field);
 687   oop mirror      = java_lang_reflect_Field::clazz(reflected);
 688   Klass* k      = java_lang_Class::as_Klass(mirror);
 689   int slot        = java_lang_reflect_Field::slot(reflected);
 690   int modifiers   = java_lang_reflect_Field::modifiers(reflected);
 691 
 692   if (must_be_static >= 0) {
 693     int really_is_static = ((modifiers & JVM_ACC_STATIC) != 0);
 694     if (must_be_static != really_is_static) {
 695       THROW_0(vmSymbols::java_lang_IllegalArgumentException());
 696     }
 697   }
 698 
 699   int offset = InstanceKlass::cast(k)->field_offset(slot);
 700   return field_offset_from_byte_offset(offset);

 701 }
 702 
 703 UNSAFE_ENTRY(jlong, Unsafe_ObjectFieldOffset(JNIEnv *env, jobject unsafe, jobject field))
 704   UnsafeWrapper("Unsafe_ObjectFieldOffset");
 705   return find_field_offset(field, 0, THREAD);
 706 UNSAFE_END
 707 
 708 UNSAFE_ENTRY(jlong, Unsafe_StaticFieldOffset(JNIEnv *env, jobject unsafe, jobject field))
 709   UnsafeWrapper("Unsafe_StaticFieldOffset");
 710   return find_field_offset(field, 1, THREAD);
 711 UNSAFE_END
 712 
 713 UNSAFE_ENTRY(jobject, Unsafe_StaticFieldBaseFromField(JNIEnv *env, jobject unsafe, jobject field))
 714   UnsafeWrapper("Unsafe_StaticFieldBase");
 715   // Note:  In this VM implementation, a field address is always a short
 716   // offset from the base of a a klass metaobject.  Thus, the full dynamic
 717   // range of the return type is never used.  However, some implementations
 718   // might put the static field inside an array shared by many classes,
 719   // or even at a fixed address, in which case the address could be quite
 720   // large.  In that last case, this function would return NULL, since
 721   // the address would operate alone, without any base pointer.
 722 
 723   if (field == NULL)  THROW_0(vmSymbols::java_lang_NullPointerException());
 724 
 725   oop reflected   = JNIHandles::resolve_non_null(field);
 726   oop mirror      = java_lang_reflect_Field::clazz(reflected);
 727   int modifiers   = java_lang_reflect_Field::modifiers(reflected);
 728 
 729   if ((modifiers & JVM_ACC_STATIC) == 0) {
 730     THROW_0(vmSymbols::java_lang_IllegalArgumentException());
 731   }
 732 
 733   return JNIHandles::make_local(env, mirror);
 734 UNSAFE_END
 735 
 736 UNSAFE_ENTRY(void, Unsafe_EnsureClassInitialized(JNIEnv *env, jobject unsafe, jobject clazz)) {
 737   UnsafeWrapper("Unsafe_EnsureClassInitialized");
 738   if (clazz == NULL) {
 739     THROW(vmSymbols::java_lang_NullPointerException());
 740   }
 741   oop mirror = JNIHandles::resolve_non_null(clazz);
 742 
 743   Klass* klass = java_lang_Class::as_Klass(mirror);
 744   if (klass != NULL && klass->should_be_initialized()) {
 745     InstanceKlass* k = InstanceKlass::cast(klass);
 746     k->initialize(CHECK);
 747   }
 748 }
 749 UNSAFE_END
 750 
 751 UNSAFE_ENTRY(jboolean, Unsafe_ShouldBeInitialized(JNIEnv *env, jobject unsafe, jobject clazz)) {
 752   UnsafeWrapper("Unsafe_ShouldBeInitialized");
 753   if (clazz == NULL) {
 754     THROW_(vmSymbols::java_lang_NullPointerException(), false);
 755   }
 756   oop mirror = JNIHandles::resolve_non_null(clazz);
 757   Klass* klass = java_lang_Class::as_Klass(mirror);
 758   if (klass != NULL && klass->should_be_initialized()) {
 759     return true;
 760   }
 761   return false;
 762 }
 763 UNSAFE_END
 764 
 765 static void getBaseAndScale(int& base, int& scale, jclass acls, TRAPS) {
 766   if (acls == NULL) {
 767     THROW(vmSymbols::java_lang_NullPointerException());
 768   }
 769   oop      mirror = JNIHandles::resolve_non_null(acls);
 770   Klass* k      = java_lang_Class::as_Klass(mirror);
 771   if (k == NULL || !k->oop_is_array()) {
 772     THROW(vmSymbols::java_lang_InvalidClassException());
 773   } else if (k->oop_is_objArray()) {
 774     base  = arrayOopDesc::base_offset_in_bytes(T_OBJECT);
 775     scale = heapOopSize;
 776   } else if (k->oop_is_typeArray()) {
 777     TypeArrayKlass* tak = TypeArrayKlass::cast(k);
 778     base  = tak->array_header_in_bytes();
 779     assert(base == arrayOopDesc::base_offset_in_bytes(tak->element_type()), "array_header_size semantics ok");
 780     scale = (1 << tak->log2_element_size());
 781   } else {
 782     ShouldNotReachHere();
 783   }
 784 }
 785 
 786 UNSAFE_ENTRY(jint, Unsafe_ArrayBaseOffset(JNIEnv *env, jobject unsafe, jclass acls))
 787   UnsafeWrapper("Unsafe_ArrayBaseOffset");
 788   int base, scale;
 789   getBaseAndScale(base, scale, acls, CHECK_0);
 790   return field_offset_from_byte_offset(base);
 791 UNSAFE_END
 792 
 793 
 794 UNSAFE_ENTRY(jint, Unsafe_ArrayIndexScale(JNIEnv *env, jobject unsafe, jclass acls))
 795   UnsafeWrapper("Unsafe_ArrayIndexScale");
 796   int base, scale;
 797   getBaseAndScale(base, scale, acls, CHECK_0);
 798   // This VM packs both fields and array elements down to the byte.
 799   // But watch out:  If this changes, so that array references for
 800   // a given primitive type (say, T_BOOLEAN) use different memory units
 801   // than fields, this method MUST return zero for such arrays.
 802   // For example, the VM used to store sub-word sized fields in full
 803   // words in the object layout, so that accessors like getByte(Object,int)
 804   // did not really do what one might expect for arrays.  Therefore,
 805   // this function used to report a zero scale factor, so that the user
 806   // would know not to attempt to access sub-word array elements.
 807   // // Code for unpacked fields:
 808   // if (scale < wordSize)  return 0;
 809 
 810   // The following allows for a pretty general fieldOffset cookie scheme,
 811   // but requires it to be linear in byte offset.
 812   return field_offset_from_byte_offset(scale) - field_offset_from_byte_offset(0);
 813 UNSAFE_END
 814 
 815 
 816 static inline void throw_new(JNIEnv *env, const char *ename) {
 817   char buf[100];
 818   jio_snprintf(buf, 100, "%s%s", "java/lang/", ename);
 819   jclass cls = env->FindClass(buf);
 820   if (env->ExceptionCheck()) {
 821     env->ExceptionClear();
 822     tty->print_cr("Unsafe: cannot throw %s because FindClass has failed", buf);
 823     return;
 824   }
 825   char* msg = NULL;
 826   env->ThrowNew(cls, msg);
 827 }
 828 
 829 static jclass Unsafe_DefineClass_impl(JNIEnv *env, jstring name, jbyteArray data, int offset, int length, jobject loader, jobject pd) {
 830   {
 831     // Code lifted from JDK 1.3 ClassLoader.c
 832 
 833     jbyte *body;
 834     char *utfName;
 835     jclass result = 0;
 836     char buf[128];
 837 
 838     if (UsePerfData) {
 839       ClassLoader::unsafe_defineClassCallCounter()->inc();
 840     }
 841 
 842     if (data == NULL) {
 843         throw_new(env, "NullPointerException");
 844         return 0;
 845     }
 846 
 847     /* Work around 4153825. malloc crashes on Solaris when passed a
 848      * negative size.
 849      */
 850     if (length < 0) {
 851         throw_new(env, "ArrayIndexOutOfBoundsException");
 852         return 0;
 853     }
 854 
 855     body = NEW_C_HEAP_ARRAY(jbyte, length, mtInternal);
 856 
 857     if (body == 0) {
 858         throw_new(env, "OutOfMemoryError");
 859         return 0;
 860     }
 861 
 862     env->GetByteArrayRegion(data, offset, length, body);
 863 
 864     if (env->ExceptionOccurred())
 865         goto free_body;
 866 
 867     if (name != NULL) {
 868         uint len = env->GetStringUTFLength(name);
 869         int unicode_len = env->GetStringLength(name);
 870         if (len >= sizeof(buf)) {
 871             utfName = NEW_C_HEAP_ARRAY(char, len + 1, mtInternal);
 872             if (utfName == NULL) {
 873                 throw_new(env, "OutOfMemoryError");
 874                 goto free_body;
 875             }
 876         } else {
 877             utfName = buf;
 878         }
 879         env->GetStringUTFRegion(name, 0, unicode_len, utfName);
 880         //VerifyFixClassname(utfName);
 881         for (uint i = 0; i < len; i++) {
 882           if (utfName[i] == '.')   utfName[i] = '/';
 883         }
 884     } else {
 885         utfName = NULL;
 886     }
 887 
 888     result = JVM_DefineClass(env, utfName, loader, body, length, pd);
 889 
 890     if (utfName && utfName != buf)
 891         FREE_C_HEAP_ARRAY(char, utfName);
 892 
 893  free_body:
 894     FREE_C_HEAP_ARRAY(jbyte, body);
 895     return result;
 896   }
 897 }
 898 
 899 
 900 UNSAFE_ENTRY(jclass, Unsafe_DefineClass(JNIEnv *env, jobject unsafe, jstring name, jbyteArray data, int offset, int length, jobject loader, jobject pd))
 901   UnsafeWrapper("Unsafe_DefineClass");
 902   {
 903     ThreadToNativeFromVM ttnfv(thread);
 904     return Unsafe_DefineClass_impl(env, name, data, offset, length, loader, pd);
 905   }
 906 UNSAFE_END
 907 
 908 
 909 // define a class but do not make it known to the class loader or system dictionary
 910 // - host_class:  supplies context for linkage, access control, protection domain, and class loader
 911 // - data:  bytes of a class file, a raw memory address (length gives the number of bytes)
 912 // - cp_patches:  where non-null entries exist, they replace corresponding CP entries in data
 913 
 914 // When you load an anonymous class U, it works as if you changed its name just before loading,
 915 // to a name that you will never use again.  Since the name is lost, no other class can directly
 916 // link to any member of U.  Just after U is loaded, the only way to use it is reflectively,
 917 // through java.lang.Class methods like Class.newInstance.
 918 
 919 // Access checks for linkage sites within U continue to follow the same rules as for named classes.
 920 // The package of an anonymous class is given by the package qualifier on the name under which it was loaded.
 921 // An anonymous class also has special privileges to access any member of its host class.
 922 // This is the main reason why this loading operation is unsafe.  The purpose of this is to
 923 // allow language implementations to simulate "open classes"; a host class in effect gets
 924 // new code when an anonymous class is loaded alongside it.  A less convenient but more
 925 // standard way to do this is with reflection, which can also be set to ignore access
 926 // restrictions.
 927 
 928 // Access into an anonymous class is possible only through reflection.  Therefore, there
 929 // are no special access rules for calling into an anonymous class.  The relaxed access
 930 // rule for the host class is applied in the opposite direction:  A host class reflectively
 931 // access one of its anonymous classes.
 932 
 933 // If you load the same bytecodes twice, you get two different classes.  You can reload
 934 // the same bytecodes with or without varying CP patches.
 935 
 936 // By using the CP patching array, you can have a new anonymous class U2 refer to an older one U1.
 937 // The bytecodes for U2 should refer to U1 by a symbolic name (doesn't matter what the name is).
 938 // The CONSTANT_Class entry for that name can be patched to refer directly to U1.
 939 
 940 // This allows, for example, U2 to use U1 as a superclass or super-interface, or as
 941 // an outer class (so that U2 is an anonymous inner class of anonymous U1).
 942 // It is not possible for a named class, or an older anonymous class, to refer by
 943 // name (via its CP) to a newer anonymous class.
 944 
 945 // CP patching may also be used to modify (i.e., hack) the names of methods, classes,
 946 // or type descriptors used in the loaded anonymous class.
 947 
 948 // Finally, CP patching may be used to introduce "live" objects into the constant pool,
 949 // instead of "dead" strings.  A compiled statement like println((Object)"hello") can
 950 // be changed to println(greeting), where greeting is an arbitrary object created before
 951 // the anonymous class is loaded.  This is useful in dynamic languages, in which
 952 // various kinds of metaobjects must be introduced as constants into bytecode.
 953 // Note the cast (Object), which tells the verifier to expect an arbitrary object,
 954 // not just a literal string.  For such ldc instructions, the verifier uses the
 955 // type Object instead of String, if the loaded constant is not in fact a String.
 956 
 957 static instanceKlassHandle
 958 Unsafe_DefineAnonymousClass_impl(JNIEnv *env,
 959                                  jclass host_class, jbyteArray data, jobjectArray cp_patches_jh,
 960                                  HeapWord* *temp_alloc,
 961                                  TRAPS) {
 962 
 963   if (UsePerfData) {
 964     ClassLoader::unsafe_defineClassCallCounter()->inc();
 965   }
 966 
 967   if (data == NULL) {
 968     THROW_0(vmSymbols::java_lang_NullPointerException());
 969   }
 970 
 971   jint length = typeArrayOop(JNIHandles::resolve_non_null(data))->length();
 972   jint word_length = (length + sizeof(HeapWord)-1) / sizeof(HeapWord);
 973   HeapWord* body = NEW_C_HEAP_ARRAY(HeapWord, word_length, mtInternal);
 974   if (body == NULL) {
 975     THROW_0(vmSymbols::java_lang_OutOfMemoryError());
 976   }
 977 
 978   // caller responsible to free it:
 979   (*temp_alloc) = body;
 980 
 981   {
 982     jbyte* array_base = typeArrayOop(JNIHandles::resolve_non_null(data))->byte_at_addr(0);
 983     Copy::conjoint_words((HeapWord*) array_base, body, word_length);
 984   }
 985 
 986   u1* class_bytes = (u1*) body;
 987   int class_bytes_length = (int) length;
 988   if (class_bytes_length < 0)  class_bytes_length = 0;
 989   if (class_bytes == NULL
 990       || host_class == NULL
 991       || length != class_bytes_length)
 992     THROW_0(vmSymbols::java_lang_IllegalArgumentException());
 993 
 994   objArrayHandle cp_patches_h;
 995   if (cp_patches_jh != NULL) {
 996     oop p = JNIHandles::resolve_non_null(cp_patches_jh);
 997     if (!p->is_objArray())
 998       THROW_0(vmSymbols::java_lang_IllegalArgumentException());
 999     cp_patches_h = objArrayHandle(THREAD, (objArrayOop)p);
1000   }
1001 
1002   KlassHandle host_klass(THREAD, java_lang_Class::as_Klass(JNIHandles::resolve_non_null(host_class)));
1003   const char* host_source = host_klass->external_name();
1004   Handle      host_loader(THREAD, host_klass->class_loader());
1005   Handle      host_domain(THREAD, host_klass->protection_domain());
1006 
1007   GrowableArray<Handle>* cp_patches = NULL;
1008   if (cp_patches_h.not_null()) {
1009     int alen = cp_patches_h->length();
1010     for (int i = alen-1; i >= 0; i--) {
1011       oop p = cp_patches_h->obj_at(i);
1012       if (p != NULL) {
1013         Handle patch(THREAD, p);
1014         if (cp_patches == NULL)
1015           cp_patches = new GrowableArray<Handle>(i+1, i+1, Handle());
1016         cp_patches->at_put(i, patch);
1017       }
1018     }
1019   }
1020 
1021   ClassFileStream st(class_bytes, class_bytes_length, (char*) host_source);
1022 
1023   instanceKlassHandle anon_klass;
1024   {
1025     Symbol* no_class_name = NULL;
1026     Klass* anonk = SystemDictionary::parse_stream(no_class_name,
1027                                                     host_loader, host_domain,
1028                                                     &st, host_klass, cp_patches,
1029                                                     CHECK_NULL);
1030     if (anonk == NULL)  return NULL;
1031     anon_klass = instanceKlassHandle(THREAD, anonk);
1032   }
1033 
1034   return anon_klass;
1035 }
1036 
1037 UNSAFE_ENTRY(jclass, Unsafe_DefineAnonymousClass(JNIEnv *env, jobject unsafe, jclass host_class, jbyteArray data, jobjectArray cp_patches_jh))
1038 {
1039   instanceKlassHandle anon_klass;
1040   jobject res_jh = NULL;
1041 
1042   UnsafeWrapper("Unsafe_DefineAnonymousClass");
1043   ResourceMark rm(THREAD);
1044 
1045   HeapWord* temp_alloc = NULL;
1046 
1047   anon_klass = Unsafe_DefineAnonymousClass_impl(env, host_class, data,
1048                                                 cp_patches_jh,
1049                                                    &temp_alloc, THREAD);
1050   if (anon_klass() != NULL)
1051     res_jh = JNIHandles::make_local(env, anon_klass->java_mirror());
1052 
1053   // try/finally clause:
1054   if (temp_alloc != NULL) {
1055     FREE_C_HEAP_ARRAY(HeapWord, temp_alloc);
1056   }
1057 
1058   // The anonymous class loader data has been artificially been kept alive to
1059   // this point.   The mirror and any instances of this class have to keep
1060   // it alive afterwards.
1061   if (anon_klass() != NULL) {
1062     anon_klass->class_loader_data()->set_keep_alive(false);
1063   }
1064 
1065   // let caller initialize it as needed...
1066 
1067   return (jclass) res_jh;
1068 }
1069 UNSAFE_END
1070 
1071 
1072 
1073 UNSAFE_ENTRY(void, Unsafe_ThrowException(JNIEnv *env, jobject unsafe, jthrowable thr))
1074   UnsafeWrapper("Unsafe_ThrowException");
1075   {
1076     ThreadToNativeFromVM ttnfv(thread);
1077     env->Throw(thr);
1078   }
1079 UNSAFE_END
1080 
1081 // JSR166 ------------------------------------------------------------------
1082 
1083 UNSAFE_ENTRY(jboolean, Unsafe_CompareAndSwapObject(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject e_h, jobject x_h))
1084   UnsafeWrapper("Unsafe_CompareAndSwapObject");
1085   oop x = JNIHandles::resolve(x_h);
1086   oop e = JNIHandles::resolve(e_h);
1087   oop p = JNIHandles::resolve(obj);
1088   HeapWord* addr = (HeapWord *)index_oop_from_field_offset_long(p, offset);
1089   oop res = oopDesc::atomic_compare_exchange_oop(x, addr, e, true);
1090   jboolean success  = (res == e);
1091   if (success)
1092     update_barrier_set((void*)addr, x);
1093   return success;
1094 UNSAFE_END
1095 
1096 UNSAFE_ENTRY(jboolean, Unsafe_CompareAndSwapInt(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jint e, jint x))
1097   UnsafeWrapper("Unsafe_CompareAndSwapInt");
1098   oop p = JNIHandles::resolve(obj);
1099   jint* addr = (jint *) index_oop_from_field_offset_long(p, offset);
1100   return (jint)(Atomic::cmpxchg(x, addr, e)) == e;
1101 UNSAFE_END
1102 
1103 UNSAFE_ENTRY(jboolean, Unsafe_CompareAndSwapLong(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jlong e, jlong x))
1104   UnsafeWrapper("Unsafe_CompareAndSwapLong");
1105   Handle p (THREAD, JNIHandles::resolve(obj));
1106   jlong* addr = (jlong*)(index_oop_from_field_offset_long(p(), offset));
1107 #ifdef SUPPORTS_NATIVE_CX8
1108   return (jlong)(Atomic::cmpxchg(x, addr, e)) == e;
1109 #else
1110   if (VM_Version::supports_cx8())
1111     return (jlong)(Atomic::cmpxchg(x, addr, e)) == e;
1112   else {
1113     jboolean success = false;
1114     MutexLockerEx mu(UnsafeJlong_lock, Mutex::_no_safepoint_check_flag);
1115     jlong val = Atomic::load(addr);
1116     if (val == e) { Atomic::store(x, addr); success = true; }
1117     return success;
1118   }
1119 #endif
1120 UNSAFE_END
1121 
1122 UNSAFE_ENTRY(void, Unsafe_Park(JNIEnv *env, jobject unsafe, jboolean isAbsolute, jlong time))
1123   UnsafeWrapper("Unsafe_Park");
1124   EventThreadPark event;
1125   HOTSPOT_THREAD_PARK_BEGIN((uintptr_t) thread->parker(), (int) isAbsolute, time);
1126 
1127   JavaThreadParkedState jtps(thread, time != 0);
1128   thread->parker()->park(isAbsolute != 0, time);
1129 
1130   HOTSPOT_THREAD_PARK_END((uintptr_t) thread->parker());
1131   if (event.should_commit()) {
1132     oop obj = thread->current_park_blocker();
1133     event.set_klass((obj != NULL) ? obj->klass() : NULL);
1134     event.set_timeout(time);
1135     event.set_address((obj != NULL) ? (TYPE_ADDRESS) cast_from_oop<uintptr_t>(obj) : 0);
1136     event.commit();
1137   }
1138 UNSAFE_END
1139 
1140 UNSAFE_ENTRY(void, Unsafe_Unpark(JNIEnv *env, jobject unsafe, jobject jthread))
1141   UnsafeWrapper("Unsafe_Unpark");
1142   Parker* p = NULL;
1143   if (jthread != NULL) {
1144     oop java_thread = JNIHandles::resolve_non_null(jthread);
1145     if (java_thread != NULL) {
1146       jlong lp = java_lang_Thread::park_event(java_thread);
1147       if (lp != 0) {
1148         // This cast is OK even though the jlong might have been read
1149         // non-atomically on 32bit systems, since there, one word will
1150         // always be zero anyway and the value set is always the same
1151         p = (Parker*)addr_from_java(lp);
1152       } else {
1153         // Grab lock if apparently null or using older version of library
1154         MutexLocker mu(Threads_lock);
1155         java_thread = JNIHandles::resolve_non_null(jthread);
1156         if (java_thread != NULL) {
1157           JavaThread* thr = java_lang_Thread::thread(java_thread);
1158           if (thr != NULL) {
1159             p = thr->parker();
1160             if (p != NULL) { // Bind to Java thread for next time.
1161               java_lang_Thread::set_park_event(java_thread, addr_to_java(p));
1162             }
1163           }
1164         }
1165       }
1166     }
1167   }
1168   if (p != NULL) {
1169     HOTSPOT_THREAD_UNPARK((uintptr_t) p);
1170     p->unpark();
1171   }
1172 UNSAFE_END
1173 
1174 UNSAFE_ENTRY(jint, Unsafe_Loadavg(JNIEnv *env, jobject unsafe, jdoubleArray loadavg, jint nelem))
1175   UnsafeWrapper("Unsafe_Loadavg");
1176   const int max_nelem = 3;
1177   double la[max_nelem];
1178   jint ret;
1179 
1180   typeArrayOop a = typeArrayOop(JNIHandles::resolve_non_null(loadavg));
1181   assert(a->is_typeArray(), "must be type array");
1182 
1183   if (nelem < 0 || nelem > max_nelem || a->length() < nelem) {
1184     ThreadToNativeFromVM ttnfv(thread);
1185     throw_new(env, "ArrayIndexOutOfBoundsException");
1186     return -1;
1187   }
1188 
1189   ret = os::loadavg(la, nelem);
1190   if (ret == -1) return -1;
1191 
1192   // if successful, ret is the number of samples actually retrieved.
1193   assert(ret >= 0 && ret <= max_nelem, "Unexpected loadavg return value");
1194   switch(ret) {
1195     case 3: a->double_at_put(2, (jdouble)la[2]); // fall through
1196     case 2: a->double_at_put(1, (jdouble)la[1]); // fall through
1197     case 1: a->double_at_put(0, (jdouble)la[0]); break;
1198   }
1199   return ret;
1200 UNSAFE_END
1201 
1202 
1203 /// JVM_RegisterUnsafeMethods
1204 
1205 #define ADR "J"
1206 
1207 #define LANG "Ljava/lang/"
1208 
1209 #define OBJ LANG"Object;"
1210 #define CLS LANG"Class;"
1211 #define FLD LANG"reflect/Field;"
1212 #define THR LANG"Throwable;"
1213 
1214 #define DC_Args  LANG"String;[BII" LANG"ClassLoader;" "Ljava/security/ProtectionDomain;"
1215 #define DAC_Args CLS"[B["OBJ
1216 
1217 #define CC (char*)  /*cast a literal from (const char*)*/
1218 #define FN_PTR(f) CAST_FROM_FN_PTR(void*, &f)
1219 
1220 #define DECLARE_GETPUTOOP(Boolean, Z) \
1221     {CC"get"#Boolean,      CC"("OBJ"J)"#Z,      FN_PTR(Unsafe_Get##Boolean)}, \
1222     {CC"put"#Boolean,      CC"("OBJ"J"#Z")V",   FN_PTR(Unsafe_Set##Boolean)}, \
1223     {CC"get"#Boolean"Volatile",      CC"("OBJ"J)"#Z,      FN_PTR(Unsafe_Get##Boolean##Volatile)}, \
1224     {CC"put"#Boolean"Volatile",      CC"("OBJ"J"#Z")V",   FN_PTR(Unsafe_Set##Boolean##Volatile)}
1225 
1226 
1227 #define DECLARE_GETPUTNATIVE(Byte, B) \
1228     {CC"get"#Byte,         CC"("ADR")"#B,       FN_PTR(Unsafe_GetNative##Byte)}, \
1229     {CC"put"#Byte,         CC"("ADR#B")V",      FN_PTR(Unsafe_SetNative##Byte)}
1230 
1231 
1232 
1233 static JNINativeMethod methods[] = {
1234     {CC"getObject",        CC"("OBJ"J)"OBJ"",   FN_PTR(Unsafe_GetObject)},
1235     {CC"putObject",        CC"("OBJ"J"OBJ")V",  FN_PTR(Unsafe_SetObject)},
1236     {CC"getObjectVolatile",CC"("OBJ"J)"OBJ"",   FN_PTR(Unsafe_GetObjectVolatile)},
1237     {CC"putObjectVolatile",CC"("OBJ"J"OBJ")V",  FN_PTR(Unsafe_SetObjectVolatile)},
1238 
1239     {CC"getUncompressedObject", CC"("ADR")"OBJ, FN_PTR(Unsafe_GetUncompressedObject)},
1240     {CC"getJavaMirror",         CC"("ADR")"CLS, FN_PTR(Unsafe_GetJavaMirror)},
1241     {CC"getKlassPointer",       CC"("OBJ")"ADR, FN_PTR(Unsafe_GetKlassPointer)},
1242 
1243     DECLARE_GETPUTOOP(Boolean, Z),
1244     DECLARE_GETPUTOOP(Byte, B),
1245     DECLARE_GETPUTOOP(Short, S),
1246     DECLARE_GETPUTOOP(Char, C),
1247     DECLARE_GETPUTOOP(Int, I),
1248     DECLARE_GETPUTOOP(Long, J),
1249     DECLARE_GETPUTOOP(Float, F),
1250     DECLARE_GETPUTOOP(Double, D),
1251 
1252     DECLARE_GETPUTNATIVE(Byte, B),
1253     DECLARE_GETPUTNATIVE(Short, S),
1254     DECLARE_GETPUTNATIVE(Char, C),
1255     DECLARE_GETPUTNATIVE(Int, I),
1256     DECLARE_GETPUTNATIVE(Long, J),
1257     DECLARE_GETPUTNATIVE(Float, F),
1258     DECLARE_GETPUTNATIVE(Double, D),
1259 
1260     {CC"getAddress",         CC"("ADR")"ADR,             FN_PTR(Unsafe_GetNativeAddress)},
1261     {CC"putAddress",         CC"("ADR""ADR")V",          FN_PTR(Unsafe_SetNativeAddress)},
1262 
1263     {CC"allocateMemory",     CC"(J)"ADR,                 FN_PTR(Unsafe_AllocateMemory)},
1264     {CC"reallocateMemory",   CC"("ADR"J)"ADR,            FN_PTR(Unsafe_ReallocateMemory)},
1265     {CC"freeMemory",         CC"("ADR")V",               FN_PTR(Unsafe_FreeMemory)},
1266 
1267     {CC"objectFieldOffset",  CC"("FLD")J",               FN_PTR(Unsafe_ObjectFieldOffset)},
1268     {CC"staticFieldOffset",  CC"("FLD")J",               FN_PTR(Unsafe_StaticFieldOffset)},
1269     {CC"staticFieldBase",    CC"("FLD")"OBJ,             FN_PTR(Unsafe_StaticFieldBaseFromField)},
1270     {CC"ensureClassInitialized",CC"("CLS")V",            FN_PTR(Unsafe_EnsureClassInitialized)},
1271     {CC"arrayBaseOffset",    CC"("CLS")I",               FN_PTR(Unsafe_ArrayBaseOffset)},
1272     {CC"arrayIndexScale",    CC"("CLS")I",               FN_PTR(Unsafe_ArrayIndexScale)},
1273     {CC"addressSize",        CC"()I",                    FN_PTR(Unsafe_AddressSize)},
1274     {CC"pageSize",           CC"()I",                    FN_PTR(Unsafe_PageSize)},
1275 
1276     {CC"defineClass",        CC"("DC_Args")"CLS,         FN_PTR(Unsafe_DefineClass)},
1277     {CC"allocateInstance",   CC"("CLS")"OBJ,             FN_PTR(Unsafe_AllocateInstance)},
1278     {CC"throwException",     CC"("THR")V",               FN_PTR(Unsafe_ThrowException)},
1279     {CC"compareAndSwapObject", CC"("OBJ"J"OBJ""OBJ")Z",  FN_PTR(Unsafe_CompareAndSwapObject)},
1280     {CC"compareAndSwapInt",  CC"("OBJ"J""I""I"")Z",      FN_PTR(Unsafe_CompareAndSwapInt)},
1281     {CC"compareAndSwapLong", CC"("OBJ"J""J""J"")Z",      FN_PTR(Unsafe_CompareAndSwapLong)},
1282     {CC"putOrderedObject",   CC"("OBJ"J"OBJ")V",         FN_PTR(Unsafe_SetOrderedObject)},
1283     {CC"putOrderedInt",      CC"("OBJ"JI)V",             FN_PTR(Unsafe_SetOrderedInt)},
1284     {CC"putOrderedLong",     CC"("OBJ"JJ)V",             FN_PTR(Unsafe_SetOrderedLong)},
1285     {CC"park",               CC"(ZJ)V",                  FN_PTR(Unsafe_Park)},
1286     {CC"unpark",             CC"("OBJ")V",               FN_PTR(Unsafe_Unpark)},
1287 
1288     {CC"getLoadAverage",     CC"([DI)I",                 FN_PTR(Unsafe_Loadavg)},
1289 
1290     {CC"copyMemory",         CC"("OBJ"J"OBJ"JJ)V",       FN_PTR(Unsafe_CopyMemory)},
1291     {CC"setMemory",          CC"("OBJ"JJB)V",            FN_PTR(Unsafe_SetMemory)},
1292 
1293     {CC"defineAnonymousClass", CC"("DAC_Args")"CLS,      FN_PTR(Unsafe_DefineAnonymousClass)},
1294 
1295     {CC"shouldBeInitialized",CC"("CLS")Z",               FN_PTR(Unsafe_ShouldBeInitialized)},
1296 
1297     {CC"loadFence",          CC"()V",                    FN_PTR(Unsafe_LoadFence)},
1298     {CC"storeFence",         CC"()V",                    FN_PTR(Unsafe_StoreFence)},
1299     {CC"fullFence",          CC"()V",                    FN_PTR(Unsafe_FullFence)},
1300 
1301     {CC"isBigEndian0",       CC"()Z",                    FN_PTR(Unsafe_isBigEndian0)},
1302     {CC"unalignedAccess0",   CC"()Z",                    FN_PTR(Unsafe_unalignedAccess0)}
1303 };
1304 
1305 #undef CC
1306 #undef FN_PTR
1307 
1308 #undef ADR
1309 #undef LANG
1310 #undef OBJ
1311 #undef CLS
1312 #undef FLD
1313 #undef THR
1314 #undef DC_Args
1315 #undef DAC_Args
1316 
1317 #undef DECLARE_GETPUTOOP
1318 #undef DECLARE_GETPUTNATIVE
1319 
1320 
1321 // This one function is exported, used by NativeLookup.
1322 // The Unsafe_xxx functions above are called only from the interpreter.
1323 // The optimizer looks at names and signatures to recognize
1324 // individual functions.
1325 
1326 JVM_ENTRY(void, JVM_RegisterUnsafeMethods(JNIEnv *env, jclass unsafeclass))
1327   UnsafeWrapper("JVM_RegisterUnsafeMethods");
1328   {
1329     ThreadToNativeFromVM ttnfv(thread);
1330 
1331     int ok = env->RegisterNatives(unsafeclass, methods, sizeof(methods)/sizeof(JNINativeMethod));
1332     guarantee(ok == 0, "register unsafe natives");
1333   }
1334 JVM_END
--- EOF ---