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