1 /*
   2  * Copyright (c) 2000, 2017, 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 "jni.h"
  27 #include "jvm.h"
  28 #include "classfile/classFileStream.hpp"
  29 #include "classfile/vmSymbols.hpp"
  30 #include "memory/allocation.inline.hpp"
  31 #include "memory/resourceArea.hpp"
  32 #include "oops/access.inline.hpp"
  33 #include "oops/fieldStreams.hpp"
  34 #include "oops/objArrayOop.inline.hpp"
  35 #include "oops/oop.inline.hpp"
  36 #include "prims/unsafe.hpp"
  37 #include "runtime/atomic.hpp"
  38 #include "runtime/globals.hpp"
  39 #include "runtime/interfaceSupport.hpp"
  40 #include "runtime/orderAccess.inline.hpp"
  41 #include "runtime/reflection.hpp"
  42 #include "runtime/thread.hpp"
  43 #include "runtime/threadSMR.hpp"
  44 #include "runtime/vm_version.hpp"
  45 #include "services/threadService.hpp"
  46 #include "trace/tracing.hpp"
  47 #include "utilities/align.hpp"
  48 #include "utilities/copy.hpp"
  49 #include "utilities/dtrace.hpp"
  50 #include "utilities/macros.hpp"
  51 
  52 /**
  53  * Implementation of the jdk.internal.misc.Unsafe class
  54  */
  55 
  56 
  57 #define MAX_OBJECT_SIZE \
  58   ( arrayOopDesc::header_size(T_DOUBLE) * HeapWordSize \
  59     + ((julong)max_jint * sizeof(double)) )
  60 
  61 
  62 #define UNSAFE_ENTRY(result_type, header) \
  63   JVM_ENTRY(static result_type, header)
  64 
  65 #define UNSAFE_LEAF(result_type, header) \
  66   JVM_LEAF(static result_type, header)
  67 
  68 #define UNSAFE_END JVM_END
  69 
  70 
  71 static inline void* addr_from_java(jlong addr) {
  72   // This assert fails in a variety of ways on 32-bit systems.
  73   // It is impossible to predict whether native code that converts
  74   // pointers to longs will sign-extend or zero-extend the addresses.
  75   //assert(addr == (uintptr_t)addr, "must not be odd high bits");
  76   return (void*)(uintptr_t)addr;
  77 }
  78 
  79 static inline jlong addr_to_java(void* p) {
  80   assert(p == (void*)(uintptr_t)p, "must not be odd high bits");
  81   return (uintptr_t)p;
  82 }
  83 
  84 
  85 // Note: The VM's obj_field and related accessors use byte-scaled
  86 // ("unscaled") offsets, just as the unsafe methods do.
  87 
  88 // However, the method Unsafe.fieldOffset explicitly declines to
  89 // guarantee this.  The field offset values manipulated by the Java user
  90 // through the Unsafe API are opaque cookies that just happen to be byte
  91 // offsets.  We represent this state of affairs by passing the cookies
  92 // through conversion functions when going between the VM and the Unsafe API.
  93 // The conversion functions just happen to be no-ops at present.
  94 
  95 static inline jlong field_offset_to_byte_offset(jlong field_offset) {
  96   return field_offset;
  97 }
  98 
  99 static inline jlong field_offset_from_byte_offset(jlong byte_offset) {
 100   return byte_offset;
 101 }
 102 
 103 static inline void assert_field_offset_sane(oop p, jlong field_offset) {
 104 #ifdef ASSERT
 105   jlong byte_offset = field_offset_to_byte_offset(field_offset);
 106 
 107   if (p != NULL) {
 108     assert(byte_offset >= 0 && byte_offset <= (jlong)MAX_OBJECT_SIZE, "sane offset");
 109     if (byte_offset == (jint)byte_offset) {
 110       void* ptr_plus_disp = (address)p + byte_offset;
 111       assert((void*)p->obj_field_addr<oop>((jint)byte_offset) == ptr_plus_disp,
 112              "raw [ptr+disp] must be consistent with oop::field_base");
 113     }
 114     jlong p_size = HeapWordSize * (jlong)(p->size());
 115     assert(byte_offset < p_size, "Unsafe access: offset " INT64_FORMAT " > object's size " INT64_FORMAT, (int64_t)byte_offset, (int64_t)p_size);
 116   }
 117 #endif
 118 }
 119 
 120 static inline void* index_oop_from_field_offset_long(oop p, jlong field_offset) {
 121   assert_field_offset_sane(p, field_offset);
 122   jlong byte_offset = field_offset_to_byte_offset(field_offset);
 123 
 124   if (sizeof(char*) == sizeof(jint)) {   // (this constant folds!)
 125     return (address)p + (jint) byte_offset;
 126   } else {
 127     return (address)p +        byte_offset;
 128   }
 129 }
 130 
 131 // Externally callable versions:
 132 // (Use these in compiler intrinsics which emulate unsafe primitives.)
 133 jlong Unsafe_field_offset_to_byte_offset(jlong field_offset) {
 134   return field_offset;
 135 }
 136 jlong Unsafe_field_offset_from_byte_offset(jlong byte_offset) {
 137   return byte_offset;
 138 }
 139 
 140 
 141 ///// Data read/writes on the Java heap and in native (off-heap) memory
 142 
 143 /**
 144  * Helper class for accessing memory.
 145  *
 146  * Normalizes values and wraps accesses in
 147  * JavaThread::doing_unsafe_access() if needed.
 148  */
 149 class MemoryAccess : StackObj {
 150   JavaThread* _thread;
 151   oop _obj;
 152   ptrdiff_t _offset;
 153 
 154   // Resolves and returns the address of the memory access
 155   void* addr() {
 156     return index_oop_from_field_offset_long(_obj, _offset);
 157   }
 158 
 159   template <typename T>
 160   T normalize_for_write(T x) {
 161     return x;
 162   }
 163 
 164   jboolean normalize_for_write(jboolean x) {
 165     return x & 1;
 166   }
 167 
 168   template <typename T>
 169   T normalize_for_read(T x) {
 170     return x;
 171   }
 172 
 173   jboolean normalize_for_read(jboolean x) {
 174     return x != 0;
 175   }
 176 
 177   /**
 178    * Helper class to wrap memory accesses in JavaThread::doing_unsafe_access()
 179    */
 180   class GuardUnsafeAccess {
 181     JavaThread* _thread;
 182 
 183   public:
 184     GuardUnsafeAccess(JavaThread* thread) : _thread(thread) {
 185       // native/off-heap access which may raise SIGBUS if accessing
 186       // memory mapped file data in a region of the file which has
 187       // been truncated and is now invalid
 188       _thread->set_doing_unsafe_access(true);
 189     }
 190 
 191     ~GuardUnsafeAccess() {
 192       _thread->set_doing_unsafe_access(false);
 193     }
 194   };
 195 
 196 public:
 197   MemoryAccess(JavaThread* thread, jobject obj, jlong offset)
 198     : _thread(thread), _obj(JNIHandles::resolve(obj)), _offset((ptrdiff_t)offset) {
 199     assert_field_offset_sane(_obj, offset);
 200   }
 201 
 202   template <typename T>
 203   T get() {
 204     if (oopDesc::is_null(_obj)) {
 205       GuardUnsafeAccess guard(_thread);
 206       T ret = RawAccess<>::load((volatile T*)addr());
 207       return normalize_for_read(ret);
 208     } else {
 209       T ret = HeapAccess<>::load_at(_obj, _offset);
 210       return normalize_for_read(ret);
 211     }
 212   }
 213 
 214   template <typename T>
 215   void put(T x) {
 216     if (oopDesc::is_null(_obj)) {
 217       GuardUnsafeAccess guard(_thread);
 218       RawAccess<>::store((volatile T*)addr(), normalize_for_write(x));
 219     } else {
 220       HeapAccess<>::store_at(_obj, _offset, normalize_for_write(x));
 221     }
 222   }
 223 
 224 
 225   template <typename T>
 226   T get_volatile() {
 227     if (oopDesc::is_null(_obj)) {
 228       GuardUnsafeAccess guard(_thread);
 229       volatile T ret = RawAccess<MO_SEQ_CST>::load((volatile T*)addr());
 230       return normalize_for_read(ret);
 231     } else {
 232       T ret = HeapAccess<MO_SEQ_CST>::load_at(_obj, _offset);
 233       return normalize_for_read(ret);
 234     }
 235   }
 236 
 237   template <typename T>
 238   void put_volatile(T x) {
 239     if (oopDesc::is_null(_obj)) {
 240       GuardUnsafeAccess guard(_thread);
 241       RawAccess<MO_SEQ_CST>::store((volatile T*)addr(), normalize_for_write(x));
 242     } else {
 243       HeapAccess<MO_SEQ_CST>::store_at(_obj, _offset, normalize_for_write(x));
 244     }
 245   }
 246 };
 247 
 248 // These functions allow a null base pointer with an arbitrary address.
 249 // But if the base pointer is non-null, the offset should make some sense.
 250 // That is, it should be in the range [0, MAX_OBJECT_SIZE].
 251 UNSAFE_ENTRY(jobject, Unsafe_GetObject(JNIEnv *env, jobject unsafe, jobject obj, jlong offset)) {
 252   oop p = JNIHandles::resolve(obj);
 253   assert_field_offset_sane(p, offset);
 254   oop v = HeapAccess<ON_UNKNOWN_OOP_REF>::oop_load_at(p, offset);
 255   return JNIHandles::make_local(env, v);
 256 } UNSAFE_END
 257 
 258 UNSAFE_ENTRY(void, Unsafe_PutObject(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject x_h)) {
 259   oop x = JNIHandles::resolve(x_h);
 260   oop p = JNIHandles::resolve(obj);
 261   assert_field_offset_sane(p, offset);
 262   HeapAccess<ON_UNKNOWN_OOP_REF>::oop_store_at(p, offset, x);
 263 } UNSAFE_END
 264 
 265 UNSAFE_ENTRY(jobject, Unsafe_GetObjectVolatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset)) {
 266   oop p = JNIHandles::resolve(obj);
 267   assert_field_offset_sane(p, offset);
 268   oop v = HeapAccess<MO_SEQ_CST | ON_UNKNOWN_OOP_REF>::oop_load_at(p, offset);
 269   return JNIHandles::make_local(env, v);
 270 } UNSAFE_END
 271 
 272 UNSAFE_ENTRY(void, Unsafe_PutObjectVolatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject x_h)) {
 273   oop x = JNIHandles::resolve(x_h);
 274   oop p = JNIHandles::resolve(obj);
 275   assert_field_offset_sane(p, offset);
 276   HeapAccess<MO_SEQ_CST | ON_UNKNOWN_OOP_REF>::oop_store_at(p, offset, x);
 277 } UNSAFE_END
 278 
 279 UNSAFE_ENTRY(jobject, Unsafe_GetUncompressedObject(JNIEnv *env, jobject unsafe, jlong addr)) {
 280   oop v = *(oop*) (address) addr;
 281   return JNIHandles::make_local(env, v);
 282 } UNSAFE_END
 283 
 284 UNSAFE_LEAF(jboolean, Unsafe_isBigEndian0(JNIEnv *env, jobject unsafe)) {
 285 #ifdef VM_LITTLE_ENDIAN
 286   return false;
 287 #else
 288   return true;
 289 #endif
 290 } UNSAFE_END
 291 
 292 UNSAFE_LEAF(jint, Unsafe_unalignedAccess0(JNIEnv *env, jobject unsafe)) {
 293   return UseUnalignedAccesses;
 294 } UNSAFE_END
 295 
 296 #define DEFINE_GETSETOOP(java_type, Type) \
 297  \
 298 UNSAFE_ENTRY(java_type, Unsafe_Get##Type(JNIEnv *env, jobject unsafe, jobject obj, jlong offset)) { \
 299   return MemoryAccess(thread, obj, offset).get<java_type>(); \
 300 } UNSAFE_END \
 301  \
 302 UNSAFE_ENTRY(void, Unsafe_Put##Type(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, java_type x)) { \
 303   MemoryAccess(thread, obj, offset).put<java_type>(x); \
 304 } UNSAFE_END \
 305  \
 306 // END DEFINE_GETSETOOP.
 307 
 308 DEFINE_GETSETOOP(jboolean, Boolean)
 309 DEFINE_GETSETOOP(jbyte, Byte)
 310 DEFINE_GETSETOOP(jshort, Short);
 311 DEFINE_GETSETOOP(jchar, Char);
 312 DEFINE_GETSETOOP(jint, Int);
 313 DEFINE_GETSETOOP(jlong, Long);
 314 DEFINE_GETSETOOP(jfloat, Float);
 315 DEFINE_GETSETOOP(jdouble, Double);
 316 
 317 #undef DEFINE_GETSETOOP
 318 
 319 #define DEFINE_GETSETOOP_VOLATILE(java_type, Type) \
 320  \
 321 UNSAFE_ENTRY(java_type, Unsafe_Get##Type##Volatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset)) { \
 322   return MemoryAccess(thread, obj, offset).get_volatile<java_type>(); \
 323 } UNSAFE_END \
 324  \
 325 UNSAFE_ENTRY(void, Unsafe_Put##Type##Volatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, java_type x)) { \
 326   MemoryAccess(thread, obj, offset).put_volatile<java_type>(x); \
 327 } UNSAFE_END \
 328  \
 329 // END DEFINE_GETSETOOP_VOLATILE.
 330 
 331 DEFINE_GETSETOOP_VOLATILE(jboolean, Boolean)
 332 DEFINE_GETSETOOP_VOLATILE(jbyte, Byte)
 333 DEFINE_GETSETOOP_VOLATILE(jshort, Short);
 334 DEFINE_GETSETOOP_VOLATILE(jchar, Char);
 335 DEFINE_GETSETOOP_VOLATILE(jint, Int);
 336 DEFINE_GETSETOOP_VOLATILE(jlong, Long);
 337 DEFINE_GETSETOOP_VOLATILE(jfloat, Float);
 338 DEFINE_GETSETOOP_VOLATILE(jdouble, Double);
 339 
 340 #undef DEFINE_GETSETOOP_VOLATILE
 341 
 342 UNSAFE_LEAF(void, Unsafe_LoadFence(JNIEnv *env, jobject unsafe)) {
 343   OrderAccess::acquire();
 344 } UNSAFE_END
 345 
 346 UNSAFE_LEAF(void, Unsafe_StoreFence(JNIEnv *env, jobject unsafe)) {
 347   OrderAccess::release();
 348 } UNSAFE_END
 349 
 350 UNSAFE_LEAF(void, Unsafe_FullFence(JNIEnv *env, jobject unsafe)) {
 351   OrderAccess::fence();
 352 } UNSAFE_END
 353 
 354 ////// Allocation requests
 355 
 356 UNSAFE_ENTRY(jobject, Unsafe_AllocateInstance(JNIEnv *env, jobject unsafe, jclass cls)) {
 357   ThreadToNativeFromVM ttnfv(thread);
 358   return env->AllocObject(cls);
 359 } UNSAFE_END
 360 
 361 UNSAFE_ENTRY(jlong, Unsafe_AllocateMemory0(JNIEnv *env, jobject unsafe, jlong size)) {
 362   size_t sz = (size_t)size;
 363 
 364   sz = align_up(sz, HeapWordSize);
 365   void* x = os::malloc(sz, mtInternal);
 366 
 367   return addr_to_java(x);
 368 } UNSAFE_END
 369 
 370 UNSAFE_ENTRY(jlong, Unsafe_ReallocateMemory0(JNIEnv *env, jobject unsafe, jlong addr, jlong size)) {
 371   void* p = addr_from_java(addr);
 372   size_t sz = (size_t)size;
 373   sz = align_up(sz, HeapWordSize);
 374 
 375   void* x = os::realloc(p, sz, mtInternal);
 376 
 377   return addr_to_java(x);
 378 } UNSAFE_END
 379 
 380 UNSAFE_ENTRY(void, Unsafe_FreeMemory0(JNIEnv *env, jobject unsafe, jlong addr)) {
 381   void* p = addr_from_java(addr);
 382 
 383   os::free(p);
 384 } UNSAFE_END
 385 
 386 UNSAFE_ENTRY(void, Unsafe_SetMemory0(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jlong size, jbyte value)) {
 387   size_t sz = (size_t)size;
 388 
 389   oop base = JNIHandles::resolve(obj);
 390   void* p = index_oop_from_field_offset_long(base, offset);
 391 
 392   Copy::fill_to_memory_atomic(p, sz, value);
 393 } UNSAFE_END
 394 
 395 UNSAFE_ENTRY(void, Unsafe_CopyMemory0(JNIEnv *env, jobject unsafe, jobject srcObj, jlong srcOffset, jobject dstObj, jlong dstOffset, jlong size)) {
 396   size_t sz = (size_t)size;
 397 
 398   oop srcp = JNIHandles::resolve(srcObj);
 399   oop dstp = JNIHandles::resolve(dstObj);
 400 
 401   void* src = index_oop_from_field_offset_long(srcp, srcOffset);
 402   void* dst = index_oop_from_field_offset_long(dstp, dstOffset);
 403 
 404   Copy::conjoint_memory_atomic(src, dst, sz);
 405 } UNSAFE_END
 406 
 407 // This function is a leaf since if the source and destination are both in native memory
 408 // the copy may potentially be very large, and we don't want to disable GC if we can avoid it.
 409 // If either source or destination (or both) are on the heap, the function will enter VM using
 410 // JVM_ENTRY_FROM_LEAF
 411 UNSAFE_LEAF(void, Unsafe_CopySwapMemory0(JNIEnv *env, jobject unsafe, jobject srcObj, jlong srcOffset, jobject dstObj, jlong dstOffset, jlong size, jlong elemSize)) {
 412   size_t sz = (size_t)size;
 413   size_t esz = (size_t)elemSize;
 414 
 415   if (srcObj == NULL && dstObj == NULL) {
 416     // Both src & dst are in native memory
 417     address src = (address)srcOffset;
 418     address dst = (address)dstOffset;
 419 
 420     Copy::conjoint_swap(src, dst, sz, esz);
 421   } else {
 422     // At least one of src/dst are on heap, transition to VM to access raw pointers
 423 
 424     JVM_ENTRY_FROM_LEAF(env, void, Unsafe_CopySwapMemory0) {
 425       oop srcp = JNIHandles::resolve(srcObj);
 426       oop dstp = JNIHandles::resolve(dstObj);
 427 
 428       address src = (address)index_oop_from_field_offset_long(srcp, srcOffset);
 429       address dst = (address)index_oop_from_field_offset_long(dstp, dstOffset);
 430 
 431       Copy::conjoint_swap(src, dst, sz, esz);
 432     } JVM_END
 433   }
 434 } UNSAFE_END
 435 
 436 ////// Random queries
 437 
 438 UNSAFE_LEAF(jint, Unsafe_AddressSize0(JNIEnv *env, jobject unsafe)) {
 439   return sizeof(void*);
 440 } UNSAFE_END
 441 
 442 UNSAFE_LEAF(jint, Unsafe_PageSize()) {
 443   return os::vm_page_size();
 444 } UNSAFE_END
 445 
 446 static jlong find_field_offset(jclass clazz, jstring name, TRAPS) {
 447   assert(clazz != NULL, "clazz must not be NULL");
 448   assert(name != NULL, "name must not be NULL");
 449 
 450   ResourceMark rm(THREAD);
 451   char *utf_name = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(name));
 452 
 453   InstanceKlass* k = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(clazz)));
 454 
 455   jint offset = -1;
 456   for (JavaFieldStream fs(k); !fs.done(); fs.next()) {
 457     Symbol *name = fs.name();
 458     if (name->equals(utf_name)) {
 459       offset = fs.offset();
 460       break;
 461     }
 462   }
 463   if (offset < 0) {
 464     THROW_0(vmSymbols::java_lang_InternalError());
 465   }
 466   return field_offset_from_byte_offset(offset);
 467 }
 468 
 469 static jlong find_field_offset(jobject field, int must_be_static, TRAPS) {
 470   assert(field != NULL, "field must not be NULL");
 471 
 472   oop reflected   = JNIHandles::resolve_non_null(field);
 473   oop mirror      = java_lang_reflect_Field::clazz(reflected);
 474   Klass* k        = java_lang_Class::as_Klass(mirror);
 475   int slot        = java_lang_reflect_Field::slot(reflected);
 476   int modifiers   = java_lang_reflect_Field::modifiers(reflected);
 477 
 478   if (must_be_static >= 0) {
 479     int really_is_static = ((modifiers & JVM_ACC_STATIC) != 0);
 480     if (must_be_static != really_is_static) {
 481       THROW_0(vmSymbols::java_lang_IllegalArgumentException());
 482     }
 483   }
 484 
 485   int offset = InstanceKlass::cast(k)->field_offset(slot);
 486   return field_offset_from_byte_offset(offset);
 487 }
 488 
 489 UNSAFE_ENTRY(jlong, Unsafe_ObjectFieldOffset0(JNIEnv *env, jobject unsafe, jobject field)) {
 490   return find_field_offset(field, 0, THREAD);
 491 } UNSAFE_END
 492 
 493 UNSAFE_ENTRY(jlong, Unsafe_ObjectFieldOffset1(JNIEnv *env, jobject unsafe, jclass c, jstring name)) {
 494   return find_field_offset(c, name, THREAD);
 495 } UNSAFE_END
 496 
 497 UNSAFE_ENTRY(jlong, Unsafe_StaticFieldOffset0(JNIEnv *env, jobject unsafe, jobject field)) {
 498   return find_field_offset(field, 1, THREAD);
 499 } UNSAFE_END
 500 
 501 UNSAFE_ENTRY(jobject, Unsafe_StaticFieldBase0(JNIEnv *env, jobject unsafe, jobject field)) {
 502   assert(field != NULL, "field must not be NULL");
 503 
 504   // Note:  In this VM implementation, a field address is always a short
 505   // offset from the base of a a klass metaobject.  Thus, the full dynamic
 506   // range of the return type is never used.  However, some implementations
 507   // might put the static field inside an array shared by many classes,
 508   // or even at a fixed address, in which case the address could be quite
 509   // large.  In that last case, this function would return NULL, since
 510   // the address would operate alone, without any base pointer.
 511 
 512   oop reflected   = JNIHandles::resolve_non_null(field);
 513   oop mirror      = java_lang_reflect_Field::clazz(reflected);
 514   int modifiers   = java_lang_reflect_Field::modifiers(reflected);
 515 
 516   if ((modifiers & JVM_ACC_STATIC) == 0) {
 517     THROW_0(vmSymbols::java_lang_IllegalArgumentException());
 518   }
 519 
 520   return JNIHandles::make_local(env, mirror);
 521 } UNSAFE_END
 522 
 523 UNSAFE_ENTRY(void, Unsafe_EnsureClassInitialized0(JNIEnv *env, jobject unsafe, jobject clazz)) {
 524   assert(clazz != NULL, "clazz must not be NULL");
 525 
 526   oop mirror = JNIHandles::resolve_non_null(clazz);
 527 
 528   Klass* klass = java_lang_Class::as_Klass(mirror);
 529   if (klass != NULL && klass->should_be_initialized()) {
 530     InstanceKlass* k = InstanceKlass::cast(klass);
 531     k->initialize(CHECK);
 532   }
 533 }
 534 UNSAFE_END
 535 
 536 UNSAFE_ENTRY(jboolean, Unsafe_ShouldBeInitialized0(JNIEnv *env, jobject unsafe, jobject clazz)) {
 537   assert(clazz != NULL, "clazz must not be NULL");
 538 
 539   oop mirror = JNIHandles::resolve_non_null(clazz);
 540   Klass* klass = java_lang_Class::as_Klass(mirror);
 541 
 542   if (klass != NULL && klass->should_be_initialized()) {
 543     return true;
 544   }
 545 
 546   return false;
 547 }
 548 UNSAFE_END
 549 
 550 static void getBaseAndScale(int& base, int& scale, jclass clazz, TRAPS) {
 551   assert(clazz != NULL, "clazz must not be NULL");
 552 
 553   oop mirror = JNIHandles::resolve_non_null(clazz);
 554   Klass* k = java_lang_Class::as_Klass(mirror);
 555 
 556   if (k == NULL || !k->is_array_klass()) {
 557     THROW(vmSymbols::java_lang_InvalidClassException());
 558   } else if (k->is_objArray_klass()) {
 559     base  = arrayOopDesc::base_offset_in_bytes(T_OBJECT);
 560     scale = heapOopSize;
 561   } else if (k->is_typeArray_klass()) {
 562     TypeArrayKlass* tak = TypeArrayKlass::cast(k);
 563     base  = tak->array_header_in_bytes();
 564     assert(base == arrayOopDesc::base_offset_in_bytes(tak->element_type()), "array_header_size semantics ok");
 565     scale = (1 << tak->log2_element_size());
 566   } else {
 567     ShouldNotReachHere();
 568   }
 569 }
 570 
 571 UNSAFE_ENTRY(jint, Unsafe_ArrayBaseOffset0(JNIEnv *env, jobject unsafe, jclass clazz)) {
 572   int base = 0, scale = 0;
 573   getBaseAndScale(base, scale, clazz, CHECK_0);
 574 
 575   return field_offset_from_byte_offset(base);
 576 } UNSAFE_END
 577 
 578 
 579 UNSAFE_ENTRY(jint, Unsafe_ArrayIndexScale0(JNIEnv *env, jobject unsafe, jclass clazz)) {
 580   int base = 0, scale = 0;
 581   getBaseAndScale(base, scale, clazz, CHECK_0);
 582 
 583   // This VM packs both fields and array elements down to the byte.
 584   // But watch out:  If this changes, so that array references for
 585   // a given primitive type (say, T_BOOLEAN) use different memory units
 586   // than fields, this method MUST return zero for such arrays.
 587   // For example, the VM used to store sub-word sized fields in full
 588   // words in the object layout, so that accessors like getByte(Object,int)
 589   // did not really do what one might expect for arrays.  Therefore,
 590   // this function used to report a zero scale factor, so that the user
 591   // would know not to attempt to access sub-word array elements.
 592   // // Code for unpacked fields:
 593   // if (scale < wordSize)  return 0;
 594 
 595   // The following allows for a pretty general fieldOffset cookie scheme,
 596   // but requires it to be linear in byte offset.
 597   return field_offset_from_byte_offset(scale) - field_offset_from_byte_offset(0);
 598 } UNSAFE_END
 599 
 600 
 601 static inline void throw_new(JNIEnv *env, const char *ename) {
 602   jclass cls = env->FindClass(ename);
 603   if (env->ExceptionCheck()) {
 604     env->ExceptionClear();
 605     tty->print_cr("Unsafe: cannot throw %s because FindClass has failed", ename);
 606     return;
 607   }
 608 
 609   env->ThrowNew(cls, NULL);
 610 }
 611 
 612 static jclass Unsafe_DefineClass_impl(JNIEnv *env, jstring name, jbyteArray data, int offset, int length, jobject loader, jobject pd) {
 613   // Code lifted from JDK 1.3 ClassLoader.c
 614 
 615   jbyte *body;
 616   char *utfName = NULL;
 617   jclass result = 0;
 618   char buf[128];
 619 
 620   assert(data != NULL, "Class bytes must not be NULL");
 621   assert(length >= 0, "length must not be negative: %d", length);
 622 
 623   if (UsePerfData) {
 624     ClassLoader::unsafe_defineClassCallCounter()->inc();
 625   }
 626 
 627   body = NEW_C_HEAP_ARRAY(jbyte, length, mtInternal);
 628   if (body == NULL) {
 629     throw_new(env, "java/lang/OutOfMemoryError");
 630     return 0;
 631   }
 632 
 633   env->GetByteArrayRegion(data, offset, length, body);
 634   if (env->ExceptionOccurred()) {
 635     goto free_body;
 636   }
 637 
 638   if (name != NULL) {
 639     uint len = env->GetStringUTFLength(name);
 640     int unicode_len = env->GetStringLength(name);
 641 
 642     if (len >= sizeof(buf)) {
 643       utfName = NEW_C_HEAP_ARRAY(char, len + 1, mtInternal);
 644       if (utfName == NULL) {
 645         throw_new(env, "java/lang/OutOfMemoryError");
 646         goto free_body;
 647       }
 648     } else {
 649       utfName = buf;
 650     }
 651 
 652     env->GetStringUTFRegion(name, 0, unicode_len, utfName);
 653 
 654     for (uint i = 0; i < len; i++) {
 655       if (utfName[i] == '.')   utfName[i] = '/';
 656     }
 657   }
 658 
 659   result = JVM_DefineClass(env, utfName, loader, body, length, pd);
 660 
 661   if (utfName && utfName != buf) {
 662     FREE_C_HEAP_ARRAY(char, utfName);
 663   }
 664 
 665  free_body:
 666   FREE_C_HEAP_ARRAY(jbyte, body);
 667   return result;
 668 }
 669 
 670 
 671 UNSAFE_ENTRY(jclass, Unsafe_DefineClass0(JNIEnv *env, jobject unsafe, jstring name, jbyteArray data, int offset, int length, jobject loader, jobject pd)) {
 672   ThreadToNativeFromVM ttnfv(thread);
 673 
 674   return Unsafe_DefineClass_impl(env, name, data, offset, length, loader, pd);
 675 } UNSAFE_END
 676 
 677 
 678 // define a class but do not make it known to the class loader or system dictionary
 679 // - host_class:  supplies context for linkage, access control, protection domain, and class loader
 680 //                if host_class is itself anonymous then it is replaced with its host class.
 681 // - data:  bytes of a class file, a raw memory address (length gives the number of bytes)
 682 // - cp_patches:  where non-null entries exist, they replace corresponding CP entries in data
 683 
 684 // When you load an anonymous class U, it works as if you changed its name just before loading,
 685 // to a name that you will never use again.  Since the name is lost, no other class can directly
 686 // link to any member of U.  Just after U is loaded, the only way to use it is reflectively,
 687 // through java.lang.Class methods like Class.newInstance.
 688 
 689 // The package of an anonymous class must either match its host's class's package or be in the
 690 // unnamed package.  If it is in the unnamed package then it will be put in its host class's
 691 // package.
 692 //
 693 
 694 // Access checks for linkage sites within U continue to follow the same rules as for named classes.
 695 // An anonymous class also has special privileges to access any member of its host class.
 696 // This is the main reason why this loading operation is unsafe.  The purpose of this is to
 697 // allow language implementations to simulate "open classes"; a host class in effect gets
 698 // new code when an anonymous class is loaded alongside it.  A less convenient but more
 699 // standard way to do this is with reflection, which can also be set to ignore access
 700 // restrictions.
 701 
 702 // Access into an anonymous class is possible only through reflection.  Therefore, there
 703 // are no special access rules for calling into an anonymous class.  The relaxed access
 704 // rule for the host class is applied in the opposite direction:  A host class reflectively
 705 // access one of its anonymous classes.
 706 
 707 // If you load the same bytecodes twice, you get two different classes.  You can reload
 708 // the same bytecodes with or without varying CP patches.
 709 
 710 // By using the CP patching array, you can have a new anonymous class U2 refer to an older one U1.
 711 // The bytecodes for U2 should refer to U1 by a symbolic name (doesn't matter what the name is).
 712 // The CONSTANT_Class entry for that name can be patched to refer directly to U1.
 713 
 714 // This allows, for example, U2 to use U1 as a superclass or super-interface, or as
 715 // an outer class (so that U2 is an anonymous inner class of anonymous U1).
 716 // It is not possible for a named class, or an older anonymous class, to refer by
 717 // name (via its CP) to a newer anonymous class.
 718 
 719 // CP patching may also be used to modify (i.e., hack) the names of methods, classes,
 720 // or type descriptors used in the loaded anonymous class.
 721 
 722 // Finally, CP patching may be used to introduce "live" objects into the constant pool,
 723 // instead of "dead" strings.  A compiled statement like println((Object)"hello") can
 724 // be changed to println(greeting), where greeting is an arbitrary object created before
 725 // the anonymous class is loaded.  This is useful in dynamic languages, in which
 726 // various kinds of metaobjects must be introduced as constants into bytecode.
 727 // Note the cast (Object), which tells the verifier to expect an arbitrary object,
 728 // not just a literal string.  For such ldc instructions, the verifier uses the
 729 // type Object instead of String, if the loaded constant is not in fact a String.
 730 
 731 static InstanceKlass*
 732 Unsafe_DefineAnonymousClass_impl(JNIEnv *env,
 733                                  jclass host_class, jbyteArray data, jobjectArray cp_patches_jh,
 734                                  u1** temp_alloc,
 735                                  TRAPS) {
 736   assert(host_class != NULL, "host_class must not be NULL");
 737   assert(data != NULL, "data must not be NULL");
 738 
 739   if (UsePerfData) {
 740     ClassLoader::unsafe_defineClassCallCounter()->inc();
 741   }
 742 
 743   jint length = typeArrayOop(JNIHandles::resolve_non_null(data))->length();
 744   assert(length >= 0, "class_bytes_length must not be negative: %d", length);
 745 
 746   int class_bytes_length = (int) length;
 747 
 748   u1* class_bytes = NEW_C_HEAP_ARRAY(u1, length, mtInternal);
 749   if (class_bytes == NULL) {
 750     THROW_0(vmSymbols::java_lang_OutOfMemoryError());
 751   }
 752 
 753   // caller responsible to free it:
 754   *temp_alloc = class_bytes;
 755 
 756   jbyte* array_base = typeArrayOop(JNIHandles::resolve_non_null(data))->byte_at_addr(0);
 757   Copy::conjoint_jbytes(array_base, class_bytes, length);
 758 
 759   objArrayHandle cp_patches_h;
 760   if (cp_patches_jh != NULL) {
 761     oop p = JNIHandles::resolve_non_null(cp_patches_jh);
 762     assert(p->is_objArray(), "cp_patches must be an object[]");
 763     cp_patches_h = objArrayHandle(THREAD, (objArrayOop)p);
 764   }
 765 
 766   const Klass* host_klass = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(host_class));
 767 
 768   // Make sure it's the real host class, not another anonymous class.
 769   while (host_klass != NULL && host_klass->is_instance_klass() &&
 770          InstanceKlass::cast(host_klass)->is_anonymous()) {
 771     host_klass = InstanceKlass::cast(host_klass)->host_klass();
 772   }
 773 
 774   // Primitive types have NULL Klass* fields in their java.lang.Class instances.
 775   if (host_klass == NULL) {
 776     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Host class is null");
 777   }
 778 
 779   assert(host_klass->is_instance_klass(), "Host class must be an instance class");
 780 
 781   const char* host_source = host_klass->external_name();
 782   Handle      host_loader(THREAD, host_klass->class_loader());
 783   Handle      host_domain(THREAD, host_klass->protection_domain());
 784 
 785   GrowableArray<Handle>* cp_patches = NULL;
 786 
 787   if (cp_patches_h.not_null()) {
 788     int alen = cp_patches_h->length();
 789 
 790     for (int i = alen-1; i >= 0; i--) {
 791       oop p = cp_patches_h->obj_at(i);
 792       if (p != NULL) {
 793         Handle patch(THREAD, p);
 794 
 795         if (cp_patches == NULL) {
 796           cp_patches = new GrowableArray<Handle>(i+1, i+1, Handle());
 797         }
 798 
 799         cp_patches->at_put(i, patch);
 800       }
 801     }
 802   }
 803 
 804   ClassFileStream st(class_bytes, class_bytes_length, host_source, ClassFileStream::verify);
 805 
 806   Symbol* no_class_name = NULL;
 807   Klass* anonk = SystemDictionary::parse_stream(no_class_name,
 808                                                 host_loader,
 809                                                 host_domain,
 810                                                 &st,
 811                                                 InstanceKlass::cast(host_klass),
 812                                                 cp_patches,
 813                                                 CHECK_NULL);
 814   if (anonk == NULL) {
 815     return NULL;
 816   }
 817 
 818   return InstanceKlass::cast(anonk);
 819 }
 820 
 821 UNSAFE_ENTRY(jclass, Unsafe_DefineAnonymousClass0(JNIEnv *env, jobject unsafe, jclass host_class, jbyteArray data, jobjectArray cp_patches_jh)) {
 822   ResourceMark rm(THREAD);
 823 
 824   jobject res_jh = NULL;
 825   u1* temp_alloc = NULL;
 826 
 827   InstanceKlass* anon_klass = Unsafe_DefineAnonymousClass_impl(env, host_class, data, cp_patches_jh, &temp_alloc, THREAD);
 828   if (anon_klass != NULL) {
 829     res_jh = JNIHandles::make_local(env, anon_klass->java_mirror());
 830   }
 831 
 832   // try/finally clause:
 833   if (temp_alloc != NULL) {
 834     FREE_C_HEAP_ARRAY(u1, temp_alloc);
 835   }
 836 
 837   // The anonymous class loader data has been artificially been kept alive to
 838   // this point.   The mirror and any instances of this class have to keep
 839   // it alive afterwards.
 840   if (anon_klass != NULL) {
 841     anon_klass->class_loader_data()->dec_keep_alive();
 842   }
 843 
 844   // let caller initialize it as needed...
 845 
 846   return (jclass) res_jh;
 847 } UNSAFE_END
 848 
 849 
 850 
 851 UNSAFE_ENTRY(void, Unsafe_ThrowException(JNIEnv *env, jobject unsafe, jthrowable thr)) {
 852   ThreadToNativeFromVM ttnfv(thread);
 853   env->Throw(thr);
 854 } UNSAFE_END
 855 
 856 // JSR166 ------------------------------------------------------------------
 857 
 858 UNSAFE_ENTRY(jobject, Unsafe_CompareAndExchangeObject(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject e_h, jobject x_h)) {
 859   oop x = JNIHandles::resolve(x_h);
 860   oop e = JNIHandles::resolve(e_h);
 861   oop p = JNIHandles::resolve(obj);
 862   assert_field_offset_sane(p, offset);
 863   oop res = HeapAccess<ON_UNKNOWN_OOP_REF>::oop_atomic_cmpxchg_at(x, p, (ptrdiff_t)offset, e);
 864   return JNIHandles::make_local(env, res);
 865 } UNSAFE_END
 866 
 867 UNSAFE_ENTRY(jint, Unsafe_CompareAndExchangeInt(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jint e, jint x)) {
 868   oop p = JNIHandles::resolve(obj);
 869   if (oopDesc::is_null(p)) {
 870     volatile jint* addr = (volatile jint*)index_oop_from_field_offset_long(p, offset);
 871     return RawAccess<>::atomic_cmpxchg(x, addr, e);
 872   } else {
 873     assert_field_offset_sane(p, offset);
 874     return HeapAccess<>::atomic_cmpxchg_at(x, p, (ptrdiff_t)offset, e);
 875   }
 876 } UNSAFE_END
 877 
 878 UNSAFE_ENTRY(jlong, Unsafe_CompareAndExchangeLong(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jlong e, jlong x)) {
 879   oop p = JNIHandles::resolve(obj);
 880   if (oopDesc::is_null(p)) {
 881     volatile jlong* addr = (volatile jlong*)index_oop_from_field_offset_long(p, offset);
 882     return RawAccess<>::atomic_cmpxchg(x, addr, e);
 883   } else {
 884     assert_field_offset_sane(p, offset);
 885     return HeapAccess<>::atomic_cmpxchg_at(x, p, (ptrdiff_t)offset, e);
 886   }
 887 } UNSAFE_END
 888 
 889 UNSAFE_ENTRY(jboolean, Unsafe_CompareAndSetObject(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject e_h, jobject x_h)) {
 890   oop x = JNIHandles::resolve(x_h);
 891   oop e = JNIHandles::resolve(e_h);
 892   oop p = JNIHandles::resolve(obj);
 893   assert_field_offset_sane(p, offset);
 894   oop ret = HeapAccess<ON_UNKNOWN_OOP_REF>::oop_atomic_cmpxchg_at(x, p, (ptrdiff_t)offset, e);
 895   return ret == e;
 896 } UNSAFE_END
 897 
 898 UNSAFE_ENTRY(jboolean, Unsafe_CompareAndSetInt(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jint e, jint x)) {
 899   oop p = JNIHandles::resolve(obj);
 900   if (oopDesc::is_null(p)) {
 901     volatile jint* addr = (volatile jint*)index_oop_from_field_offset_long(p, offset);
 902     return RawAccess<>::atomic_cmpxchg(x, addr, e) == e;
 903   } else {
 904     assert_field_offset_sane(p, offset);
 905     return HeapAccess<>::atomic_cmpxchg_at(x, p, (ptrdiff_t)offset, e) == e;
 906   }
 907 } UNSAFE_END
 908 
 909 UNSAFE_ENTRY(jboolean, Unsafe_CompareAndSetLong(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jlong e, jlong x)) {
 910   oop p = JNIHandles::resolve(obj);
 911   if (oopDesc::is_null(p)) {
 912     volatile jlong* addr = (volatile jlong*)index_oop_from_field_offset_long(p, offset);
 913     return RawAccess<>::atomic_cmpxchg(x, addr, e) == e;
 914   } else {
 915     assert_field_offset_sane(p, offset);
 916     return HeapAccess<>::atomic_cmpxchg_at(x, p, (ptrdiff_t)offset, e) == e;
 917   }
 918 } UNSAFE_END
 919 
 920 UNSAFE_ENTRY(void, Unsafe_Park(JNIEnv *env, jobject unsafe, jboolean isAbsolute, jlong time)) {
 921   EventThreadPark event;
 922   HOTSPOT_THREAD_PARK_BEGIN((uintptr_t) thread->parker(), (int) isAbsolute, time);
 923 
 924   JavaThreadParkedState jtps(thread, time != 0);
 925   thread->parker()->park(isAbsolute != 0, time);
 926 
 927   HOTSPOT_THREAD_PARK_END((uintptr_t) thread->parker());
 928 
 929   if (event.should_commit()) {
 930     oop obj = thread->current_park_blocker();
 931     event.set_parkedClass((obj != NULL) ? obj->klass() : NULL);
 932     event.set_timeout(time);
 933     event.set_address((obj != NULL) ? (TYPE_ADDRESS) cast_from_oop<uintptr_t>(obj) : 0);
 934     event.commit();
 935   }
 936 } UNSAFE_END
 937 
 938 UNSAFE_ENTRY(void, Unsafe_Unpark(JNIEnv *env, jobject unsafe, jobject jthread)) {
 939   Parker* p = NULL;
 940 
 941   if (jthread != NULL) {
 942     ThreadsListHandle tlh;
 943     JavaThread* thr = NULL;
 944     oop java_thread = NULL;
 945     (void) tlh.cv_internal_thread_to_JavaThread(jthread, &thr, &java_thread);
 946     if (java_thread != NULL) {
 947       // This is a valid oop.
 948       jlong lp = java_lang_Thread::park_event(java_thread);
 949       if (lp != 0) {
 950         // This cast is OK even though the jlong might have been read
 951         // non-atomically on 32bit systems, since there, one word will
 952         // always be zero anyway and the value set is always the same
 953         p = (Parker*)addr_from_java(lp);
 954       } else {
 955         // Not cached in the java.lang.Thread oop yet (could be an
 956         // older version of library).
 957         if (thr != NULL) {
 958           // The JavaThread is alive.
 959           p = thr->parker();
 960           if (p != NULL) {
 961             // Cache the Parker in the java.lang.Thread oop for next time.
 962             java_lang_Thread::set_park_event(java_thread, addr_to_java(p));
 963           }
 964         }
 965       }
 966     }
 967   } // ThreadsListHandle is destroyed here.
 968 
 969   if (p != NULL) {
 970     HOTSPOT_THREAD_UNPARK((uintptr_t) p);
 971     p->unpark();
 972   }
 973 } UNSAFE_END
 974 
 975 UNSAFE_ENTRY(jint, Unsafe_GetLoadAverage0(JNIEnv *env, jobject unsafe, jdoubleArray loadavg, jint nelem)) {
 976   const int max_nelem = 3;
 977   double la[max_nelem];
 978   jint ret;
 979 
 980   typeArrayOop a = typeArrayOop(JNIHandles::resolve_non_null(loadavg));
 981   assert(a->is_typeArray(), "must be type array");
 982 
 983   ret = os::loadavg(la, nelem);
 984   if (ret == -1) {
 985     return -1;
 986   }
 987 
 988   // if successful, ret is the number of samples actually retrieved.
 989   assert(ret >= 0 && ret <= max_nelem, "Unexpected loadavg return value");
 990   switch(ret) {
 991     case 3: a->double_at_put(2, (jdouble)la[2]); // fall through
 992     case 2: a->double_at_put(1, (jdouble)la[1]); // fall through
 993     case 1: a->double_at_put(0, (jdouble)la[0]); break;
 994   }
 995 
 996   return ret;
 997 } UNSAFE_END
 998 
 999 
