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