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