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