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