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