1 /*
   2  * Copyright (c) 2000, 2024, 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 "classfile/classFileStream.hpp"
  27 #include "classfile/classLoader.hpp"
  28 #include "classfile/classLoadInfo.hpp"
  29 #include "classfile/javaClasses.inline.hpp"
  30 #include "classfile/systemDictionary.hpp"
  31 #include "classfile/vmSymbols.hpp"
  32 #include "jfr/jfrEvents.hpp"
  33 #include "jni.h"
  34 #include "jvm.h"
  35 #include "memory/allocation.inline.hpp"
  36 #include "memory/resourceArea.hpp"
  37 #include "logging/log.hpp"
  38 #include "logging/logStream.hpp"
  39 #include "oops/access.inline.hpp"
  40 #include "oops/fieldStreams.inline.hpp"
  41 #include "oops/flatArrayKlass.hpp"
  42 #include "oops/flatArrayOop.inline.hpp"
  43 #include "oops/inlineKlass.inline.hpp"
  44 #include "oops/instanceKlass.inline.hpp"
  45 #include "oops/klass.inline.hpp"
  46 #include "oops/objArrayOop.inline.hpp"
  47 #include "oops/oop.inline.hpp"
  48 #include "oops/typeArrayOop.inline.hpp"
  49 #include "prims/jvmtiExport.hpp"
  50 #include "prims/unsafe.hpp"
  51 #include "runtime/fieldDescriptor.inline.hpp"
  52 #include "runtime/globals.hpp"
  53 #include "runtime/handles.inline.hpp"
  54 #include "runtime/interfaceSupport.inline.hpp"
  55 #include "runtime/javaThread.inline.hpp"
  56 #include "runtime/jniHandles.inline.hpp"
  57 #include "runtime/orderAccess.hpp"
  58 #include "runtime/reflection.hpp"
  59 #include "runtime/sharedRuntime.hpp"
  60 #include "runtime/stubRoutines.hpp"
  61 #include "runtime/threadSMR.hpp"
  62 #include "runtime/vmOperations.hpp"
  63 #include "runtime/vm_version.hpp"
  64 #include "sanitizers/ub.hpp"
  65 #include "services/threadService.hpp"
  66 #include "utilities/align.hpp"
  67 #include "utilities/copy.hpp"
  68 #include "utilities/dtrace.hpp"
  69 #include "utilities/macros.hpp"
  70 
  71 /**
  72  * Implementation of the jdk.internal.misc.Unsafe class
  73  */
  74 
  75 
  76 #define MAX_OBJECT_SIZE \
  77   ( arrayOopDesc::base_offset_in_bytes(T_DOUBLE) \
  78     + ((julong)max_jint * sizeof(double)) )
  79 
  80 #define UNSAFE_ENTRY(result_type, header) \
  81   JVM_ENTRY(static result_type, header)
  82 
  83 #define UNSAFE_LEAF(result_type, header) \
  84   JVM_LEAF(static result_type, header)
  85 
  86 // All memory access methods (e.g. getInt, copyMemory) must use this macro.
  87 // We call these methods "scoped" methods, as access to these methods is
  88 // typically governed by a "scope" (a MemorySessionImpl object), and no
  89 // access is allowed when the scope is no longer alive.
  90 //
  91 // Closing a scope object (cf. scopedMemoryAccess.cpp) can install
  92 // an async exception during a safepoint. When that happens,
  93 // scoped methods are not allowed to touch the underlying memory (as that
  94 // memory might have been released). Therefore, when entering a scoped method
  95 // we check if an async exception has been installed, and return immediately
  96 // if that is the case.
  97 //
  98 // As a rule, we disallow safepoints in the middle of a scoped method.
  99 // If an async exception handshake were installed in such a safepoint,
 100 // memory access might still occur before the handshake is honored by
 101 // the accessing thread.
 102 //
 103 // Corollary: as threads in native state are considered to be at a safepoint,
 104 // scoped methods must NOT be executed while in the native thread state.
 105 // Because of this, there can be no UNSAFE_LEAF_SCOPED.
 106 #define UNSAFE_ENTRY_SCOPED(result_type, header) \
 107   JVM_ENTRY(static result_type, header) \
 108   if (thread->has_async_exception_condition()) {return (result_type)0;}
 109 
 110 #define UNSAFE_END JVM_END
 111 
 112 
 113 static inline void* addr_from_java(jlong addr) {
 114   // This assert fails in a variety of ways on 32-bit systems.
 115   // It is impossible to predict whether native code that converts
 116   // pointers to longs will sign-extend or zero-extend the addresses.
 117   //assert(addr == (uintptr_t)addr, "must not be odd high bits");
 118   return (void*)(uintptr_t)addr;
 119 }
 120 
 121 static inline jlong addr_to_java(void* p) {
 122   assert(p == (void*)(uintptr_t)p, "must not be odd high bits");
 123   return (uintptr_t)p;
 124 }
 125 
 126 
 127 // Note: The VM's obj_field and related accessors use byte-scaled
 128 // ("unscaled") offsets, just as the unsafe methods do.
 129 
 130 // However, the method Unsafe.fieldOffset explicitly declines to
 131 // guarantee this.  The field offset values manipulated by the Java user
 132 // through the Unsafe API are opaque cookies that just happen to be byte
 133 // offsets.  We represent this state of affairs by passing the cookies
 134 // through conversion functions when going between the VM and the Unsafe API.
 135 // The conversion functions just happen to be no-ops at present.
 136 
 137 static inline jlong field_offset_to_byte_offset(jlong field_offset) {
 138   return field_offset;
 139 }
 140 
 141 static inline int field_offset_from_byte_offset(int byte_offset) {
 142   return byte_offset;
 143 }
 144 
 145 static inline void assert_field_offset_sane(oop p, jlong field_offset) {
 146 #ifdef ASSERT
 147   jlong byte_offset = field_offset_to_byte_offset(field_offset);
 148 
 149   if (p != nullptr) {
 150     assert(byte_offset >= 0 && byte_offset <= (jlong)MAX_OBJECT_SIZE, "sane offset");
 151     if (byte_offset == (jint)byte_offset) {
 152       void* ptr_plus_disp = cast_from_oop<address>(p) + byte_offset;
 153       assert(p->field_addr<void>((jint)byte_offset) == ptr_plus_disp,
 154              "raw [ptr+disp] must be consistent with oop::field_addr");
 155     }
 156     jlong p_size = HeapWordSize * (jlong)(p->size());
 157     assert(byte_offset < p_size, "Unsafe access: offset " INT64_FORMAT " > object's size " INT64_FORMAT, (int64_t)byte_offset, (int64_t)p_size);
 158   }
 159 #endif
 160 }
 161 
 162 static inline void* index_oop_from_field_offset_long(oop p, jlong field_offset) {
 163   assert_field_offset_sane(p, field_offset);
 164   uintptr_t base_address = cast_from_oop<uintptr_t>(p);
 165   uintptr_t byte_offset  = (uintptr_t)field_offset_to_byte_offset(field_offset);
 166   return (void*)(base_address + byte_offset);
 167 }
 168 
 169 // Externally callable versions:
 170 // (Use these in compiler intrinsics which emulate unsafe primitives.)
 171 jlong Unsafe_field_offset_to_byte_offset(jlong field_offset) {
 172   return field_offset;
 173 }
 174 jlong Unsafe_field_offset_from_byte_offset(jlong byte_offset) {
 175   return byte_offset;
 176 }
 177 
 178 ///// Data read/writes on the Java heap and in native (off-heap) memory
 179 
 180 /**
 181  * Helper class to wrap memory accesses in JavaThread::doing_unsafe_access()
 182  */
 183 class GuardUnsafeAccess {
 184   JavaThread* _thread;
 185 
 186 public:
 187   GuardUnsafeAccess(JavaThread* thread) : _thread(thread) {
 188     // native/off-heap access which may raise SIGBUS if accessing
 189     // memory mapped file data in a region of the file which has
 190     // been truncated and is now invalid.
 191     _thread->set_doing_unsafe_access(true);
 192   }
 193 
 194   ~GuardUnsafeAccess() {
 195     _thread->set_doing_unsafe_access(false);
 196   }
 197 };
 198 
 199 /**
 200  * Helper class for accessing memory.
 201  *
 202  * Normalizes values and wraps accesses in
 203  * JavaThread::doing_unsafe_access() if needed.
 204  */
 205 template <typename T>
 206 class MemoryAccess : StackObj {
 207   JavaThread* _thread;
 208   oop _obj;
 209   ptrdiff_t _offset;
 210 
 211   // Resolves and returns the address of the memory access.
 212   // This raw memory access may fault, so we make sure it happens within the
 213   // guarded scope by making the access volatile at least. Since the store
 214   // of Thread::set_doing_unsafe_access() is also volatile, these accesses
 215   // can not be reordered by the compiler. Therefore, if the access triggers
 216   // a fault, we will know that Thread::doing_unsafe_access() returns true.
 217   volatile T* addr() {
 218     void* addr = index_oop_from_field_offset_long(_obj, _offset);
 219     return static_cast<volatile T*>(addr);
 220   }
 221 
 222   template <typename U>
 223   U normalize_for_write(U x) {
 224     return x;
 225   }
 226 
 227   jboolean normalize_for_write(jboolean x) {
 228     return x & 1;
 229   }
 230 
 231   template <typename U>
 232   U normalize_for_read(U x) {
 233     return x;
 234   }
 235 
 236   jboolean normalize_for_read(jboolean x) {
 237     return x != 0;
 238   }
 239 
 240 public:
 241   MemoryAccess(JavaThread* thread, jobject obj, jlong offset)
 242     : _thread(thread), _obj(JNIHandles::resolve(obj)), _offset((ptrdiff_t)offset) {
 243     assert_field_offset_sane(_obj, offset);
 244   }
 245 
 246   T get() {
 247     GuardUnsafeAccess guard(_thread);
 248     return normalize_for_read(*addr());
 249   }
 250 
 251   // we use this method at some places for writing to 0 e.g. to cause a crash;
 252   // ubsan does not know that this is the desired behavior
 253   ATTRIBUTE_NO_UBSAN
 254   void put(T x) {
 255     GuardUnsafeAccess guard(_thread);
 256     assert(_obj == nullptr || !_obj->is_inline_type() || _obj->mark().is_larval_state(), "must be an object instance or a larval inline type");
 257     *addr() = normalize_for_write(x);
 258   }
 259 
 260   T get_volatile() {
 261     GuardUnsafeAccess guard(_thread);
 262     volatile T ret = RawAccess<MO_SEQ_CST>::load(addr());
 263     return normalize_for_read(ret);
 264   }
 265 
 266   void put_volatile(T x) {
 267     GuardUnsafeAccess guard(_thread);
 268     RawAccess<MO_SEQ_CST>::store(addr(), normalize_for_write(x));
 269   }
 270 };
 271 
 272 #ifdef ASSERT
 273 /*
 274  * Get the field descriptor of the field of the given object at the given offset.
 275  */
 276 static bool get_field_descriptor(oop p, jlong offset, fieldDescriptor* fd) {
 277   bool found = false;
 278   Klass* k = p->klass();
 279   if (k->is_instance_klass()) {
 280     InstanceKlass* ik = InstanceKlass::cast(k);
 281     found = ik->find_field_from_offset((int)offset, false, fd);
 282     if (!found && ik->is_mirror_instance_klass()) {
 283       Klass* k2 = java_lang_Class::as_Klass(p);
 284       if (k2->is_instance_klass()) {
 285         ik = InstanceKlass::cast(k2);
 286         found = ik->find_field_from_offset((int)offset, true, fd);
 287       }
 288     }
 289   }
 290   return found;
 291 }
 292 #endif // ASSERT
 293 
 294 static void assert_and_log_unsafe_value_access(oop p, jlong offset, InlineKlass* vk) {
 295   Klass* k = p->klass();
 296 #ifdef ASSERT
 297   if (k->is_instance_klass()) {
 298     assert_field_offset_sane(p, offset);
 299     fieldDescriptor fd;
 300     bool found = get_field_descriptor(p, offset, &fd);
 301     if (found) {
 302       assert(found, "value field not found");
 303       assert(fd.is_flat(), "field not flat");
 304     } else {
 305       if (log_is_enabled(Trace, valuetypes)) {
 306         log_trace(valuetypes)("not a field in %s at offset " UINT64_FORMAT_X,
 307                               p->klass()->external_name(), (uint64_t)offset);
 308       }
 309     }
 310   } else if (k->is_flatArray_klass()) {
 311     FlatArrayKlass* vak = FlatArrayKlass::cast(k);
 312     int index = (offset - vak->array_header_in_bytes()) / vak->element_byte_size();
 313     address dest = (address)((flatArrayOop)p)->value_at_addr(index, vak->layout_helper());
 314     assert(dest == (cast_from_oop<address>(p) + offset), "invalid offset");
 315   } else {
 316     ShouldNotReachHere();
 317   }
 318 #endif // ASSERT
 319   if (log_is_enabled(Trace, valuetypes)) {
 320     if (k->is_flatArray_klass()) {
 321       FlatArrayKlass* vak = FlatArrayKlass::cast(k);
 322       int index = (offset - vak->array_header_in_bytes()) / vak->element_byte_size();
 323       address dest = (address)((flatArrayOop)p)->value_at_addr(index, vak->layout_helper());
 324       log_trace(valuetypes)("%s array type %s index %d element size %d offset " UINT64_FORMAT_X " at " INTPTR_FORMAT,
 325                             p->klass()->external_name(), vak->external_name(),
 326                             index, vak->element_byte_size(), (uint64_t)offset, p2i(dest));
 327     } else {
 328       log_trace(valuetypes)("%s field type %s at offset " UINT64_FORMAT_X,
 329                             p->klass()->external_name(), vk->external_name(), (uint64_t)offset);
 330     }
 331   }
 332 }
 333 
 334 // These functions allow a null base pointer with an arbitrary address.
 335 // But if the base pointer is non-null, the offset should make some sense.
 336 // That is, it should be in the range [0, MAX_OBJECT_SIZE].
 337 UNSAFE_ENTRY(jobject, Unsafe_GetReference(JNIEnv *env, jobject unsafe, jobject obj, jlong offset)) {
 338   oop p = JNIHandles::resolve(obj);
 339   assert_field_offset_sane(p, offset);
 340   oop v = HeapAccess<ON_UNKNOWN_OOP_REF>::oop_load_at(p, offset);
 341   return JNIHandles::make_local(THREAD, v);
 342 } UNSAFE_END
 343 
 344 UNSAFE_ENTRY(void, Unsafe_PutReference(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject x_h)) {
 345   oop x = JNIHandles::resolve(x_h);
 346   oop p = JNIHandles::resolve(obj);
 347   assert_field_offset_sane(p, offset);
 348   assert(!p->is_inline_type() || p->mark().is_larval_state(), "must be an object instance or a larval inline type");
 349   HeapAccess<ON_UNKNOWN_OOP_REF>::oop_store_at(p, offset, x);
 350 } UNSAFE_END
 351 
 352 UNSAFE_ENTRY(jlong, Unsafe_ValueHeaderSize(JNIEnv *env, jobject unsafe, jclass c)) {
 353   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(c));
 354   InlineKlass* vk = InlineKlass::cast(k);
 355   return vk->first_field_offset();
 356 } UNSAFE_END
 357 
 358 UNSAFE_ENTRY(jboolean, Unsafe_IsFlatField(JNIEnv *env, jobject unsafe, jobject o)) {
 359   oop f = JNIHandles::resolve_non_null(o);
 360   Klass* k = java_lang_Class::as_Klass(java_lang_reflect_Field::clazz(f));
 361   int slot = java_lang_reflect_Field::slot(f);
 362   return InstanceKlass::cast(k)->field_is_flat(slot);
 363 } UNSAFE_END
 364 
 365 UNSAFE_ENTRY(jboolean, Unsafe_HasNullMarker(JNIEnv *env, jobject unsage, jobject o)) {
 366   oop f = JNIHandles::resolve_non_null(o);
 367   Klass* k = java_lang_Class::as_Klass(java_lang_reflect_Field::clazz(f));
 368   int slot = java_lang_reflect_Field::slot(f);
 369   return InstanceKlass::cast(k)->field_has_null_marker(slot);
 370 } UNSAFE_END
 371 
 372 UNSAFE_ENTRY(jint, Unsafe_NullMarkerOffset(JNIEnv *env, jobject unsage, jobject o)) {
 373   oop f = JNIHandles::resolve_non_null(o);
 374   Klass* k = java_lang_Class::as_Klass(java_lang_reflect_Field::clazz(f));
 375   int slot = java_lang_reflect_Field::slot(f);
 376   fatal("Not supported yet");
 377 } UNSAFE_END
 378 
 379 UNSAFE_ENTRY(jboolean, Unsafe_IsFlatArray(JNIEnv *env, jobject unsafe, jclass c)) {
 380   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(c));
 381   return k->is_flatArray_klass();
 382 } UNSAFE_END
 383 
 384 UNSAFE_ENTRY(jobject, Unsafe_UninitializedDefaultValue(JNIEnv *env, jobject unsafe, jclass vc)) {
 385   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(vc));
 386   InlineKlass* vk = InlineKlass::cast(k);
 387   oop v = vk->default_value();
 388   return JNIHandles::make_local(THREAD, v);
 389 } UNSAFE_END
 390 
 391 UNSAFE_ENTRY(jobject, Unsafe_GetValue(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jclass vc)) {
 392   oop base = JNIHandles::resolve(obj);
 393   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(vc));
 394   InlineKlass* vk = InlineKlass::cast(k);
 395   assert_and_log_unsafe_value_access(base, offset, vk);
 396   Handle base_h(THREAD, base);
 397   oop v = vk->read_flat_field(base_h(), offset, LayoutKind::PAYLOAD, CHECK_NULL);  // TODO FIXME Hard coded layout kind to make the code compile, Unsafe must be upgraded to handle correct layout kind
 398   return JNIHandles::make_local(THREAD, v);
 399 } UNSAFE_END
 400 
 401 UNSAFE_ENTRY(void, Unsafe_PutValue(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jclass vc, jobject value)) {
 402   oop base = JNIHandles::resolve(obj);
 403   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(vc));
 404   InlineKlass* vk = InlineKlass::cast(k);
 405   assert(!base->is_inline_type() || base->mark().is_larval_state(), "must be an object instance or a larval inline type");
 406   assert_and_log_unsafe_value_access(base, offset, vk);
 407   oop v = JNIHandles::resolve(value);
 408   vk->write_flat_field(base, offset, v, true /*null free*/, LayoutKind::PAYLOAD, CHECK);  // TODO FIXME Hard coded layout kind to make the code compile, Unsafe must be upgraded to handle correct layout kind
 409 } UNSAFE_END
 410 
 411 UNSAFE_ENTRY(jobject, Unsafe_MakePrivateBuffer(JNIEnv *env, jobject unsafe, jobject value)) {
 412   oop v = JNIHandles::resolve_non_null(value);
 413   assert(v->is_inline_type(), "must be an inline type instance");
 414   Handle vh(THREAD, v);
 415   InlineKlass* vk = InlineKlass::cast(v->klass());
 416   instanceOop new_value = vk->allocate_instance_buffer(CHECK_NULL);
 417   vk->inline_copy_oop_to_new_oop(vh(), new_value, LayoutKind::PAYLOAD);  // FIXME temporary hack for the transition
 418   markWord mark = new_value->mark();
 419   new_value->set_mark(mark.enter_larval_state());
 420   return JNIHandles::make_local(THREAD, new_value);
 421 } UNSAFE_END
 422 
 423 UNSAFE_ENTRY(jobject, Unsafe_FinishPrivateBuffer(JNIEnv *env, jobject unsafe, jobject value)) {
 424   oop v = JNIHandles::resolve(value);
 425   assert(v->mark().is_larval_state(), "must be a larval value");
 426   markWord mark = v->mark();
 427   v->set_mark(mark.exit_larval_state());
 428   return JNIHandles::make_local(THREAD, v);
 429 } UNSAFE_END
 430 
 431 UNSAFE_ENTRY(jobject, Unsafe_GetReferenceVolatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset)) {
 432   oop p = JNIHandles::resolve(obj);
 433   assert_field_offset_sane(p, offset);
 434   oop v = HeapAccess<MO_SEQ_CST | ON_UNKNOWN_OOP_REF>::oop_load_at(p, offset);
 435   return JNIHandles::make_local(THREAD, v);
 436 } UNSAFE_END
 437 
 438 UNSAFE_ENTRY(void, Unsafe_PutReferenceVolatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject x_h)) {
 439   oop x = JNIHandles::resolve(x_h);
 440   oop p = JNIHandles::resolve(obj);
 441   assert_field_offset_sane(p, offset);
 442   HeapAccess<MO_SEQ_CST | ON_UNKNOWN_OOP_REF>::oop_store_at(p, offset, x);
 443 } UNSAFE_END
 444 
 445 UNSAFE_ENTRY(jobject, Unsafe_GetUncompressedObject(JNIEnv *env, jobject unsafe, jlong addr)) {
 446   oop v = *(oop*) (address) addr;
 447   return JNIHandles::make_local(THREAD, v);
 448 } UNSAFE_END
 449 
 450 #define DEFINE_GETSETOOP(java_type, Type) \
 451  \
 452 UNSAFE_ENTRY_SCOPED(java_type, Unsafe_Get##Type(JNIEnv *env, jobject unsafe, jobject obj, jlong offset)) { \
 453   return MemoryAccess<java_type>(thread, obj, offset).get(); \
 454 } UNSAFE_END \
 455  \
 456 UNSAFE_ENTRY_SCOPED(void, Unsafe_Put##Type(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, java_type x)) { \
 457   MemoryAccess<java_type>(thread, obj, offset).put(x); \
 458 } UNSAFE_END \
 459  \
 460 // END DEFINE_GETSETOOP.
 461 
 462 DEFINE_GETSETOOP(jboolean, Boolean)
 463 DEFINE_GETSETOOP(jbyte, Byte)
 464 DEFINE_GETSETOOP(jshort, Short);
 465 DEFINE_GETSETOOP(jchar, Char);
 466 DEFINE_GETSETOOP(jint, Int);
 467 DEFINE_GETSETOOP(jlong, Long);
 468 DEFINE_GETSETOOP(jfloat, Float);
 469 DEFINE_GETSETOOP(jdouble, Double);
 470 
 471 #undef DEFINE_GETSETOOP
 472 
 473 #define DEFINE_GETSETOOP_VOLATILE(java_type, Type) \
 474  \
 475 UNSAFE_ENTRY_SCOPED(java_type, Unsafe_Get##Type##Volatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset)) { \
 476   return MemoryAccess<java_type>(thread, obj, offset).get_volatile(); \
 477 } UNSAFE_END \
 478  \
 479 UNSAFE_ENTRY_SCOPED(void, Unsafe_Put##Type##Volatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, java_type x)) { \
 480   MemoryAccess<java_type>(thread, obj, offset).put_volatile(x); \
 481 } UNSAFE_END \
 482  \
 483 // END DEFINE_GETSETOOP_VOLATILE.
 484 
 485 DEFINE_GETSETOOP_VOLATILE(jboolean, Boolean)
 486 DEFINE_GETSETOOP_VOLATILE(jbyte, Byte)
 487 DEFINE_GETSETOOP_VOLATILE(jshort, Short);
 488 DEFINE_GETSETOOP_VOLATILE(jchar, Char);
 489 DEFINE_GETSETOOP_VOLATILE(jint, Int);
 490 DEFINE_GETSETOOP_VOLATILE(jlong, Long);
 491 DEFINE_GETSETOOP_VOLATILE(jfloat, Float);
 492 DEFINE_GETSETOOP_VOLATILE(jdouble, Double);
 493 
 494 #undef DEFINE_GETSETOOP_VOLATILE
 495 
 496 UNSAFE_LEAF(void, Unsafe_FullFence(JNIEnv *env, jobject unsafe)) {
 497   OrderAccess::fence();
 498 } UNSAFE_END
 499 
 500 ////// Allocation requests
 501 
 502 UNSAFE_ENTRY(jobject, Unsafe_AllocateInstance(JNIEnv *env, jobject unsafe, jclass cls)) {
 503   JvmtiVMObjectAllocEventCollector oam;
 504   instanceOop i = InstanceKlass::allocate_instance(JNIHandles::resolve_non_null(cls), CHECK_NULL);
 505   return JNIHandles::make_local(THREAD, i);
 506 } UNSAFE_END
 507 
 508 UNSAFE_LEAF(jlong, Unsafe_AllocateMemory0(JNIEnv *env, jobject unsafe, jlong size)) {
 509   size_t sz = (size_t)size;
 510 
 511   assert(is_aligned(sz, HeapWordSize), "sz not aligned");
 512 
 513   void* x = os::malloc(sz, mtOther);
 514 
 515   return addr_to_java(x);
 516 } UNSAFE_END
 517 
 518 UNSAFE_LEAF(jlong, Unsafe_ReallocateMemory0(JNIEnv *env, jobject unsafe, jlong addr, jlong size)) {
 519   void* p = addr_from_java(addr);
 520   size_t sz = (size_t)size;
 521 
 522   assert(is_aligned(sz, HeapWordSize), "sz not aligned");
 523 
 524   void* x = os::realloc(p, sz, mtOther);
 525 
 526   return addr_to_java(x);
 527 } UNSAFE_END
 528 
 529 UNSAFE_LEAF(void, Unsafe_FreeMemory0(JNIEnv *env, jobject unsafe, jlong addr)) {
 530   void* p = addr_from_java(addr);
 531 
 532   os::free(p);
 533 } UNSAFE_END
 534 
 535 UNSAFE_ENTRY_SCOPED(void, Unsafe_SetMemory0(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jlong size, jbyte value)) {
 536   size_t sz = (size_t)size;
 537 
 538   oop base = JNIHandles::resolve(obj);
 539   void* p = index_oop_from_field_offset_long(base, offset);
 540 
 541   {
 542     GuardUnsafeAccess guard(thread);
 543     if (StubRoutines::unsafe_setmemory() != nullptr) {
 544       MACOS_AARCH64_ONLY(ThreadWXEnable wx(WXExec, thread));
 545       StubRoutines::UnsafeSetMemory_stub()(p, sz, value);
 546     } else {
 547       Copy::fill_to_memory_atomic(p, sz, value);
 548     }
 549   }
 550 } UNSAFE_END
 551 
 552 UNSAFE_ENTRY_SCOPED(void, Unsafe_CopyMemory0(JNIEnv *env, jobject unsafe, jobject srcObj, jlong srcOffset, jobject dstObj, jlong dstOffset, jlong size)) {
 553   size_t sz = (size_t)size;
 554 
 555   oop srcp = JNIHandles::resolve(srcObj);
 556   oop dstp = JNIHandles::resolve(dstObj);
 557 
 558   void* src = index_oop_from_field_offset_long(srcp, srcOffset);
 559   void* dst = index_oop_from_field_offset_long(dstp, dstOffset);
 560   {
 561     GuardUnsafeAccess guard(thread);
 562     if (StubRoutines::unsafe_arraycopy() != nullptr) {
 563       MACOS_AARCH64_ONLY(ThreadWXEnable wx(WXExec, thread));
 564       StubRoutines::UnsafeArrayCopy_stub()(src, dst, sz);
 565     } else {
 566       Copy::conjoint_memory_atomic(src, dst, sz);
 567     }
 568   }
 569 } UNSAFE_END
 570 
 571 UNSAFE_ENTRY_SCOPED(void, Unsafe_CopySwapMemory0(JNIEnv *env, jobject unsafe, jobject srcObj, jlong srcOffset, jobject dstObj, jlong dstOffset, jlong size, jlong elemSize)) {
 572   size_t sz = (size_t)size;
 573   size_t esz = (size_t)elemSize;
 574 
 575   oop srcp = JNIHandles::resolve(srcObj);
 576   oop dstp = JNIHandles::resolve(dstObj);
 577 
 578   address src = (address)index_oop_from_field_offset_long(srcp, srcOffset);
 579   address dst = (address)index_oop_from_field_offset_long(dstp, dstOffset);
 580 
 581   {
 582     GuardUnsafeAccess guard(thread);
 583     Copy::conjoint_swap(src, dst, sz, esz);
 584   }
 585 } UNSAFE_END
 586 
 587 UNSAFE_LEAF (void, Unsafe_WriteBack0(JNIEnv *env, jobject unsafe, jlong line)) {
 588   assert(VM_Version::supports_data_cache_line_flush(), "should not get here");
 589 #ifdef ASSERT
 590   if (TraceMemoryWriteback) {
 591     tty->print_cr("Unsafe: writeback 0x%p", addr_from_java(line));
 592   }
 593 #endif
 594 
 595   MACOS_AARCH64_ONLY(ThreadWXEnable wx(WXExec, Thread::current()));
 596   assert(StubRoutines::data_cache_writeback() != nullptr, "sanity");
 597   (StubRoutines::DataCacheWriteback_stub())(addr_from_java(line));
 598 } UNSAFE_END
 599 
 600 static void doWriteBackSync0(bool is_pre)
 601 {
 602   MACOS_AARCH64_ONLY(ThreadWXEnable wx(WXExec, Thread::current()));
 603   assert(StubRoutines::data_cache_writeback_sync() != nullptr, "sanity");
 604   (StubRoutines::DataCacheWritebackSync_stub())(is_pre);
 605 }
 606 
 607 UNSAFE_LEAF (void, Unsafe_WriteBackPreSync0(JNIEnv *env, jobject unsafe)) {
 608   assert(VM_Version::supports_data_cache_line_flush(), "should not get here");
 609 #ifdef ASSERT
 610   if (TraceMemoryWriteback) {
 611       tty->print_cr("Unsafe: writeback pre-sync");
 612   }
 613 #endif
 614 
 615   doWriteBackSync0(true);
 616 } UNSAFE_END
 617 
 618 UNSAFE_LEAF (void, Unsafe_WriteBackPostSync0(JNIEnv *env, jobject unsafe)) {
 619   assert(VM_Version::supports_data_cache_line_flush(), "should not get here");
 620 #ifdef ASSERT
 621   if (TraceMemoryWriteback) {
 622     tty->print_cr("Unsafe: writeback pre-sync");
 623   }
 624 #endif
 625 
 626   doWriteBackSync0(false);
 627 } UNSAFE_END
 628 
 629 ////// Random queries
 630 
 631 static jlong find_field_offset(jclass clazz, jstring name, TRAPS) {
 632   assert(clazz != nullptr, "clazz must not be null");
 633   assert(name != nullptr, "name must not be null");
 634 
 635   ResourceMark rm(THREAD);
 636   char *utf_name = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(name));
 637 
 638   InstanceKlass* k = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(clazz)));
 639 
 640   jint offset = -1;
 641   for (JavaFieldStream fs(k); !fs.done(); fs.next()) {
 642     Symbol *name = fs.name();
 643     if (name->equals(utf_name)) {
 644       offset = fs.offset();
 645       break;
 646     }
 647   }
 648   if (offset < 0) {
 649     THROW_0(vmSymbols::java_lang_InternalError());
 650   }
 651   return field_offset_from_byte_offset(offset);
 652 }
 653 
 654 static jlong find_field_offset(jobject field, int must_be_static, TRAPS) {
 655   assert(field != nullptr, "field must not be null");
 656 
 657   oop reflected   = JNIHandles::resolve_non_null(field);
 658   oop mirror      = java_lang_reflect_Field::clazz(reflected);
 659   Klass* k        = java_lang_Class::as_Klass(mirror);
 660   int slot        = java_lang_reflect_Field::slot(reflected);
 661   int modifiers   = java_lang_reflect_Field::modifiers(reflected);
 662 
 663   if (must_be_static >= 0) {
 664     int really_is_static = ((modifiers & JVM_ACC_STATIC) != 0);
 665     if (must_be_static != really_is_static) {
 666       THROW_0(vmSymbols::java_lang_IllegalArgumentException());
 667     }
 668   }
 669 
 670   int offset = InstanceKlass::cast(k)->field_offset(slot);
 671   return field_offset_from_byte_offset(offset);
 672 }
 673 
 674 UNSAFE_ENTRY(jlong, Unsafe_ObjectFieldOffset0(JNIEnv *env, jobject unsafe, jobject field)) {
 675   return find_field_offset(field, 0, THREAD);
 676 } UNSAFE_END
 677 
 678 UNSAFE_ENTRY(jlong, Unsafe_ObjectFieldOffset1(JNIEnv *env, jobject unsafe, jclass c, jstring name)) {
 679   return find_field_offset(c, name, THREAD);
 680 } UNSAFE_END
 681 
 682 UNSAFE_ENTRY(jlong, Unsafe_StaticFieldOffset0(JNIEnv *env, jobject unsafe, jobject field)) {
 683   return find_field_offset(field, 1, THREAD);
 684 } UNSAFE_END
 685 
 686 UNSAFE_ENTRY(jobject, Unsafe_StaticFieldBase0(JNIEnv *env, jobject unsafe, jobject field)) {
 687   assert(field != nullptr, "field must not be null");
 688 
 689   // Note:  In this VM implementation, a field address is always a short
 690   // offset from the base of a klass metaobject.  Thus, the full dynamic
 691   // range of the return type is never used.  However, some implementations
 692   // might put the static field inside an array shared by many classes,
 693   // or even at a fixed address, in which case the address could be quite
 694   // large.  In that last case, this function would return null, since
 695   // the address would operate alone, without any base pointer.
 696 
 697   oop reflected   = JNIHandles::resolve_non_null(field);
 698   oop mirror      = java_lang_reflect_Field::clazz(reflected);
 699   int modifiers   = java_lang_reflect_Field::modifiers(reflected);
 700 
 701   if ((modifiers & JVM_ACC_STATIC) == 0) {
 702     THROW_NULL(vmSymbols::java_lang_IllegalArgumentException());
 703   }
 704 
 705   return JNIHandles::make_local(THREAD, mirror);
 706 } UNSAFE_END
 707 
 708 UNSAFE_ENTRY(void, Unsafe_EnsureClassInitialized0(JNIEnv *env, jobject unsafe, jobject clazz)) {
 709   assert(clazz != nullptr, "clazz must not be null");
 710 
 711   oop mirror = JNIHandles::resolve_non_null(clazz);
 712 
 713   Klass* klass = java_lang_Class::as_Klass(mirror);
 714   if (klass != nullptr && klass->should_be_initialized()) {
 715     InstanceKlass* k = InstanceKlass::cast(klass);
 716     k->initialize(CHECK);
 717   }
 718 }
 719 UNSAFE_END
 720 
 721 UNSAFE_ENTRY(jboolean, Unsafe_ShouldBeInitialized0(JNIEnv *env, jobject unsafe, jobject clazz)) {
 722   assert(clazz != nullptr, "clazz must not be null");
 723 
 724   oop mirror = JNIHandles::resolve_non_null(clazz);
 725   Klass* klass = java_lang_Class::as_Klass(mirror);
 726 
 727   if (klass != nullptr && klass->should_be_initialized()) {
 728     return true;
 729   }
 730 
 731   return false;
 732 }
 733 UNSAFE_END
 734 
 735 static void getBaseAndScale(int& base, int& scale, jclass clazz, TRAPS) {
 736   assert(clazz != nullptr, "clazz must not be null");
 737 
 738   oop mirror = JNIHandles::resolve_non_null(clazz);
 739   Klass* k = java_lang_Class::as_Klass(mirror);
 740 
 741   if (k == nullptr || !k->is_array_klass()) {
 742     THROW(vmSymbols::java_lang_InvalidClassException());
 743   } else if (k->is_objArray_klass()) {
 744     base  = arrayOopDesc::base_offset_in_bytes(T_OBJECT);
 745     scale = heapOopSize;
 746   } else if (k->is_typeArray_klass()) {
 747     TypeArrayKlass* tak = TypeArrayKlass::cast(k);
 748     base  = tak->array_header_in_bytes();
 749     assert(base == arrayOopDesc::base_offset_in_bytes(tak->element_type()), "array_header_size semantics ok");
 750     scale = (1 << tak->log2_element_size());
 751   } else if (k->is_flatArray_klass()) {
 752     FlatArrayKlass* vak = FlatArrayKlass::cast(k);
 753     InlineKlass* vklass = vak->element_klass();
 754     base = vak->array_header_in_bytes();
 755     scale = vak->element_byte_size();
 756   } else {
 757     ShouldNotReachHere();
 758   }
 759 }
 760 
 761 UNSAFE_ENTRY(jint, Unsafe_ArrayBaseOffset0(JNIEnv *env, jobject unsafe, jclass clazz)) {
 762   int base = 0, scale = 0;
 763   getBaseAndScale(base, scale, clazz, CHECK_0);
 764 
 765   return field_offset_from_byte_offset(base);
 766 } UNSAFE_END
 767 
 768 
 769 UNSAFE_ENTRY(jint, Unsafe_ArrayIndexScale0(JNIEnv *env, jobject unsafe, jclass clazz)) {
 770   int base = 0, scale = 0;
 771   getBaseAndScale(base, scale, clazz, CHECK_0);
 772 
 773   // This VM packs both fields and array elements down to the byte.
 774   // But watch out:  If this changes, so that array references for
 775   // a given primitive type (say, T_BOOLEAN) use different memory units
 776   // than fields, this method MUST return zero for such arrays.
 777   // For example, the VM used to store sub-word sized fields in full
 778   // words in the object layout, so that accessors like getByte(Object,int)
 779   // did not really do what one might expect for arrays.  Therefore,
 780   // this function used to report a zero scale factor, so that the user
 781   // would know not to attempt to access sub-word array elements.
 782   // // Code for unpacked fields:
 783   // if (scale < wordSize)  return 0;
 784 
 785   // The following allows for a pretty general fieldOffset cookie scheme,
 786   // but requires it to be linear in byte offset.
 787   return field_offset_from_byte_offset(scale) - field_offset_from_byte_offset(0);
 788 } UNSAFE_END
 789 
 790 
 791 UNSAFE_ENTRY(jlong, Unsafe_GetObjectSize0(JNIEnv* env, jobject o, jobject obj))
 792   oop p = JNIHandles::resolve(obj);
 793   return p->size() * HeapWordSize;
 794 UNSAFE_END
 795 
 796 
 797 static inline void throw_new(JNIEnv *env, const char *ename) {
 798   jclass cls = env->FindClass(ename);
 799   if (env->ExceptionCheck()) {
 800     env->ExceptionClear();
 801     tty->print_cr("Unsafe: cannot throw %s because FindClass has failed", ename);
 802     return;
 803   }
 804 
 805   env->ThrowNew(cls, nullptr);
 806 }
 807 
 808 static jclass Unsafe_DefineClass_impl(JNIEnv *env, jstring name, jbyteArray data, int offset, int length, jobject loader, jobject pd) {
 809   // Code lifted from JDK 1.3 ClassLoader.c
 810 
 811   jbyte *body;
 812   char *utfName = nullptr;
 813   jclass result = nullptr;
 814   char buf[128];
 815 
 816   assert(data != nullptr, "Class bytes must not be null");
 817   assert(length >= 0, "length must not be negative: %d", length);
 818 
 819   if (UsePerfData) {
 820     ClassLoader::unsafe_defineClassCallCounter()->inc();
 821   }
 822 
 823   body = NEW_C_HEAP_ARRAY_RETURN_NULL(jbyte, length, mtInternal);
 824   if (body == nullptr) {
 825     throw_new(env, "java/lang/OutOfMemoryError");
 826     return nullptr;
 827   }
 828 
 829   env->GetByteArrayRegion(data, offset, length, body);
 830   if (env->ExceptionOccurred()) {
 831     goto free_body;
 832   }
 833 
 834   if (name != nullptr) {
 835     uint len = env->GetStringUTFLength(name);
 836     int unicode_len = env->GetStringLength(name);
 837 
 838     if (len >= sizeof(buf)) {
 839       utfName = NEW_C_HEAP_ARRAY_RETURN_NULL(char, len + 1, mtInternal);
 840       if (utfName == nullptr) {
 841         throw_new(env, "java/lang/OutOfMemoryError");
 842         goto free_body;
 843       }
 844     } else {
 845       utfName = buf;
 846     }
 847 
 848     env->GetStringUTFRegion(name, 0, unicode_len, utfName);
 849 
 850     for (uint i = 0; i < len; i++) {
 851       if (utfName[i] == '.')   utfName[i] = '/';
 852     }
 853   }
 854 
 855   result = JVM_DefineClass(env, utfName, loader, body, length, pd);
 856 
 857   if (utfName && utfName != buf) {
 858     FREE_C_HEAP_ARRAY(char, utfName);
 859   }
 860 
 861  free_body:
 862   FREE_C_HEAP_ARRAY(jbyte, body);
 863   return result;
 864 }
 865 
 866 
 867 UNSAFE_ENTRY(jclass, Unsafe_DefineClass0(JNIEnv *env, jobject unsafe, jstring name, jbyteArray data, int offset, int length, jobject loader, jobject pd)) {
 868   ThreadToNativeFromVM ttnfv(thread);
 869 
 870   return Unsafe_DefineClass_impl(env, name, data, offset, length, loader, pd);
 871 } UNSAFE_END
 872 
 873 
 874 UNSAFE_ENTRY(void, Unsafe_ThrowException(JNIEnv *env, jobject unsafe, jthrowable thr)) {
 875   ThreadToNativeFromVM ttnfv(thread);
 876   env->Throw(thr);
 877 } UNSAFE_END
 878 
 879 // JSR166 ------------------------------------------------------------------
 880 
 881 UNSAFE_ENTRY(jobject, Unsafe_CompareAndExchangeReference(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject e_h, jobject x_h)) {
 882   oop x = JNIHandles::resolve(x_h);
 883   oop e = JNIHandles::resolve(e_h);
 884   oop p = JNIHandles::resolve(obj);
 885   assert_field_offset_sane(p, offset);
 886   oop res = HeapAccess<ON_UNKNOWN_OOP_REF>::oop_atomic_cmpxchg_at(p, (ptrdiff_t)offset, e, x);
 887   return JNIHandles::make_local(THREAD, res);
 888 } UNSAFE_END
 889 
 890 UNSAFE_ENTRY_SCOPED(jint, Unsafe_CompareAndExchangeInt(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jint e, jint x)) {
 891   oop p = JNIHandles::resolve(obj);
 892   volatile jint* addr = (volatile jint*)index_oop_from_field_offset_long(p, offset);
 893   return Atomic::cmpxchg(addr, e, x);
 894 } UNSAFE_END
 895 
 896 UNSAFE_ENTRY_SCOPED(jlong, Unsafe_CompareAndExchangeLong(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jlong e, jlong x)) {
 897   oop p = JNIHandles::resolve(obj);
 898   volatile jlong* addr = (volatile jlong*)index_oop_from_field_offset_long(p, offset);
 899   return Atomic::cmpxchg(addr, e, x);
 900 } UNSAFE_END
 901 
 902 UNSAFE_ENTRY(jboolean, Unsafe_CompareAndSetReference(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject e_h, jobject x_h)) {
 903   oop x = JNIHandles::resolve(x_h);
 904   oop e = JNIHandles::resolve(e_h);
 905   oop p = JNIHandles::resolve(obj);
 906   assert_field_offset_sane(p, offset);
 907   oop ret = HeapAccess<ON_UNKNOWN_OOP_REF>::oop_atomic_cmpxchg_at(p, (ptrdiff_t)offset, e, x);
 908   return ret == e;
 909 } UNSAFE_END
 910 
 911 UNSAFE_ENTRY_SCOPED(jboolean, Unsafe_CompareAndSetInt(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jint e, jint x)) {
 912   oop p = JNIHandles::resolve(obj);
 913   volatile jint* addr = (volatile jint*)index_oop_from_field_offset_long(p, offset);
 914   return Atomic::cmpxchg(addr, e, x) == e;
 915 } UNSAFE_END
 916 
 917 UNSAFE_ENTRY_SCOPED(jboolean, Unsafe_CompareAndSetLong(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jlong e, jlong x)) {
 918   oop p = JNIHandles::resolve(obj);
 919   volatile jlong* addr = (volatile jlong*)index_oop_from_field_offset_long(p, offset);
 920   return Atomic::cmpxchg(addr, e, x) == e;
 921 } UNSAFE_END
 922 
 923 static void post_thread_park_event(EventThreadPark* event, const oop obj, jlong timeout_nanos, jlong until_epoch_millis) {
 924   assert(event != nullptr, "invariant");
 925   event->set_parkedClass((obj != nullptr) ? obj->klass() : nullptr);
 926   event->set_timeout(timeout_nanos);
 927   event->set_until(until_epoch_millis);
 928   event->set_address((obj != nullptr) ? (u8)cast_from_oop<uintptr_t>(obj) : 0);
 929   event->commit();
 930 }
 931 
 932 UNSAFE_ENTRY(void, Unsafe_Park(JNIEnv *env, jobject unsafe, jboolean isAbsolute, jlong time)) {
 933   HOTSPOT_THREAD_PARK_BEGIN((uintptr_t) thread->parker(), (int) isAbsolute, time);
 934   EventThreadPark event;
 935 
 936   JavaThreadParkedState jtps(thread, time != 0);
 937   thread->parker()->park(isAbsolute != 0, time);
 938   if (event.should_commit()) {
 939     const oop obj = thread->current_park_blocker();
 940     if (time == 0) {
 941       post_thread_park_event(&event, obj, min_jlong, min_jlong);
 942     } else {
 943       if (isAbsolute != 0) {
 944         post_thread_park_event(&event, obj, min_jlong, time);
 945       } else {
 946         post_thread_park_event(&event, obj, time, min_jlong);
 947       }
 948     }
 949   }
 950   HOTSPOT_THREAD_PARK_END((uintptr_t) thread->parker());
 951 } UNSAFE_END
 952 
 953 UNSAFE_ENTRY(void, Unsafe_Unpark(JNIEnv *env, jobject unsafe, jobject jthread)) {
 954   if (jthread != nullptr) {
 955     oop thread_oop = JNIHandles::resolve_non_null(jthread);
 956     // Get the JavaThread* stored in the java.lang.Thread object _before_
 957     // the embedded ThreadsListHandle is constructed so we know if the
 958     // early life stage of the JavaThread* is protected. We use acquire
 959     // here to ensure that if we see a non-nullptr value, then we also
 960     // see the main ThreadsList updates from the JavaThread* being added.
 961     FastThreadsListHandle ftlh(thread_oop, java_lang_Thread::thread_acquire(thread_oop));
 962     JavaThread* thr = ftlh.protected_java_thread();
 963     if (thr != nullptr) {
 964       // The still live JavaThread* is protected by the FastThreadsListHandle
 965       // so it is safe to access.
 966       Parker* p = thr->parker();
 967       HOTSPOT_THREAD_UNPARK((uintptr_t) p);
 968       p->unpark();
 969     }
 970   } // FastThreadsListHandle is destroyed here.
 971 } UNSAFE_END
 972 
 973 UNSAFE_ENTRY(jint, Unsafe_GetLoadAverage0(JNIEnv *env, jobject unsafe, jdoubleArray loadavg, jint nelem)) {
 974   const int max_nelem = 3;
 975   double la[max_nelem];
 976   jint ret;
 977 
 978   typeArrayOop a = typeArrayOop(JNIHandles::resolve_non_null(loadavg));
 979   assert(a->is_typeArray(), "must be type array");
 980 
 981   ret = os::loadavg(la, nelem);
 982   if (ret == -1) {
 983     return -1;
 984   }
 985 
 986   // if successful, ret is the number of samples actually retrieved.
 987   assert(ret >= 0 && ret <= max_nelem, "Unexpected loadavg return value");
 988   switch(ret) {
 989     case 3: a->double_at_put(2, (jdouble)la[2]); // fall through
 990     case 2: a->double_at_put(1, (jdouble)la[1]); // fall through
 991     case 1: a->double_at_put(0, (jdouble)la[0]); break;
 992   }
 993 
 994   return ret;
 995 } UNSAFE_END
 996 
 997 
 998 /// JVM_RegisterUnsafeMethods
 999 
