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