1 /*
   2  * Copyright (c) 2000, 2018, 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/vmSymbols.hpp"
  30 #include "jfr/jfrEvents.hpp"
  31 #include "memory/allocation.inline.hpp"
  32 #include "memory/resourceArea.hpp"
  33 #include "logging/log.hpp"
  34 #include "logging/logStream.hpp"
  35 #include "oops/access.inline.hpp"
  36 #include "oops/fieldStreams.hpp"
  37 #include "oops/objArrayOop.inline.hpp"
  38 #include "oops/oop.inline.hpp"
  39 #include "oops/typeArrayOop.inline.hpp"
  40 #include "oops/valueArrayKlass.hpp"
  41 #include "oops/valueArrayOop.hpp"
  42 #include "oops/valueArrayOop.inline.hpp"
  43 #include "prims/unsafe.hpp"
  44 #include "runtime/atomic.hpp"
  45 #include "runtime/fieldDescriptor.inline.hpp"
  46 #include "runtime/globals.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/thread.hpp"
  52 #include "runtime/threadSMR.hpp"
  53 #include "runtime/vm_version.hpp"
  54 #include "services/threadService.hpp"
  55 #include "utilities/align.hpp"
  56 #include "utilities/copy.hpp"
  57 #include "utilities/dtrace.hpp"
  58 #include "utilities/macros.hpp"
  59 
  60 /**
  61  * Implementation of the jdk.internal.misc.Unsafe class
  62  */
  63 
  64 
  65 #define MAX_OBJECT_SIZE \
  66   ( arrayOopDesc::header_size(T_DOUBLE) * HeapWordSize \
  67     + ((julong)max_jint * sizeof(double)) )
  68 
  69 
  70 #define UNSAFE_ENTRY(result_type, header) \
  71   JVM_ENTRY(static result_type, header)
  72 
  73 #define UNSAFE_LEAF(result_type, header) \
  74   JVM_LEAF(static result_type, header)
  75 
  76 #define UNSAFE_END JVM_END
  77 
  78 
  79 static inline void* addr_from_java(jlong addr) {
  80   // This assert fails in a variety of ways on 32-bit systems.
  81   // It is impossible to predict whether native code that converts
  82   // pointers to longs will sign-extend or zero-extend the addresses.
  83   //assert(addr == (uintptr_t)addr, "must not be odd high bits");
  84   return (void*)(uintptr_t)addr;
  85 }
  86 
  87 static inline jlong addr_to_java(void* p) {
  88   assert(p == (void*)(uintptr_t)p, "must not be odd high bits");
  89   return (uintptr_t)p;
  90 }
  91 
  92 
  93 // Note: The VM's obj_field and related accessors use byte-scaled
  94 // ("unscaled") offsets, just as the unsafe methods do.
  95 
  96 // However, the method Unsafe.fieldOffset explicitly declines to
  97 // guarantee this.  The field offset values manipulated by the Java user
  98 // through the Unsafe API are opaque cookies that just happen to be byte
  99 // offsets.  We represent this state of affairs by passing the cookies
 100 // through conversion functions when going between the VM and the Unsafe API.
 101 // The conversion functions just happen to be no-ops at present.
 102 
 103 static inline jlong field_offset_to_byte_offset(jlong field_offset) {
 104   return field_offset;
 105 }
 106 
 107 static inline jlong field_offset_from_byte_offset(jlong byte_offset) {
 108   return byte_offset;
 109 }
 110 
 111 static inline void assert_field_offset_sane(oop p, jlong field_offset) {
 112 #ifdef ASSERT
 113   jlong byte_offset = field_offset_to_byte_offset(field_offset);
 114 
 115   if (p != NULL) {
 116     assert(byte_offset >= 0 && byte_offset <= (jlong)MAX_OBJECT_SIZE, "sane offset");
 117     if (byte_offset == (jint)byte_offset) {
 118       void* ptr_plus_disp = (address)p + byte_offset;
 119       assert(p->field_addr_raw((jint)byte_offset) == ptr_plus_disp,
 120              "raw [ptr+disp] must be consistent with oop::field_addr_raw");
 121     }
 122     jlong p_size = HeapWordSize * (jlong)(p->size());
 123     assert(byte_offset < p_size, "Unsafe access: offset " INT64_FORMAT " > object's size " INT64_FORMAT, (int64_t)byte_offset, (int64_t)p_size);
 124   }
 125 #endif
 126 }
 127 
 128 static inline void* index_oop_from_field_offset_long(oop p, jlong field_offset) {
 129   assert_field_offset_sane(p, field_offset);
 130   jlong byte_offset = field_offset_to_byte_offset(field_offset);
 131 
 132   if (p != NULL) {
 133     p = Access<>::resolve(p);
 134   }
 135 
 136   if (sizeof(char*) == sizeof(jint)) {   // (this constant folds!)
 137     return (address)p + (jint) byte_offset;
 138   } else {
 139     return (address)p +        byte_offset;
 140   }
 141 }
 142 
 143 // Externally callable versions:
 144 // (Use these in compiler intrinsics which emulate unsafe primitives.)
 145 jlong Unsafe_field_offset_to_byte_offset(jlong field_offset) {
 146   return field_offset;
 147 }
 148 jlong Unsafe_field_offset_from_byte_offset(jlong byte_offset) {
 149   return byte_offset;
 150 }
 151 
 152 ///// Data read/writes on the Java heap and in native (off-heap) memory
 153 
 154 /**
 155  * Helper class for accessing memory.
 156  *
 157  * Normalizes values and wraps accesses in
 158  * JavaThread::doing_unsafe_access() if needed.
 159  */
 160 template <typename T>
 161 class MemoryAccess : StackObj {
 162   JavaThread* _thread;
 163   oop _obj;
 164   ptrdiff_t _offset;
 165 
 166   // Resolves and returns the address of the memory access.
 167   // This raw memory access may fault, so we make sure it happens within the
 168   // guarded scope by making the access volatile at least. Since the store
 169   // of Thread::set_doing_unsafe_access() is also volatile, these accesses
 170   // can not be reordered by the compiler. Therefore, if the access triggers
 171   // a fault, we will know that Thread::doing_unsafe_access() returns true.
 172   volatile T* addr() {
 173     void* addr = index_oop_from_field_offset_long(_obj, _offset);
 174     return static_cast<volatile T*>(addr);
 175   }
 176 
 177   template <typename U>
 178   U normalize_for_write(U x) {
 179     return x;
 180   }
 181 
 182   jboolean normalize_for_write(jboolean x) {
 183     return x & 1;
 184   }
 185 
 186   template <typename U>
 187   U normalize_for_read(U x) {
 188     return x;
 189   }
 190 
 191   jboolean normalize_for_read(jboolean x) {
 192     return x != 0;
 193   }
 194 
 195   /**
 196    * Helper class to wrap memory accesses in JavaThread::doing_unsafe_access()
 197    */
 198   class GuardUnsafeAccess {
 199     JavaThread* _thread;
 200 
 201   public:
 202     GuardUnsafeAccess(JavaThread* thread) : _thread(thread) {
 203       // native/off-heap access which may raise SIGBUS if accessing
 204       // memory mapped file data in a region of the file which has
 205       // been truncated and is now invalid
 206       _thread->set_doing_unsafe_access(true);
 207     }
 208 
 209     ~GuardUnsafeAccess() {
 210       _thread->set_doing_unsafe_access(false);
 211     }
 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   void withfield(oop new_value, T x) {
 241     guarantee(_obj != NULL, "off heap value access unimplemented");      
 242     ValueKlass* vk = ValueKlass::cast(new_value->klass());
 243     vk->value_store(vk->data_for_oop(_obj), vk->data_for_oop(new_value), true, false);
 244     HeapAccess<>::store_at(new_value, _offset, normalize_for_write(x));
 245   }
 246 
 247   T get_volatile() {
 248     if (_obj == NULL) {
 249       GuardUnsafeAccess guard(_thread);
 250       volatile T ret = RawAccess<MO_SEQ_CST>::load(addr());
 251       return normalize_for_read(ret);
 252     } else {
 253       T ret = HeapAccess<MO_SEQ_CST>::load_at(_obj, _offset);
 254       return normalize_for_read(ret);
 255     }
 256   }
 257 
 258   void put_volatile(T x) {
 259     if (_obj == NULL) {
 260       GuardUnsafeAccess guard(_thread);
 261       RawAccess<MO_SEQ_CST>::store(addr(), normalize_for_write(x));
 262     } else {
 263       HeapAccess<MO_SEQ_CST>::store_at(_obj, _offset, normalize_for_write(x));
 264     }
 265   }
 266 };
 267 
 268 #ifdef ASSERT
 269 /*
 270  * Get the field descriptor of the field of the given object at the given offset.
 271  */
 272 static bool get_field_descriptor(oop p, jlong offset, fieldDescriptor* fd) {
 273   bool found = false;
 274   Klass* k = p->klass();
 275   if (k->is_instance_klass()) {
 276     InstanceKlass* ik = InstanceKlass::cast(k);
 277     found = ik->find_field_from_offset((int)offset, false, fd);
 278     if (!found && ik->is_mirror_instance_klass()) {
 279       Klass* k2 = java_lang_Class::as_Klass(p);
 280       if (k2->is_instance_klass()) {
 281         ik = InstanceKlass::cast(k2);
 282         found = ik->find_field_from_offset((int)offset, true, fd);
 283       }
 284     }
 285   }
 286   return found;
 287 }
 288 #endif // ASSERT
 289 
 290 static void assert_and_log_unsafe_value_access(oop p, jlong offset, ValueKlass* vk) {
 291   Klass* k = p->klass();
 292 #ifdef ASSERT
 293   if (k->is_instance_klass()) {
 294     assert_field_offset_sane(p, offset);
 295     fieldDescriptor fd;
 296     bool found = get_field_descriptor(p, offset, &fd);
 297     if (found) {
 298       assert(found, "value field not found");
 299       assert(fd.is_flattened(), "field not flat");
 300     } else {
 301       if (log_is_enabled(Trace, valuetypes)) {
 302         log_trace(valuetypes)("not a field in %s at offset " SIZE_FORMAT_HEX,
 303                               p->klass()->external_name(), offset);
 304       }
 305     }
 306   } else if (k->is_valueArray_klass()) {
 307     ValueArrayKlass* vak = ValueArrayKlass::cast(k);
 308     int index = (offset - vak->array_header_in_bytes()) / vak->element_byte_size();
 309     address dest = (address)((valueArrayOop)p)->value_at_addr(index, vak->layout_helper());
 310     assert(dest == ((address)p) + offset, "invalid offset");
 311   } else {
 312     ShouldNotReachHere();
 313   }
 314 #endif // ASSERT
 315   if (log_is_enabled(Trace, valuetypes)) {
 316     if (k->is_valueArray_klass()) {
 317       ValueArrayKlass* vak = ValueArrayKlass::cast(k);
 318       int index = (offset - vak->array_header_in_bytes()) / vak->element_byte_size();
 319       address dest = (address)((valueArrayOop)p)->value_at_addr(index, vak->layout_helper());
 320       log_trace(valuetypes)("%s array type %s index %d element size %d offset " SIZE_FORMAT_HEX " at " INTPTR_FORMAT,
 321                             p->klass()->external_name(), vak->external_name(),
 322                             index, vak->element_byte_size(), offset, p2i(dest));
 323     } else {
 324       log_trace(valuetypes)("%s field type %s at offset " SIZE_FORMAT_HEX,
 325                             p->klass()->external_name(), vk->external_name(), offset);
 326     }
 327   }
 328 }
 329 
 330 // These functions allow a null base pointer with an arbitrary address.
 331 // But if the base pointer is non-null, the offset should make some sense.
 332 // That is, it should be in the range [0, MAX_OBJECT_SIZE].
 333 UNSAFE_ENTRY(jobject, Unsafe_GetObject(JNIEnv *env, jobject unsafe, jobject obj, jlong offset)) {
 334   oop p = JNIHandles::resolve(obj);
 335   assert_field_offset_sane(p, offset);
 336   oop v = HeapAccess<ON_UNKNOWN_OOP_REF>::oop_load_at(p, offset);
 337   return JNIHandles::make_local(env, v);
 338 } UNSAFE_END
 339 
 340 UNSAFE_ENTRY(void, Unsafe_PutObject(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject x_h)) {
 341   oop x = JNIHandles::resolve(x_h);
 342   oop p = JNIHandles::resolve(obj);
 343   assert_field_offset_sane(p, offset);
 344   HeapAccess<ON_UNKNOWN_OOP_REF>::oop_store_at(p, offset, x);
 345 } UNSAFE_END
 346 
 347 UNSAFE_ENTRY(jlong, Unsafe_ValueHeaderSize(JNIEnv *env, jobject unsafe, jclass c)) {
 348   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(c));
 349   ValueKlass* vk = ValueKlass::cast(k);
 350   return vk->first_field_offset();
 351 } UNSAFE_END
 352 
 353 UNSAFE_ENTRY(jboolean, Unsafe_IsFlattenedArray(JNIEnv *env, jobject unsafe, jclass c)) {
 354   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(c));
 355   return k->is_valueArray_klass();
 356 } UNSAFE_END
 357 
 358 UNSAFE_ENTRY(jobject, Unsafe_GetValue(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jclass vc)) {
 359   oop base = JNIHandles::resolve(obj);
 360   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(vc));
 361   ValueKlass* vk = ValueKlass::cast(k);
 362   assert(!base->is_value() || base->mark()->is_larval_state(), "must be an object instance or a larval value");
 363   assert_and_log_unsafe_value_access(base, offset, vk);
 364   Handle base_h(THREAD, base);
 365   oop v = vk->allocate_instance(CHECK_NULL); // allocate instance
 366   vk->initialize(CHECK_NULL); // If field is a default value, value class might not be initialized yet
 367   vk->value_store(((address)(oopDesc*)base_h()) + offset,
 368                   vk->data_for_oop(v),
 369                   true, true);
 370   return JNIHandles::make_local(env, v);
 371 } UNSAFE_END
 372 
 373 UNSAFE_ENTRY(void, Unsafe_PutValue(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jclass vc, jobject value)) {
 374   oop base = JNIHandles::resolve(obj);
 375   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(vc));
 376   ValueKlass* vk = ValueKlass::cast(k);
 377   assert(!base->is_value() || base->mark()->is_larval_state(), "must be an object instance or a larval value");
 378   assert_and_log_unsafe_value_access(base, offset, vk);
 379   oop v = JNIHandles::resolve(value);
 380   vk->value_store(vk->data_for_oop(v),
 381                  ((address)(oopDesc*)base) + offset, true, true);
 382 } UNSAFE_END
 383 
 384 UNSAFE_ENTRY(jobject, Unsafe_StartPrivateBuffer(JNIEnv *env, jobject unsafe, jobject value)) {
 385   oop v = JNIHandles::resolve_non_null(value);
 386   assert(v->is_value(), "must be a value instance");
 387   Handle vh(THREAD, v);
 388   ValueKlass* vk = ValueKlass::cast(v->klass());
 389   instanceOop new_value = vk->allocate_instance(CHECK_NULL);
 390   vk->value_store(vk->data_for_oop(vh()), vk->data_for_oop(new_value), true, false);
 391   markOop mark = new_value->mark();
 392   new_value->set_mark(mark->enter_larval_state());
 393   return JNIHandles::make_local(env, new_value);
 394 } UNSAFE_END
 395 
 396 UNSAFE_ENTRY(jobject, Unsafe_FinishPrivateBuffer(JNIEnv *env, jobject unsafe, jobject value)) {
 397   oop v = JNIHandles::resolve(value);
 398   assert(v->mark()->is_larval_state(), "must be a larval value");
 399   markOop mark = v->mark();
 400   v->set_mark(mark->exit_larval_state());
 401   return JNIHandles::make_local(env, v);
 402 } UNSAFE_END
 403 
 404 UNSAFE_ENTRY(jobject, Unsafe_WithValue(JNIEnv *env, jobject unsafe, jclass vc, jobject obj, jlong vc_offset, jlong offset, jclass xc, jobject x)) {
 405   // base can be of any type T which is a value-within-a-value-within...-a-value
 406   // base+vc_offset is the address of a buffered value of VC
 407   // new_value is an instance of VC
 408   // new_value+offset is a buffered value of XC
 409   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(vc));
 410   ValueKlass* vk = ValueKlass::cast(k);
 411   oop base = JNIHandles::resolve(obj);
 412   Handle base_h(THREAD, base);
 413 
 414   Klass* field_k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(xc));
 415   ValueKlass* field_vk = ValueKlass::cast(field_k);
 416   oop x_oop = JNIHandles::resolve(x);
 417   assert(field_vk == x_oop->klass(), "Must match");
 418 
 419   if (log_is_enabled(Trace, valuetypes)) {
 420     LogTarget(Trace, valuetypes) lt;
 421     if (lt.is_enabled()) {
 422       ResourceMark rm(THREAD);
 423       LogStream ls(lt);
 424       outputStream* st = &ls;
 425       st->print_cr("withValue: object %s at " SIZE_FORMAT_HEX " container %s field type %s at offset " SIZE_FORMAT_HEX,
 426                     base_h->klass()->external_name(), vc_offset,
 427                     vk->external_name(), field_vk->external_name(), offset);
 428       base_h->print_on(st);              
 429     } 
 430   }
 431 
 432   // Create new value of VC by copying the value at vc_offset
 433   instanceOop new_value = vk->allocate_instance(CHECK_NULL);
 434   Handle new_value_h(THREAD, new_value);
 435   vk->value_store(((address)(oopDesc*)base_h()) + vc_offset, vk->data_for_oop(new_value), true, false);
 436   // patch xc_offset at new_value with x
 437   field_vk->value_store(field_vk->data_for_oop(x_oop),
 438                         ((address)(oopDesc*)new_value_h()) + offset, true, false);
 439   
 440   if (log_is_enabled(Trace, valuetypes)) {
 441     LogTarget(Trace, valuetypes) lt;
 442     if (lt.is_enabled()) {
 443       ResourceMark rm(THREAD);
 444       LogStream ls(lt);
 445       outputStream* st = &ls;
 446       st->print_cr("------ after patching ---- ");
 447       new_value_h->print_on(st);   
 448     }           
 449   }                 
 450   return JNIHandles::make_local(env, new_value_h());
 451 } UNSAFE_END
 452 
 453 UNSAFE_ENTRY(jobject, Unsafe_WithReference(JNIEnv *env, jobject unsafe, jclass vc, jobject obj, jlong offset, jobject x)) {
 454   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(vc));
 455   ValueKlass* vk = ValueKlass::cast(k);
 456   oop base = JNIHandles::resolve(obj);
 457   Handle base_h(THREAD, base);
 458   assert_field_offset_sane(base, offset);
 459   
 460   instanceOop new_value = vk->allocate_instance(CHECK_NULL);
 461   vk->value_store(((address)(oopDesc*)base_h()) + vk->first_field_offset(), vk->data_for_oop(new_value), true, false);
 462   oop x_oop = JNIHandles::resolve(x);
 463   new_value->obj_field_put(offset, x_oop);
 464   return JNIHandles::make_local(env, new_value);
 465 } UNSAFE_END
 466 
 467 UNSAFE_ENTRY(jobject, Unsafe_GetObjectVolatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset)) {
 468   oop p = JNIHandles::resolve(obj);
 469   assert_field_offset_sane(p, offset);
 470   oop v = HeapAccess<MO_SEQ_CST | ON_UNKNOWN_OOP_REF>::oop_load_at(p, offset);
 471   return JNIHandles::make_local(env, v);
 472 } UNSAFE_END
 473 
 474 UNSAFE_ENTRY(void, Unsafe_PutObjectVolatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject x_h)) {
 475   oop x = JNIHandles::resolve(x_h);
 476   oop p = JNIHandles::resolve(obj);
 477   assert_field_offset_sane(p, offset);
 478   HeapAccess<MO_SEQ_CST | ON_UNKNOWN_OOP_REF>::oop_store_at(p, offset, x);
 479 } UNSAFE_END
 480 
 481 UNSAFE_ENTRY(jobject, Unsafe_GetUncompressedObject(JNIEnv *env, jobject unsafe, jlong addr)) {
 482   oop v = *(oop*) (address) addr;
 483   return JNIHandles::make_local(env, v);
 484 } UNSAFE_END
 485 
 486 UNSAFE_LEAF(jboolean, Unsafe_isBigEndian0(JNIEnv *env, jobject unsafe)) {
 487 #ifdef VM_LITTLE_ENDIAN
 488   return false;
 489 #else
 490   return true;
 491 #endif
 492 } UNSAFE_END
 493 
 494 UNSAFE_LEAF(jint, Unsafe_unalignedAccess0(JNIEnv *env, jobject unsafe)) {
 495   return UseUnalignedAccesses;
 496 } UNSAFE_END
 497 
 498 #define DEFINE_GETSETOOP(java_type, Type) \
 499  \
 500 UNSAFE_ENTRY(java_type, Unsafe_Get##Type(JNIEnv *env, jobject unsafe, jobject obj, jlong offset)) { \
 501   return MemoryAccess<java_type>(thread, obj, offset).get(); \
 502 } UNSAFE_END \
 503  \
 504 UNSAFE_ENTRY(void, Unsafe_Put##Type(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, java_type x)) { \
 505   MemoryAccess<java_type>(thread, obj, offset).put(x); \
 506 } UNSAFE_END \
 507  \
 508 UNSAFE_ENTRY(jobject, Unsafe_With##Type(JNIEnv *env, jobject unsafe, jclass vc, jobject obj, jlong offset, java_type x)) { \
 509   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(vc)); \
 510   ValueKlass* vk = ValueKlass::cast(k); \
 511   instanceOop new_value = vk->allocate_instance(CHECK_NULL); \
 512   MemoryAccess<java_type>(thread, obj, offset).withfield(new_value, x); \
 513   return JNIHandles::make_local(env, new_value); \
 514 } UNSAFE_END \
 515  \
 516 // END DEFINE_GETSETOOP.
 517 
 518 DEFINE_GETSETOOP(jboolean, Boolean)
 519 DEFINE_GETSETOOP(jbyte, Byte)
 520 DEFINE_GETSETOOP(jshort, Short);
 521 DEFINE_GETSETOOP(jchar, Char);
 522 DEFINE_GETSETOOP(jint, Int);
 523 DEFINE_GETSETOOP(jlong, Long);
 524 DEFINE_GETSETOOP(jfloat, Float);
 525 DEFINE_GETSETOOP(jdouble, Double);
 526 
 527 #undef DEFINE_GETSETOOP
 528 
 529 #define DEFINE_GETSETOOP_VOLATILE(java_type, Type) \
 530  \
 531 UNSAFE_ENTRY(java_type, Unsafe_Get##Type##Volatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset)) { \
 532   return MemoryAccess<java_type>(thread, obj, offset).get_volatile(); \
 533 } UNSAFE_END \
 534  \
 535 UNSAFE_ENTRY(void, Unsafe_Put##Type##Volatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, java_type x)) { \
 536   MemoryAccess<java_type>(thread, obj, offset).put_volatile(x); \
 537 } UNSAFE_END \
 538  \
 539 // END DEFINE_GETSETOOP_VOLATILE.
 540 
 541 DEFINE_GETSETOOP_VOLATILE(jboolean, Boolean)
 542 DEFINE_GETSETOOP_VOLATILE(jbyte, Byte)
 543 DEFINE_GETSETOOP_VOLATILE(jshort, Short);
 544 DEFINE_GETSETOOP_VOLATILE(jchar, Char);
 545 DEFINE_GETSETOOP_VOLATILE(jint, Int);
 546 DEFINE_GETSETOOP_VOLATILE(jlong, Long);
 547 DEFINE_GETSETOOP_VOLATILE(jfloat, Float);
 548 DEFINE_GETSETOOP_VOLATILE(jdouble, Double);
 549 
 550 #undef DEFINE_GETSETOOP_VOLATILE
 551 
 552 UNSAFE_LEAF(void, Unsafe_LoadFence(JNIEnv *env, jobject unsafe)) {
 553   OrderAccess::acquire();
 554 } UNSAFE_END
 555 
 556 UNSAFE_LEAF(void, Unsafe_StoreFence(JNIEnv *env, jobject unsafe)) {
 557   OrderAccess::release();
 558 } UNSAFE_END
 559 
 560 UNSAFE_LEAF(void, Unsafe_FullFence(JNIEnv *env, jobject unsafe)) {
 561   OrderAccess::fence();
 562 } UNSAFE_END
 563 
 564 ////// Allocation requests
 565 
 566 UNSAFE_ENTRY(jobject, Unsafe_AllocateInstance(JNIEnv *env, jobject unsafe, jclass cls)) {
 567   ThreadToNativeFromVM ttnfv(thread);
 568   return env->AllocObject(cls);
 569 } UNSAFE_END
 570 
 571 UNSAFE_ENTRY(jlong, Unsafe_AllocateMemory0(JNIEnv *env, jobject unsafe, jlong size)) {
 572   size_t sz = (size_t)size;
 573 
 574   sz = align_up(sz, HeapWordSize);
 575   void* x = os::malloc(sz, mtOther);
 576 
 577   return addr_to_java(x);
 578 } UNSAFE_END
 579 
 580 UNSAFE_ENTRY(jlong, Unsafe_ReallocateMemory0(JNIEnv *env, jobject unsafe, jlong addr, jlong size)) {
 581   void* p = addr_from_java(addr);
 582   size_t sz = (size_t)size;
 583   sz = align_up(sz, HeapWordSize);
 584 
 585   void* x = os::realloc(p, sz, mtOther);
 586 
 587   return addr_to_java(x);
 588 } UNSAFE_END
 589 
 590 UNSAFE_ENTRY(void, Unsafe_FreeMemory0(JNIEnv *env, jobject unsafe, jlong addr)) {
 591   void* p = addr_from_java(addr);
 592 
 593   os::free(p);
 594 } UNSAFE_END
 595 
 596 UNSAFE_ENTRY(void, Unsafe_SetMemory0(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jlong size, jbyte value)) {
 597   size_t sz = (size_t)size;
 598 
 599   oop base = JNIHandles::resolve(obj);
 600   void* p = index_oop_from_field_offset_long(base, offset);
 601 
 602   Copy::fill_to_memory_atomic(p, sz, value);
 603 } UNSAFE_END
 604 
 605 UNSAFE_ENTRY(void, Unsafe_CopyMemory0(JNIEnv *env, jobject unsafe, jobject srcObj, jlong srcOffset, jobject dstObj, jlong dstOffset, jlong size)) {
 606   size_t sz = (size_t)size;
 607 
 608   oop srcp = JNIHandles::resolve(srcObj);
 609   oop dstp = JNIHandles::resolve(dstObj);
 610 
 611   void* src = index_oop_from_field_offset_long(srcp, srcOffset);
 612   void* dst = index_oop_from_field_offset_long(dstp, dstOffset);
 613 
 614   Copy::conjoint_memory_atomic(src, dst, sz);
 615 } UNSAFE_END
 616 
 617 // This function is a leaf since if the source and destination are both in native memory
 618 // the copy may potentially be very large, and we don't want to disable GC if we can avoid it.
 619 // If either source or destination (or both) are on the heap, the function will enter VM using
 620 // JVM_ENTRY_FROM_LEAF
 621 UNSAFE_LEAF(void, Unsafe_CopySwapMemory0(JNIEnv *env, jobject unsafe, jobject srcObj, jlong srcOffset, jobject dstObj, jlong dstOffset, jlong size, jlong elemSize)) {
 622   size_t sz = (size_t)size;
 623   size_t esz = (size_t)elemSize;
 624 
 625   if (srcObj == NULL && dstObj == NULL) {
 626     // Both src & dst are in native memory
 627     address src = (address)srcOffset;
 628     address dst = (address)dstOffset;
 629 
 630     Copy::conjoint_swap(src, dst, sz, esz);
 631   } else {
 632     // At least one of src/dst are on heap, transition to VM to access raw pointers
 633 
 634     JVM_ENTRY_FROM_LEAF(env, void, Unsafe_CopySwapMemory0) {
 635       oop srcp = JNIHandles::resolve(srcObj);
 636       oop dstp = JNIHandles::resolve(dstObj);
 637 
 638       address src = (address)index_oop_from_field_offset_long(srcp, srcOffset);
 639       address dst = (address)index_oop_from_field_offset_long(dstp, dstOffset);
 640 
 641       Copy::conjoint_swap(src, dst, sz, esz);
 642     } JVM_END
 643   }
 644 } UNSAFE_END
 645 
 646 ////// Random queries
 647 
 648 UNSAFE_LEAF(jint, Unsafe_AddressSize0(JNIEnv *env, jobject unsafe)) {
 649   return sizeof(void*);
 650 } UNSAFE_END
 651 
 652 UNSAFE_LEAF(jint, Unsafe_PageSize()) {
 653   return os::vm_page_size();
 654 } UNSAFE_END
 655 
 656 static jlong find_field_offset(jclass clazz, jstring name, TRAPS) {
 657   assert(clazz != NULL, "clazz must not be NULL");
 658   assert(name != NULL, "name must not be NULL");
 659 
 660   ResourceMark rm(THREAD);
 661   char *utf_name = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(name));
 662 
 663   InstanceKlass* k = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(clazz)));
 664 
 665   jint offset = -1;
 666   for (JavaFieldStream fs(k); !fs.done(); fs.next()) {
 667     Symbol *name = fs.name();
 668     if (name->equals(utf_name)) {
 669       offset = fs.offset();
 670       break;
 671     }
 672   }
 673   if (offset < 0) {
 674     THROW_0(vmSymbols::java_lang_InternalError());
 675   }
 676   return field_offset_from_byte_offset(offset);
 677 }
 678 
 679 static jlong find_field_offset(jobject field, int must_be_static, TRAPS) {
 680   assert(field != NULL, "field must not be NULL");
 681 
 682   oop reflected   = JNIHandles::resolve_non_null(field);
 683   oop mirror      = java_lang_reflect_Field::clazz(reflected);
 684   Klass* k        = java_lang_Class::as_Klass(mirror);
 685   int slot        = java_lang_reflect_Field::slot(reflected);
 686   int modifiers   = java_lang_reflect_Field::modifiers(reflected);
 687 
 688   if (must_be_static >= 0) {
 689     int really_is_static = ((modifiers & JVM_ACC_STATIC) != 0);
 690     if (must_be_static != really_is_static) {
 691       THROW_0(vmSymbols::java_lang_IllegalArgumentException());
 692     }
 693   }
 694 
 695   int offset = InstanceKlass::cast(k)->field_offset(slot);
 696   return field_offset_from_byte_offset(offset);
 697 }
 698 
 699 UNSAFE_ENTRY(jlong, Unsafe_ObjectFieldOffset0(JNIEnv *env, jobject unsafe, jobject field)) {
 700   return find_field_offset(field, 0, THREAD);
 701 } UNSAFE_END
 702 
 703 UNSAFE_ENTRY(jlong, Unsafe_ObjectFieldOffset1(JNIEnv *env, jobject unsafe, jclass c, jstring name)) {
 704   return find_field_offset(c, name, THREAD);
 705 } UNSAFE_END
 706 
 707 UNSAFE_ENTRY(jlong, Unsafe_StaticFieldOffset0(JNIEnv *env, jobject unsafe, jobject field)) {
 708   return find_field_offset(field, 1, THREAD);
 709 } UNSAFE_END
 710 
 711 UNSAFE_ENTRY(jobject, Unsafe_StaticFieldBase0(JNIEnv *env, jobject unsafe, jobject field)) {
 712   assert(field != NULL, "field must not be NULL");
 713 
 714   // Note:  In this VM implementation, a field address is always a short
 715   // offset from the base of a a klass metaobject.  Thus, the full dynamic
 716   // range of the return type is never used.  However, some implementations
 717   // might put the static field inside an array shared by many classes,
 718   // or even at a fixed address, in which case the address could be quite
 719   // large.  In that last case, this function would return NULL, since
 720   // the address would operate alone, without any base pointer.
 721 
 722   oop reflected   = JNIHandles::resolve_non_null(field);
 723   oop mirror      = java_lang_reflect_Field::clazz(reflected);
 724   int modifiers   = java_lang_reflect_Field::modifiers(reflected);
 725 
 726   if ((modifiers & JVM_ACC_STATIC) == 0) {
 727     THROW_0(vmSymbols::java_lang_IllegalArgumentException());
 728   }
 729 
 730   return JNIHandles::make_local(env, mirror);
 731 } UNSAFE_END
 732 
 733 UNSAFE_ENTRY(void, Unsafe_EnsureClassInitialized0(JNIEnv *env, jobject unsafe, jobject clazz)) {
 734   assert(clazz != NULL, "clazz must not be NULL");
 735 
 736   oop mirror = JNIHandles::resolve_non_null(clazz);
 737 
 738   Klass* klass = java_lang_Class::as_Klass(mirror);
 739   if (klass != NULL && klass->should_be_initialized()) {
 740     InstanceKlass* k = InstanceKlass::cast(klass);
 741     k->initialize(CHECK);
 742   }
 743 }
 744 UNSAFE_END
 745 
 746 UNSAFE_ENTRY(jboolean, Unsafe_ShouldBeInitialized0(JNIEnv *env, jobject unsafe, jobject clazz)) {
 747   assert(clazz != NULL, "clazz must not be NULL");
 748 
 749   oop mirror = JNIHandles::resolve_non_null(clazz);
 750   Klass* klass = java_lang_Class::as_Klass(mirror);
 751 
 752   if (klass != NULL && klass->should_be_initialized()) {
 753     return true;
 754   }
 755 
 756   return false;
 757 }
 758 UNSAFE_END
 759 
 760 static void getBaseAndScale(int& base, int& scale, jclass clazz, TRAPS) {
 761   assert(clazz != NULL, "clazz must not be NULL");
 762 
 763   oop mirror = JNIHandles::resolve_non_null(clazz);
 764   Klass* k = java_lang_Class::as_Klass(mirror);
 765 
 766   if (k == NULL || !k->is_array_klass()) {
 767     THROW(vmSymbols::java_lang_InvalidClassException());
 768   } else if (k->is_objArray_klass()) {
 769     base  = arrayOopDesc::base_offset_in_bytes(T_OBJECT);
 770     scale = heapOopSize;
 771   } else if (k->is_typeArray_klass()) {
 772     TypeArrayKlass* tak = TypeArrayKlass::cast(k);
 773     base  = tak->array_header_in_bytes();
 774     assert(base == arrayOopDesc::base_offset_in_bytes(tak->element_type()), "array_header_size semantics ok");
 775     scale = (1 << tak->log2_element_size());
 776   } else if (k->is_valueArray_klass()) {
 777     ValueArrayKlass* vak = ValueArrayKlass::cast(k);
 778     ValueKlass* vklass = vak->element_klass();
 779     base = vak->array_header_in_bytes();
 780     scale = vak->element_byte_size();
 781   } else {
 782     ShouldNotReachHere();
 783   }
 784 }
 785 
 786 UNSAFE_ENTRY(jint, Unsafe_ArrayBaseOffset0(JNIEnv *env, jobject unsafe, jclass clazz)) {
 787   int base = 0, scale = 0;
 788   getBaseAndScale(base, scale, clazz, CHECK_0);
 789 
 790   return field_offset_from_byte_offset(base);
 791 } UNSAFE_END
 792 
 793 
 794 UNSAFE_ENTRY(jint, Unsafe_ArrayIndexScale0(JNIEnv *env, jobject unsafe, jclass clazz)) {
 795   int base = 0, scale = 0;
 796   getBaseAndScale(base, scale, clazz, CHECK_0);
 797 
 798   // This VM packs both fields and array elements down to the byte.
 799   // But watch out:  If this changes, so that array references for
 800   // a given primitive type (say, T_BOOLEAN) use different memory units
 801   // than fields, this method MUST return zero for such arrays.
 802   // For example, the VM used to store sub-word sized fields in full
 803   // words in the object layout, so that accessors like getByte(Object,int)
 804   // did not really do what one might expect for arrays.  Therefore,
 805   // this function used to report a zero scale factor, so that the user
 806   // would know not to attempt to access sub-word array elements.
 807   // // Code for unpacked fields:
 808   // if (scale < wordSize)  return 0;
 809 
 810   // The following allows for a pretty general fieldOffset cookie scheme,
 811   // but requires it to be linear in byte offset.
 812   return field_offset_from_byte_offset(scale) - field_offset_from_byte_offset(0);
 813 } UNSAFE_END
 814 
 815 
 816 static inline void throw_new(JNIEnv *env, const char *ename) {
 817   jclass cls = env->FindClass(ename);
 818   if (env->ExceptionCheck()) {
 819     env->ExceptionClear();
 820     tty->print_cr("Unsafe: cannot throw %s because FindClass has failed", ename);
 821     return;
 822   }
 823 
 824   env->ThrowNew(cls, NULL);
 825 }
 826 
 827 static jclass Unsafe_DefineClass_impl(JNIEnv *env, jstring name, jbyteArray data, int offset, int length, jobject loader, jobject pd) {
 828   // Code lifted from JDK 1.3 ClassLoader.c
 829 
 830   jbyte *body;
 831   char *utfName = NULL;
 832   jclass result = 0;
 833   char buf[128];
 834 
 835   assert(data != NULL, "Class bytes must not be NULL");
 836   assert(length >= 0, "length must not be negative: %d", length);
 837 
 838   if (UsePerfData) {
 839     ClassLoader::unsafe_defineClassCallCounter()->inc();
 840   }
 841 
 842   body = NEW_C_HEAP_ARRAY(jbyte, length, mtInternal);
 843   if (body == NULL) {
 844     throw_new(env, "java/lang/OutOfMemoryError");
 845     return 0;
 846   }
 847 
 848   env->GetByteArrayRegion(data, offset, length, body);
 849   if (env->ExceptionOccurred()) {
 850     goto free_body;
 851   }
 852 
 853   if (name != NULL) {
 854     uint len = env->GetStringUTFLength(name);
 855     int unicode_len = env->GetStringLength(name);
 856 
 857     if (len >= sizeof(buf)) {
 858       utfName = NEW_C_HEAP_ARRAY(char, len + 1, mtInternal);
 859       if (utfName == NULL) {
 860         throw_new(env, "java/lang/OutOfMemoryError");
 861         goto free_body;
 862       }
 863     } else {
 864       utfName = buf;
 865     }
 866 
 867     env->GetStringUTFRegion(name, 0, unicode_len, utfName);
 868 
 869     for (uint i = 0; i < len; i++) {
 870       if (utfName[i] == '.')   utfName[i] = '/';
 871     }
 872   }
 873 
 874   result = JVM_DefineClass(env, utfName, loader, body, length, pd);
 875 
 876   if (utfName && utfName != buf) {
 877     FREE_C_HEAP_ARRAY(char, utfName);
 878   }
 879 
 880  free_body:
 881   FREE_C_HEAP_ARRAY(jbyte, body);
 882   return result;
 883 }
 884 
 885 
 886 UNSAFE_ENTRY(jclass, Unsafe_DefineClass0(JNIEnv *env, jobject unsafe, jstring name, jbyteArray data, int offset, int length, jobject loader, jobject pd)) {
 887   ThreadToNativeFromVM ttnfv(thread);
 888 
 889   return Unsafe_DefineClass_impl(env, name, data, offset, length, loader, pd);
 890 } UNSAFE_END
 891 
 892 
 893 // define a class but do not make it known to the class loader or system dictionary
 894 // - host_class:  supplies context for linkage, access control, protection domain, and class loader
 895 //                if host_class is itself anonymous then it is replaced with its host class.
 896 // - data:  bytes of a class file, a raw memory address (length gives the number of bytes)
 897 // - cp_patches:  where non-null entries exist, they replace corresponding CP entries in data
 898 
 899 // When you load an anonymous class U, it works as if you changed its name just before loading,
 900 // to a name that you will never use again.  Since the name is lost, no other class can directly
 901 // link to any member of U.  Just after U is loaded, the only way to use it is reflectively,
 902 // through java.lang.Class methods like Class.newInstance.
 903 
 904 // The package of an anonymous class must either match its host's class's package or be in the
 905 // unnamed package.  If it is in the unnamed package then it will be put in its host class's
 906 // package.
 907 //
 908 
 909 // Access checks for linkage sites within U continue to follow the same rules as for named classes.
 910 // An anonymous class also has special privileges to access any member of its host class.
 911 // This is the main reason why this loading operation is unsafe.  The purpose of this is to
 912 // allow language implementations to simulate "open classes"; a host class in effect gets
 913 // new code when an anonymous class is loaded alongside it.  A less convenient but more
 914 // standard way to do this is with reflection, which can also be set to ignore access
 915 // restrictions.
 916 
 917 // Access into an anonymous class is possible only through reflection.  Therefore, there
 918 // are no special access rules for calling into an anonymous class.  The relaxed access
 919 // rule for the host class is applied in the opposite direction:  A host class reflectively
 920 // access one of its anonymous classes.
 921 
 922 // If you load the same bytecodes twice, you get two different classes.  You can reload
 923 // the same bytecodes with or without varying CP patches.
 924 
 925 // By using the CP patching array, you can have a new anonymous class U2 refer to an older one U1.
 926 // The bytecodes for U2 should refer to U1 by a symbolic name (doesn't matter what the name is).
 927 // The CONSTANT_Class entry for that name can be patched to refer directly to U1.
 928 
 929 // This allows, for example, U2 to use U1 as a superclass or super-interface, or as
 930 // an outer class (so that U2 is an anonymous inner class of anonymous U1).
 931 // It is not possible for a named class, or an older anonymous class, to refer by
 932 // name (via its CP) to a newer anonymous class.
 933 
 934 // CP patching may also be used to modify (i.e., hack) the names of methods, classes,
 935 // or type descriptors used in the loaded anonymous class.
 936 
 937 // Finally, CP patching may be used to introduce "live" objects into the constant pool,
 938 // instead of "dead" strings.  A compiled statement like println((Object)"hello") can
 939 // be changed to println(greeting), where greeting is an arbitrary object created before
 940 // the anonymous class is loaded.  This is useful in dynamic languages, in which
 941 // various kinds of metaobjects must be introduced as constants into bytecode.
 942 // Note the cast (Object), which tells the verifier to expect an arbitrary object,
 943 // not just a literal string.  For such ldc instructions, the verifier uses the
 944 // type Object instead of String, if the loaded constant is not in fact a String.
 945 
 946 static InstanceKlass*
 947 Unsafe_DefineAnonymousClass_impl(JNIEnv *env,
 948                                  jclass host_class, jbyteArray data, jobjectArray cp_patches_jh,
 949                                  u1** temp_alloc,
 950                                  TRAPS) {
 951   assert(host_class != NULL, "host_class must not be NULL");
 952   assert(data != NULL, "data must not be NULL");
 953 
 954   if (UsePerfData) {
 955     ClassLoader::unsafe_defineClassCallCounter()->inc();
 956   }
 957 
 958   jint length = typeArrayOop(JNIHandles::resolve_non_null(data))->length();
 959   assert(length >= 0, "class_bytes_length must not be negative: %d", length);
 960 
 961   int class_bytes_length = (int) length;
 962 
 963   u1* class_bytes = NEW_C_HEAP_ARRAY(u1, length, mtInternal);
 964   if (class_bytes == NULL) {
 965     THROW_0(vmSymbols::java_lang_OutOfMemoryError());
 966   }
 967 
 968   // caller responsible to free it:
 969   *temp_alloc = class_bytes;
 970 
 971   ArrayAccess<>::arraycopy_to_native(arrayOop(JNIHandles::resolve_non_null(data)), typeArrayOopDesc::element_offset<jbyte>(0),
 972                                      reinterpret_cast<jbyte*>(class_bytes), length);
 973 
 974   objArrayHandle cp_patches_h;
 975   if (cp_patches_jh != NULL) {
 976     oop p = JNIHandles::resolve_non_null(cp_patches_jh);
 977     assert(p->is_objArray(), "cp_patches must be an object[]");
 978     cp_patches_h = objArrayHandle(THREAD, (objArrayOop)p);
 979   }
 980 
 981   const Klass* host_klass = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(host_class));
 982 
 983   // Make sure it's the real host class, not another anonymous class.
 984   while (host_klass != NULL && host_klass->is_instance_klass() &&
 985          InstanceKlass::cast(host_klass)->is_unsafe_anonymous()) {
 986     host_klass = InstanceKlass::cast(host_klass)->unsafe_anonymous_host();
 987   }
 988 
 989   // Primitive types have NULL Klass* fields in their java.lang.Class instances.
 990   if (host_klass == NULL) {
 991     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Host class is null");
 992   }
 993 
 994   assert(host_klass->is_instance_klass(), "Host class must be an instance class");
 995 
 996   const char* host_source = host_klass->external_name();
 997   Handle      host_loader(THREAD, host_klass->class_loader());
 998   Handle      host_domain(THREAD, host_klass->protection_domain());
 999 
