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