1000 #define ADR "J"
1001 
1002 #define LANG "Ljava/lang/"
1003 
1004 #define OBJ LANG "Object;"
1005 #define CLS LANG "Class;"
1006 #define FLD LANG "reflect/Field;"
1007 #define THR LANG "Throwable;"
1008 
1009 #define DC_Args  LANG "String;[BII" LANG "ClassLoader;" "Ljava/security/ProtectionDomain;"
1010 #define DAC_Args CLS "[B[" OBJ
1011 
1012 #define CC (char*)  /*cast a literal from (const char*)*/
1013 #define FN_PTR(f) CAST_FROM_FN_PTR(void*, &f)
1014 
1015 #define DECLARE_GETPUTOOP(Type, Desc) \
1016     {CC "get"  #Type,      CC "(" OBJ "J)" #Desc,                 FN_PTR(Unsafe_Get##Type)}, \
1017     {CC "put"  #Type,      CC "(" OBJ "J" #Desc ")V",             FN_PTR(Unsafe_Put##Type)}, \
1018     {CC "get"  #Type "Volatile",      CC "(" OBJ "J)" #Desc,      FN_PTR(Unsafe_Get##Type##Volatile)}, \
1019     {CC "put"  #Type "Volatile",      CC "(" OBJ "J" #Desc ")V",  FN_PTR(Unsafe_Put##Type##Volatile)}
1020 
1021 
1022 static JNINativeMethod jdk_internal_misc_Unsafe_methods[] = {
1023     {CC "getReference",         CC "(" OBJ "J)" OBJ "",   FN_PTR(Unsafe_GetReference)},
1024     {CC "putReference",         CC "(" OBJ "J" OBJ ")V",  FN_PTR(Unsafe_PutReference)},
1025     {CC "getReferenceVolatile", CC "(" OBJ "J)" OBJ,      FN_PTR(Unsafe_GetReferenceVolatile)},
1026     {CC "putReferenceVolatile", CC "(" OBJ "J" OBJ ")V",  FN_PTR(Unsafe_PutReferenceVolatile)},
1027 
1028     {CC "isFlatArray", CC "(" CLS ")Z",                   FN_PTR(Unsafe_IsFlatArray)},
1029     {CC "isFlatField0", CC "(" OBJ ")Z",                  FN_PTR(Unsafe_IsFlatField)},
1030     {CC "hasNullMarker0"   , CC "(" OBJ ")Z",                    FN_PTR(Unsafe_HasNullMarker)},
1031     {CC "nullMarkerOffset0", CC "(" OBJ ")I",                    FN_PTR(Unsafe_NullMarkerOffset)},
1032     {CC "getValue",         CC "(" OBJ "J" CLS ")" OBJ,   FN_PTR(Unsafe_GetValue)},
1033     {CC "putValue",         CC "(" OBJ "J" CLS OBJ ")V",  FN_PTR(Unsafe_PutValue)},
1034     {CC "uninitializedDefaultValue", CC "(" CLS ")" OBJ,  FN_PTR(Unsafe_UninitializedDefaultValue)},
1035     {CC "makePrivateBuffer",     CC "(" OBJ ")" OBJ,      FN_PTR(Unsafe_MakePrivateBuffer)},
1036     {CC "finishPrivateBuffer",   CC "(" OBJ ")" OBJ,      FN_PTR(Unsafe_FinishPrivateBuffer)},
1037     {CC "valueHeaderSize",       CC "(" CLS ")J",         FN_PTR(Unsafe_ValueHeaderSize)},
1038 
1039     {CC "getUncompressedObject", CC "(" ADR ")" OBJ,  FN_PTR(Unsafe_GetUncompressedObject)},
1040 
1041     DECLARE_GETPUTOOP(Boolean, Z),
1042     DECLARE_GETPUTOOP(Byte, B),
1043     DECLARE_GETPUTOOP(Short, S),
1044     DECLARE_GETPUTOOP(Char, C),
1045     DECLARE_GETPUTOOP(Int, I),
1046     DECLARE_GETPUTOOP(Long, J),
1047     DECLARE_GETPUTOOP(Float, F),
1048     DECLARE_GETPUTOOP(Double, D),
1049 
1050     {CC "allocateMemory0",    CC "(J)" ADR,              FN_PTR(Unsafe_AllocateMemory0)},
1051     {CC "reallocateMemory0",  CC "(" ADR "J)" ADR,       FN_PTR(Unsafe_ReallocateMemory0)},
1052     {CC "freeMemory0",        CC "(" ADR ")V",           FN_PTR(Unsafe_FreeMemory0)},
1053 
1054     {CC "objectFieldOffset0", CC "(" FLD ")J",           FN_PTR(Unsafe_ObjectFieldOffset0)},
1055     {CC "objectFieldOffset1", CC "(" CLS LANG "String;)J", FN_PTR(Unsafe_ObjectFieldOffset1)},
1056     {CC "staticFieldOffset0", CC "(" FLD ")J",           FN_PTR(Unsafe_StaticFieldOffset0)},
1057     {CC "staticFieldBase0",   CC "(" FLD ")" OBJ,        FN_PTR(Unsafe_StaticFieldBase0)},
1058     {CC "ensureClassInitialized0", CC "(" CLS ")V",      FN_PTR(Unsafe_EnsureClassInitialized0)},
1059     {CC "arrayBaseOffset0",   CC "(" CLS ")I",           FN_PTR(Unsafe_ArrayBaseOffset0)},
1060     {CC "arrayIndexScale0",   CC "(" CLS ")I",           FN_PTR(Unsafe_ArrayIndexScale0)},
1061     {CC "getObjectSize0",     CC "(Ljava/lang/Object;)J", FN_PTR(Unsafe_GetObjectSize0)},
1062 
1063     {CC "defineClass0",       CC "(" DC_Args ")" CLS,    FN_PTR(Unsafe_DefineClass0)},
1064     {CC "allocateInstance",   CC "(" CLS ")" OBJ,        FN_PTR(Unsafe_AllocateInstance)},
1065     {CC "throwException",     CC "(" THR ")V",           FN_PTR(Unsafe_ThrowException)},
1066     {CC "compareAndSetReference",CC "(" OBJ "J" OBJ "" OBJ ")Z", FN_PTR(Unsafe_CompareAndSetReference)},
1067     {CC "compareAndSetInt",   CC "(" OBJ "J""I""I"")Z",  FN_PTR(Unsafe_CompareAndSetInt)},
1068     {CC "compareAndSetLong",  CC "(" OBJ "J""J""J"")Z",  FN_PTR(Unsafe_CompareAndSetLong)},
1069     {CC "compareAndExchangeReference", CC "(" OBJ "J" OBJ "" OBJ ")" OBJ, FN_PTR(Unsafe_CompareAndExchangeReference)},
1070     {CC "compareAndExchangeInt",  CC "(" OBJ "J""I""I"")I", FN_PTR(Unsafe_CompareAndExchangeInt)},
1071     {CC "compareAndExchangeLong", CC "(" OBJ "J""J""J"")J", FN_PTR(Unsafe_CompareAndExchangeLong)},
1072 
1073     {CC "park",               CC "(ZJ)V",                FN_PTR(Unsafe_Park)},
1074     {CC "unpark",             CC "(" OBJ ")V",           FN_PTR(Unsafe_Unpark)},
1075 
1076     {CC "getLoadAverage0",    CC "([DI)I",               FN_PTR(Unsafe_GetLoadAverage0)},
1077 
1078     {CC "copyMemory0",        CC "(" OBJ "J" OBJ "JJ)V", FN_PTR(Unsafe_CopyMemory0)},
1079     {CC "copySwapMemory0",    CC "(" OBJ "J" OBJ "JJJ)V", FN_PTR(Unsafe_CopySwapMemory0)},
1080     {CC "writeback0",         CC "(" "J" ")V",           FN_PTR(Unsafe_WriteBack0)},
1081     {CC "writebackPreSync0",  CC "()V",                  FN_PTR(Unsafe_WriteBackPreSync0)},
1082     {CC "writebackPostSync0", CC "()V",                  FN_PTR(Unsafe_WriteBackPostSync0)},
1083     {CC "setMemory0",         CC "(" OBJ "JJB)V",        FN_PTR(Unsafe_SetMemory0)},
1084 
1085     {CC "shouldBeInitialized0", CC "(" CLS ")Z",         FN_PTR(Unsafe_ShouldBeInitialized0)},
1086 
1087     {CC "fullFence",          CC "()V",                  FN_PTR(Unsafe_FullFence)},
1088 };
1089 
1090 #undef CC
1091 #undef FN_PTR
1092 
1093 #undef ADR
1094 #undef LANG
1095 #undef OBJ
1096 #undef CLS
1097 #undef FLD
1098 #undef THR
1099 #undef DC_Args
1100 #undef DAC_Args
1101 
1102 #undef DECLARE_GETPUTOOP
1103 
1104 
1105 // This function is exported, used by NativeLookup.
1106 // The Unsafe_xxx functions above are called only from the interpreter.
1107 // The optimizer looks at names and signatures to recognize
1108 // individual functions.
1109 
1110 JVM_ENTRY(void, JVM_RegisterJDKInternalMiscUnsafeMethods(JNIEnv *env, jclass unsafeclass)) {
1111   ThreadToNativeFromVM ttnfv(thread);
1112 
1113   int ok = env->RegisterNatives(unsafeclass, jdk_internal_misc_Unsafe_methods, sizeof(jdk_internal_misc_Unsafe_methods)/sizeof(JNINativeMethod));
1114   guarantee(ok == 0, "register jdk.internal.misc.Unsafe natives");
1115 } JVM_END