1000   GrowableArray<Handle>* cp_patches = NULL;
1001 
1002   if (cp_patches_h.not_null()) {
1003     int alen = cp_patches_h->length();
1004 
1005     for (int i = alen-1; i >= 0; i--) {
1006       oop p = cp_patches_h->obj_at(i);
1007       if (p != NULL) {
1008         Handle patch(THREAD, p);
1009 
1010         if (cp_patches == NULL) {
1011           cp_patches = new GrowableArray<Handle>(i+1, i+1, Handle());
1012         }
1013 
1014         cp_patches->at_put(i, patch);
1015       }
1016     }
1017   }
1018 
1019   ClassFileStream st(class_bytes, class_bytes_length, host_source, ClassFileStream::verify);
1020 
1021   Symbol* no_class_name = NULL;
1022   Klass* anonk = SystemDictionary::parse_stream(no_class_name,
1023                                                 host_loader,
1024                                                 host_domain,
1025                                                 &st,
1026                                                 InstanceKlass::cast(host_klass),
1027                                                 cp_patches,
1028                                                 CHECK_NULL);
1029   if (anonk == NULL) {
1030     return NULL;
1031   }
1032 
1033   return InstanceKlass::cast(anonk);
1034 }
1035 
1036 UNSAFE_ENTRY(jclass, Unsafe_DefineAnonymousClass0(JNIEnv *env, jobject unsafe, jclass host_class, jbyteArray data, jobjectArray cp_patches_jh)) {
1037   ResourceMark rm(THREAD);
1038 
1039   jobject res_jh = NULL;
1040   u1* temp_alloc = NULL;
1041 
1042   InstanceKlass* anon_klass = Unsafe_DefineAnonymousClass_impl(env, host_class, data, cp_patches_jh, &temp_alloc, THREAD);
1043   if (anon_klass != NULL) {
1044     res_jh = JNIHandles::make_local(env, anon_klass->java_mirror());
1045   }
1046 
1047   // try/finally clause:
1048   if (temp_alloc != NULL) {
1049     FREE_C_HEAP_ARRAY(u1, temp_alloc);
1050   }
1051 
1052   // The anonymous class loader data has been artificially been kept alive to
1053   // this point.   The mirror and any instances of this class have to keep
1054   // it alive afterwards.
1055   if (anon_klass != NULL) {
1056     anon_klass->class_loader_data()->dec_keep_alive();
1057   }
1058 
1059   // let caller initialize it as needed...
1060 
1061   return (jclass) res_jh;
1062 } UNSAFE_END
1063 
1064 
1065 
1066 UNSAFE_ENTRY(void, Unsafe_ThrowException(JNIEnv *env, jobject unsafe, jthrowable thr)) {
1067   ThreadToNativeFromVM ttnfv(thread);
1068   env->Throw(thr);
1069 } UNSAFE_END
1070 
1071 // JSR166 ------------------------------------------------------------------
1072 
1073 UNSAFE_ENTRY(jobject, Unsafe_CompareAndExchangeObject(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject e_h, jobject x_h)) {
1074   oop x = JNIHandles::resolve(x_h);
1075   oop e = JNIHandles::resolve(e_h);
1076   oop p = JNIHandles::resolve(obj);
1077   assert_field_offset_sane(p, offset);
1078   oop res = HeapAccess<ON_UNKNOWN_OOP_REF>::oop_atomic_cmpxchg_at(x, p, (ptrdiff_t)offset, e);
1079   return JNIHandles::make_local(env, res);
1080 } UNSAFE_END
1081 
1082 UNSAFE_ENTRY(jint, Unsafe_CompareAndExchangeInt(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jint e, jint x)) {
1083   oop p = JNIHandles::resolve(obj);
1084   if (p == NULL) {
1085     volatile jint* addr = (volatile jint*)index_oop_from_field_offset_long(p, offset);
1086     return RawAccess<>::atomic_cmpxchg(x, addr, e);
1087   } else {
1088     assert_field_offset_sane(p, offset);
1089     return HeapAccess<>::atomic_cmpxchg_at(x, p, (ptrdiff_t)offset, e);
1090   }
1091 } UNSAFE_END
1092 
1093 UNSAFE_ENTRY(jlong, Unsafe_CompareAndExchangeLong(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jlong e, jlong x)) {
1094   oop p = JNIHandles::resolve(obj);
1095   if (p == NULL) {
1096     volatile jlong* addr = (volatile jlong*)index_oop_from_field_offset_long(p, offset);
1097     return RawAccess<>::atomic_cmpxchg(x, addr, e);
1098   } else {
1099     assert_field_offset_sane(p, offset);
1100     return HeapAccess<>::atomic_cmpxchg_at(x, p, (ptrdiff_t)offset, e);
1101   }
1102 } UNSAFE_END
1103 
1104 UNSAFE_ENTRY(jboolean, Unsafe_CompareAndSetObject(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject e_h, jobject x_h)) {
1105   oop x = JNIHandles::resolve(x_h);
1106   oop e = JNIHandles::resolve(e_h);
1107   oop p = JNIHandles::resolve(obj);
1108   assert_field_offset_sane(p, offset);
1109   oop ret = HeapAccess<ON_UNKNOWN_OOP_REF>::oop_atomic_cmpxchg_at(x, p, (ptrdiff_t)offset, e);
1110   return oopDesc::equals(ret, e);
1111 } UNSAFE_END
1112 
1113 UNSAFE_ENTRY(jboolean, Unsafe_CompareAndSetInt(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jint e, jint x)) {
1114   oop p = JNIHandles::resolve(obj);
1115   if (p == NULL) {
1116     volatile jint* addr = (volatile jint*)index_oop_from_field_offset_long(p, offset);
1117     return RawAccess<>::atomic_cmpxchg(x, addr, e) == e;
1118   } else {
1119     assert_field_offset_sane(p, offset);
1120     return HeapAccess<>::atomic_cmpxchg_at(x, p, (ptrdiff_t)offset, e) == e;
1121   }
1122 } UNSAFE_END
1123 
1124 UNSAFE_ENTRY(jboolean, Unsafe_CompareAndSetLong(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jlong e, jlong x)) {
1125   oop p = JNIHandles::resolve(obj);
1126   if (p == NULL) {
1127     volatile jlong* addr = (volatile jlong*)index_oop_from_field_offset_long(p, offset);
1128     return RawAccess<>::atomic_cmpxchg(x, addr, e) == e;
1129   } else {
1130     assert_field_offset_sane(p, offset);
1131     return HeapAccess<>::atomic_cmpxchg_at(x, p, (ptrdiff_t)offset, e) == e;
1132   }
1133 } UNSAFE_END
1134 
1135 static void post_thread_park_event(EventThreadPark* event, const oop obj, jlong timeout) {
1136   assert(event != NULL, "invariant");
1137   assert(event->should_commit(), "invariant");
1138   event->set_parkedClass((obj != NULL) ? obj->klass() : NULL);
1139   event->set_timeout(timeout);
1140   event->set_address((obj != NULL) ? (u8)cast_from_oop<uintptr_t>(obj) : 0);
1141   event->commit();
1142 }
1143 
1144 UNSAFE_ENTRY(void, Unsafe_Park(JNIEnv *env, jobject unsafe, jboolean isAbsolute, jlong time)) {
1145   HOTSPOT_THREAD_PARK_BEGIN((uintptr_t) thread->parker(), (int) isAbsolute, time);
1146   EventThreadPark event;
1147 
1148   JavaThreadParkedState jtps(thread, time != 0);
1149   thread->parker()->park(isAbsolute != 0, time);
1150   if (event.should_commit()) {
1151     post_thread_park_event(&event, thread->current_park_blocker(), time);
1152   }
1153   HOTSPOT_THREAD_PARK_END((uintptr_t) thread->parker());
1154 } UNSAFE_END
1155 
1156 UNSAFE_ENTRY(void, Unsafe_Unpark(JNIEnv *env, jobject unsafe, jobject jthread)) {
1157   Parker* p = NULL;
1158 
1159   if (jthread != NULL) {
1160     ThreadsListHandle tlh;
1161     JavaThread* thr = NULL;
1162     oop java_thread = NULL;
1163     (void) tlh.cv_internal_thread_to_JavaThread(jthread, &thr, &java_thread);
1164     if (java_thread != NULL) {
1165       // This is a valid oop.
1166       jlong lp = java_lang_Thread::park_event(java_thread);
1167       if (lp != 0) {
1168         // This cast is OK even though the jlong might have been read
1169         // non-atomically on 32bit systems, since there, one word will
1170         // always be zero anyway and the value set is always the same
1171         p = (Parker*)addr_from_java(lp);
1172       } else {
1173         // Not cached in the java.lang.Thread oop yet (could be an
1174         // older version of library).
1175         if (thr != NULL) {
1176           // The JavaThread is alive.
1177           p = thr->parker();
1178           if (p != NULL) {
1179             // Cache the Parker in the java.lang.Thread oop for next time.
1180             java_lang_Thread::set_park_event(java_thread, addr_to_java(p));
1181           }
1182         }
1183       }
1184     }
1185   } // ThreadsListHandle is destroyed here.
1186 
1187   if (p != NULL) {
1188     HOTSPOT_THREAD_UNPARK((uintptr_t) p);
1189     p->unpark();
1190   }
1191 } UNSAFE_END
1192 
1193 UNSAFE_ENTRY(jint, Unsafe_GetLoadAverage0(JNIEnv *env, jobject unsafe, jdoubleArray loadavg, jint nelem)) {
1194   const int max_nelem = 3;
1195   double la[max_nelem];
1196   jint ret;
1197 
1198   typeArrayOop a = typeArrayOop(JNIHandles::resolve_non_null(loadavg));
1199   assert(a->is_typeArray(), "must be type array");
1200 
1201   ret = os::loadavg(la, nelem);
1202   if (ret == -1) {
1203     return -1;
1204   }
1205 
1206   // if successful, ret is the number of samples actually retrieved.
1207   assert(ret >= 0 && ret <= max_nelem, "Unexpected loadavg return value");
1208   switch(ret) {
1209     case 3: a->double_at_put(2, (jdouble)la[2]); // fall through
1210     case 2: a->double_at_put(1, (jdouble)la[1]); // fall through
1211     case 1: a->double_at_put(0, (jdouble)la[0]); break;
1212   }
1213 
1214   return ret;
1215 } UNSAFE_END
1216 
1217 
1218 /// JVM_RegisterUnsafeMethods
1219 
1220 #define ADR "J"
1221 
1222 #define LANG "Ljava/lang/"
1223 
1224 #define OBJ LANG "Object;"
1225 #define CLS LANG "Class;"
1226 #define FLD LANG "reflect/Field;"
1227 #define THR LANG "Throwable;"
1228 
1229 #define DC_Args  LANG "String;[BII" LANG "ClassLoader;" "Ljava/security/ProtectionDomain;"
1230 #define DAC_Args CLS "[B[" OBJ
1231 
1232 #define CC (char*)  /*cast a literal from (const char*)*/
1233 #define FN_PTR(f) CAST_FROM_FN_PTR(void*, &f)
1234 
1235 #define DECLARE_GETPUTOOP(Type, Desc) \
1236     {CC "get"  #Type,      CC "(" OBJ "J)" #Desc,                 FN_PTR(Unsafe_Get##Type)}, \
1237     {CC "put"  #Type,      CC "(" OBJ "J" #Desc ")V",             FN_PTR(Unsafe_Put##Type)}, \
1238     {CC "get"  #Type "Volatile",      CC "(" OBJ "J)" #Desc,      FN_PTR(Unsafe_Get##Type##Volatile)}, \
1239     {CC "put"  #Type "Volatile",      CC "(" OBJ "J" #Desc ")V",  FN_PTR(Unsafe_Put##Type##Volatile)}, \
1240     {CC "with" #Type,      CC "(" CLS OBJ "J" #Desc ")" OBJ,      FN_PTR(Unsafe_With##Type)}
1241 
1242 
1243 static JNINativeMethod jdk_internal_misc_Unsafe_methods[] = {
1244     {CC "getObject",        CC "(" OBJ "J)" OBJ "",   FN_PTR(Unsafe_GetObject)},
1245     {CC "putObject",        CC "(" OBJ "J" OBJ ")V",  FN_PTR(Unsafe_PutObject)},
1246     {CC "getObjectVolatile",CC "(" OBJ "J)" OBJ "",   FN_PTR(Unsafe_GetObjectVolatile)},
1247     {CC "putObjectVolatile",CC "(" OBJ "J" OBJ ")V",  FN_PTR(Unsafe_PutObjectVolatile)},
1248 
1249     {CC "isFlattenedArray", CC "(" CLS ")Z",                     FN_PTR(Unsafe_IsFlattenedArray)},
1250     {CC "valueHeaderSize",  CC "(" CLS ")J",                     FN_PTR(Unsafe_ValueHeaderSize)},
1251     {CC "getValue",         CC "(" OBJ "J" CLS ")" OBJ,          FN_PTR(Unsafe_GetValue)},
1252     {CC "putValue",         CC "(" OBJ "J" CLS OBJ ")V",         FN_PTR(Unsafe_PutValue)},
1253     {CC "withValue",        CC "(" CLS OBJ "JJ" CLS OBJ ")" OBJ, FN_PTR(Unsafe_WithValue)},
1254     {CC "withReference",    CC "(" CLS OBJ "J" OBJ ")" OBJ,      FN_PTR(Unsafe_WithReference)},
1255     {CC "startPrivateBuffer",    CC "(" OBJ ")" OBJ,             FN_PTR(Unsafe_StartPrivateBuffer)},
1256     {CC "finishPrivateBuffer",   CC "(" OBJ ")" OBJ,             FN_PTR(Unsafe_FinishPrivateBuffer)},
1257 
1258     {CC "getUncompressedObject", CC "(" ADR ")" OBJ,  FN_PTR(Unsafe_GetUncompressedObject)},
1259 
1260     DECLARE_GETPUTOOP(Boolean, Z),
1261     DECLARE_GETPUTOOP(Byte, B),
1262     DECLARE_GETPUTOOP(Short, S),
1263     DECLARE_GETPUTOOP(Char, C),
1264     DECLARE_GETPUTOOP(Int, I),
1265     DECLARE_GETPUTOOP(Long, J),
1266     DECLARE_GETPUTOOP(Float, F),
1267     DECLARE_GETPUTOOP(Double, D),
1268 
1269     {CC "allocateMemory0",    CC "(J)" ADR,              FN_PTR(Unsafe_AllocateMemory0)},
1270     {CC "reallocateMemory0",  CC "(" ADR "J)" ADR,       FN_PTR(Unsafe_ReallocateMemory0)},
1271     {CC "freeMemory0",        CC "(" ADR ")V",           FN_PTR(Unsafe_FreeMemory0)},
1272 
1273     {CC "objectFieldOffset0", CC "(" FLD ")J",           FN_PTR(Unsafe_ObjectFieldOffset0)},
1274     {CC "objectFieldOffset1", CC "(" CLS LANG "String;)J", FN_PTR(Unsafe_ObjectFieldOffset1)},
1275     {CC "staticFieldOffset0", CC "(" FLD ")J",           FN_PTR(Unsafe_StaticFieldOffset0)},
1276     {CC "staticFieldBase0",   CC "(" FLD ")" OBJ,        FN_PTR(Unsafe_StaticFieldBase0)},
1277     {CC "ensureClassInitialized0", CC "(" CLS ")V",      FN_PTR(Unsafe_EnsureClassInitialized0)},
1278     {CC "arrayBaseOffset0",   CC "(" CLS ")I",           FN_PTR(Unsafe_ArrayBaseOffset0)},
1279     {CC "arrayIndexScale0",   CC "(" CLS ")I",           FN_PTR(Unsafe_ArrayIndexScale0)},
1280     {CC "addressSize0",       CC "()I",                  FN_PTR(Unsafe_AddressSize0)},
1281     {CC "pageSize",           CC "()I",                  FN_PTR(Unsafe_PageSize)},
1282 
1283     {CC "defineClass0",       CC "(" DC_Args ")" CLS,    FN_PTR(Unsafe_DefineClass0)},
1284     {CC "allocateInstance",   CC "(" CLS ")" OBJ,        FN_PTR(Unsafe_AllocateInstance)},
1285     {CC "throwException",     CC "(" THR ")V",           FN_PTR(Unsafe_ThrowException)},
1286     {CC "compareAndSetObject",CC "(" OBJ "J" OBJ "" OBJ ")Z", FN_PTR(Unsafe_CompareAndSetObject)},
1287     {CC "compareAndSetInt",   CC "(" OBJ "J""I""I"")Z",  FN_PTR(Unsafe_CompareAndSetInt)},
1288     {CC "compareAndSetLong",  CC "(" OBJ "J""J""J"")Z",  FN_PTR(Unsafe_CompareAndSetLong)},
1289     {CC "compareAndExchangeObject", CC "(" OBJ "J" OBJ "" OBJ ")" OBJ, FN_PTR(Unsafe_CompareAndExchangeObject)},
1290     {CC "compareAndExchangeInt",  CC "(" OBJ "J""I""I"")I", FN_PTR(Unsafe_CompareAndExchangeInt)},
1291     {CC "compareAndExchangeLong", CC "(" OBJ "J""J""J"")J", FN_PTR(Unsafe_CompareAndExchangeLong)},
1292 
1293     {CC "park",               CC "(ZJ)V",                FN_PTR(Unsafe_Park)},
1294     {CC "unpark",             CC "(" OBJ ")V",           FN_PTR(Unsafe_Unpark)},
1295 
1296     {CC "getLoadAverage0",    CC "([DI)I",               FN_PTR(Unsafe_GetLoadAverage0)},
1297 
1298     {CC "copyMemory0",        CC "(" OBJ "J" OBJ "JJ)V", FN_PTR(Unsafe_CopyMemory0)},
1299     {CC "copySwapMemory0",    CC "(" OBJ "J" OBJ "JJJ)V", FN_PTR(Unsafe_CopySwapMemory0)},
1300     {CC "setMemory0",         CC "(" OBJ "JJB)V",        FN_PTR(Unsafe_SetMemory0)},
1301 
1302     {CC "defineAnonymousClass0", CC "(" DAC_Args ")" CLS, FN_PTR(Unsafe_DefineAnonymousClass0)},
1303 
1304     {CC "shouldBeInitialized0", CC "(" CLS ")Z",         FN_PTR(Unsafe_ShouldBeInitialized0)},
1305 
1306     {CC "loadFence",          CC "()V",                  FN_PTR(Unsafe_LoadFence)},
1307     {CC "storeFence",         CC "()V",                  FN_PTR(Unsafe_StoreFence)},
1308     {CC "fullFence",          CC "()V",                  FN_PTR(Unsafe_FullFence)},
1309 
1310     {CC "isBigEndian0",       CC "()Z",                  FN_PTR(Unsafe_isBigEndian0)},
1311     {CC "unalignedAccess0",   CC "()Z",                  FN_PTR(Unsafe_unalignedAccess0)}
1312 };
1313 
1314 #undef CC
1315 #undef FN_PTR
1316 
1317 #undef ADR
1318 #undef LANG
1319 #undef OBJ
1320 #undef CLS
1321 #undef FLD
1322 #undef THR
1323 #undef DC_Args
1324 #undef DAC_Args
1325 
1326 #undef DECLARE_GETPUTOOP
1327 
1328 
1329 // This function is exported, used by NativeLookup.
1330 // The Unsafe_xxx functions above are called only from the interpreter.
1331 // The optimizer looks at names and signatures to recognize
1332 // individual functions.
1333 
1334 JVM_ENTRY(void, JVM_RegisterJDKInternalMiscUnsafeMethods(JNIEnv *env, jclass unsafeclass)) {
1335   ThreadToNativeFromVM ttnfv(thread);
1336 
1337   int ok = env->RegisterNatives(unsafeclass, jdk_internal_misc_Unsafe_methods, sizeof(jdk_internal_misc_Unsafe_methods)/sizeof(JNINativeMethod));
1338   guarantee(ok == 0, "register jdk.internal.misc.Unsafe natives");
1339 } JVM_END