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