1000 /// JVM_RegisterUnsafeMethods
1001 
1002 #define ADR "J"
1003 
1004 #define LANG "Ljava/lang/"
1005 
1006 #define OBJ LANG "Object;"
1007 #define CLS LANG "Class;"
1008 #define FLD LANG "reflect/Field;"
1009 #define THR LANG "Throwable;"
1010 
1011 #define DC_Args  LANG "String;[BII" LANG "ClassLoader;" "Ljava/security/ProtectionDomain;"
1012 #define DAC_Args CLS "[B[" OBJ
1013 
1014 #define CC (char*)  /*cast a literal from (const char*)*/
1015 #define FN_PTR(f) CAST_FROM_FN_PTR(void*, &f)
1016 
1017 #define DECLARE_GETPUTOOP(Type, Desc) \
1018     {CC "get" #Type,      CC "(" OBJ "J)" #Desc,       FN_PTR(Unsafe_Get##Type)}, \
1019     {CC "put" #Type,      CC "(" OBJ "J" #Desc ")V",   FN_PTR(Unsafe_Put##Type)}, \
1020     {CC "get" #Type "Volatile",      CC "(" OBJ "J)" #Desc,       FN_PTR(Unsafe_Get##Type##Volatile)}, \
1021     {CC "put" #Type "Volatile",      CC "(" OBJ "J" #Desc ")V",   FN_PTR(Unsafe_Put##Type##Volatile)}
1022 
1023 
1024 static JNINativeMethod jdk_internal_misc_Unsafe_methods[] = {
1025     {CC "getObject",        CC "(" OBJ "J)" OBJ "",   FN_PTR(Unsafe_GetObject)},
1026     {CC "putObject",        CC "(" OBJ "J" OBJ ")V",  FN_PTR(Unsafe_PutObject)},
1027     {CC "getObjectVolatile",CC "(" OBJ "J)" OBJ "",   FN_PTR(Unsafe_GetObjectVolatile)},
1028     {CC "putObjectVolatile",CC "(" OBJ "J" OBJ ")V",  FN_PTR(Unsafe_PutObjectVolatile)},
1029 
1030     {CC "getUncompressedObject", CC "(" ADR ")" OBJ,  FN_PTR(Unsafe_GetUncompressedObject)},
1031 
1032     DECLARE_GETPUTOOP(Boolean, Z),
1033     DECLARE_GETPUTOOP(Byte, B),
1034     DECLARE_GETPUTOOP(Short, S),
1035     DECLARE_GETPUTOOP(Char, C),
1036     DECLARE_GETPUTOOP(Int, I),
1037     DECLARE_GETPUTOOP(Long, J),
1038     DECLARE_GETPUTOOP(Float, F),
1039     DECLARE_GETPUTOOP(Double, D),
1040 
1041     {CC "allocateMemory0",    CC "(J)" ADR,              FN_PTR(Unsafe_AllocateMemory0)},
1042     {CC "reallocateMemory0",  CC "(" ADR "J)" ADR,       FN_PTR(Unsafe_ReallocateMemory0)},
1043     {CC "freeMemory0",        CC "(" ADR ")V",           FN_PTR(Unsafe_FreeMemory0)},
1044 
1045     {CC "objectFieldOffset0", CC "(" FLD ")J",           FN_PTR(Unsafe_ObjectFieldOffset0)},
1046     {CC "objectFieldOffset1", CC "(" CLS LANG "String;)J", FN_PTR(Unsafe_ObjectFieldOffset1)},
1047     {CC "staticFieldOffset0", CC "(" FLD ")J",           FN_PTR(Unsafe_StaticFieldOffset0)},
1048     {CC "staticFieldBase0",   CC "(" FLD ")" OBJ,        FN_PTR(Unsafe_StaticFieldBase0)},
1049     {CC "ensureClassInitialized0", CC "(" CLS ")V",      FN_PTR(Unsafe_EnsureClassInitialized0)},
1050     {CC "arrayBaseOffset0",   CC "(" CLS ")I",           FN_PTR(Unsafe_ArrayBaseOffset0)},
1051     {CC "arrayIndexScale0",   CC "(" CLS ")I",           FN_PTR(Unsafe_ArrayIndexScale0)},
1052     {CC "addressSize0",       CC "()I",                  FN_PTR(Unsafe_AddressSize0)},
1053     {CC "pageSize",           CC "()I",                  FN_PTR(Unsafe_PageSize)},
1054 
1055     {CC "defineClass0",       CC "(" DC_Args ")" CLS,    FN_PTR(Unsafe_DefineClass0)},
1056     {CC "allocateInstance",   CC "(" CLS ")" OBJ,        FN_PTR(Unsafe_AllocateInstance)},
1057     {CC "throwException",     CC "(" THR ")V",           FN_PTR(Unsafe_ThrowException)},
1058     {CC "compareAndSetObject",CC "(" OBJ "J" OBJ "" OBJ ")Z", FN_PTR(Unsafe_CompareAndSetObject)},
1059     {CC "compareAndSetInt",   CC "(" OBJ "J""I""I"")Z",  FN_PTR(Unsafe_CompareAndSetInt)},
1060     {CC "compareAndSetLong",  CC "(" OBJ "J""J""J"")Z",  FN_PTR(Unsafe_CompareAndSetLong)},
1061     {CC "compareAndExchangeObject", CC "(" OBJ "J" OBJ "" OBJ ")" OBJ, FN_PTR(Unsafe_CompareAndExchangeObject)},
1062     {CC "compareAndExchangeInt",  CC "(" OBJ "J""I""I"")I", FN_PTR(Unsafe_CompareAndExchangeInt)},
1063     {CC "compareAndExchangeLong", CC "(" OBJ "J""J""J"")J", FN_PTR(Unsafe_CompareAndExchangeLong)},
1064 
1065     {CC "park",               CC "(ZJ)V",                FN_PTR(Unsafe_Park)},
1066     {CC "unpark",             CC "(" OBJ ")V",           FN_PTR(Unsafe_Unpark)},
1067 
1068     {CC "getLoadAverage0",    CC "([DI)I",               FN_PTR(Unsafe_GetLoadAverage0)},
1069 
1070     {CC "copyMemory0",        CC "(" OBJ "J" OBJ "JJ)V", FN_PTR(Unsafe_CopyMemory0)},
1071     {CC "copySwapMemory0",    CC "(" OBJ "J" OBJ "JJJ)V", FN_PTR(Unsafe_CopySwapMemory0)},
1072     {CC "setMemory0",         CC "(" OBJ "JJB)V",        FN_PTR(Unsafe_SetMemory0)},
1073 
1074     {CC "defineAnonymousClass0", CC "(" DAC_Args ")" CLS, FN_PTR(Unsafe_DefineAnonymousClass0)},
1075 
1076     {CC "shouldBeInitialized0", CC "(" CLS ")Z",         FN_PTR(Unsafe_ShouldBeInitialized0)},
1077 
1078     {CC "loadFence",          CC "()V",                  FN_PTR(Unsafe_LoadFence)},
1079     {CC "storeFence",         CC "()V",                  FN_PTR(Unsafe_StoreFence)},
1080     {CC "fullFence",          CC "()V",                  FN_PTR(Unsafe_FullFence)},
1081 
1082     {CC "isBigEndian0",       CC "()Z",                  FN_PTR(Unsafe_isBigEndian0)},
1083     {CC "unalignedAccess0",   CC "()Z",                  FN_PTR(Unsafe_unalignedAccess0)}
1084 };
1085 
1086 #undef CC
1087 #undef FN_PTR
1088 
1089 #undef ADR
1090 #undef LANG
1091 #undef OBJ
1092 #undef CLS
1093 #undef FLD
1094 #undef THR
1095 #undef DC_Args
1096 #undef DAC_Args
1097 
1098 #undef DECLARE_GETPUTOOP
1099 
1100 
1101 // This function is exported, used by NativeLookup.
1102 // The Unsafe_xxx functions above are called only from the interpreter.
1103 // The optimizer looks at names and signatures to recognize
1104 // individual functions.
1105 
1106 JVM_ENTRY(void, JVM_RegisterJDKInternalMiscUnsafeMethods(JNIEnv *env, jclass unsafeclass)) {
1107   ThreadToNativeFromVM ttnfv(thread);
1108 
1109   int ok = env->RegisterNatives(unsafeclass, jdk_internal_misc_Unsafe_methods, sizeof(jdk_internal_misc_Unsafe_methods)/sizeof(JNINativeMethod));
1110   guarantee(ok == 0, "register jdk.internal.misc.Unsafe natives");
1111 } JVM_END