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