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