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