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