1 /*
   2  * Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "classfile/vmSymbols.hpp"
  27 #include "memory/allocation.inline.hpp"
  28 #include "prims/jni.h"
  29 #include "prims/jvm.h"
  30 #include "runtime/globals.hpp"
  31 #include "runtime/interfaceSupport.hpp"
  32 #include "runtime/reflection.hpp"
  33 #include "runtime/reflectionCompat.hpp"
  34 #include "runtime/synchronizer.hpp"
  35 #include "services/threadService.hpp"
  36 #include "utilities/copy.hpp"
  37 #include "utilities/dtrace.hpp"
  38 
  39 /*
  40  *      Implementation of class sun.misc.Unsafe
  41  */
  42 
  43 HS_DTRACE_PROBE_DECL3(hotspot, thread__park__begin, uintptr_t, int, long long);
  44 HS_DTRACE_PROBE_DECL1(hotspot, thread__park__end, uintptr_t);
  45 HS_DTRACE_PROBE_DECL1(hotspot, thread__unpark, uintptr_t);
  46 
  47 #define MAX_OBJECT_SIZE \
  48   ( arrayOopDesc::header_size(T_DOUBLE) * HeapWordSize \
  49     + ((julong)max_jint * sizeof(double)) )
  50 
  51 
  52 #define UNSAFE_ENTRY(result_type, header) \
  53   JVM_ENTRY(result_type, header)
  54 
  55 // Can't use UNSAFE_LEAF because it has the signature of a straight
  56 // call into the runtime (just like JVM_LEAF, funny that) but it's
  57 // called like a Java Native and thus the wrapper built for it passes
  58 // arguments like a JNI call.  It expects those arguments to be popped
  59 // from the stack on Intel like all good JNI args are, and adjusts the
  60 // stack according.  Since the JVM_LEAF call expects no extra
  61 // arguments the stack isn't popped in the C code, is pushed by the
  62 // wrapper and we get sick.
  63 //#define UNSAFE_LEAF(result_type, header) \
  64 //  JVM_LEAF(result_type, header)
  65 
  66 #define UNSAFE_END JVM_END
  67 
  68 #define UnsafeWrapper(arg) /*nothing, for the present*/
  69 
  70 
  71 inline void* addr_from_java(jlong addr) {
  72   // This assert fails in a variety of ways on 32-bit systems.
  73   // It is impossible to predict whether native code that converts
  74   // pointers to longs will sign-extend or zero-extend the addresses.
  75   //assert(addr == (uintptr_t)addr, "must not be odd high bits");
  76   return (void*)(uintptr_t)addr;
  77 }
  78 
  79 inline jlong addr_to_java(void* p) {
  80   assert(p == (void*)(uintptr_t)p, "must not be odd high bits");
  81   return (uintptr_t)p;
  82 }
  83 
  84 
  85 // Note: The VM's obj_field and related accessors use byte-scaled
  86 // ("unscaled") offsets, just as the unsafe methods do.
  87 
  88 // However, the method Unsafe.fieldOffset explicitly declines to
  89 // guarantee this.  The field offset values manipulated by the Java user
  90 // through the Unsafe API are opaque cookies that just happen to be byte
  91 // offsets.  We represent this state of affairs by passing the cookies
  92 // through conversion functions when going between the VM and the Unsafe API.
  93 // The conversion functions just happen to be no-ops at present.
  94 
  95 inline jlong field_offset_to_byte_offset(jlong field_offset) {
  96   return field_offset;
  97 }
  98 
  99 inline jlong field_offset_from_byte_offset(jlong byte_offset) {
 100   return byte_offset;
 101 }
 102 
 103 inline jint invocation_key_from_method_slot(jint slot) {
 104   return slot;
 105 }
 106 
 107 inline jint invocation_key_to_method_slot(jint key) {
 108   return key;
 109 }
 110 
 111 inline void* index_oop_from_field_offset_long(oop p, jlong field_offset) {
 112   jlong byte_offset = field_offset_to_byte_offset(field_offset);
 113 #ifdef ASSERT
 114   if (p != NULL) {
 115     assert(byte_offset >= 0 && byte_offset <= (jlong)MAX_OBJECT_SIZE, "sane offset");
 116     if (byte_offset == (jint)byte_offset) {
 117       void* ptr_plus_disp = (address)p + byte_offset;
 118       assert((void*)p->obj_field_addr<oop>((jint)byte_offset) == ptr_plus_disp,
 119              "raw [ptr+disp] must be consistent with oop::field_base");
 120     }
 121   }
 122 #endif
 123   if (sizeof(char*) == sizeof(jint))    // (this constant folds!)
 124     return (address)p + (jint) byte_offset;
 125   else
 126     return (address)p +        byte_offset;
 127 }
 128 
 129 // Externally callable versions:
 130 // (Use these in compiler intrinsics which emulate unsafe primitives.)
 131 jlong Unsafe_field_offset_to_byte_offset(jlong field_offset) {
 132   return field_offset;
 133 }
 134 jlong Unsafe_field_offset_from_byte_offset(jlong byte_offset) {
 135   return byte_offset;
 136 }
 137 jint Unsafe_invocation_key_from_method_slot(jint slot) {
 138   return invocation_key_from_method_slot(slot);
 139 }
 140 jint Unsafe_invocation_key_to_method_slot(jint key) {
 141   return invocation_key_to_method_slot(key);
 142 }
 143 
 144 
 145 ///// Data in the Java heap.
 146 
 147 #define GET_FIELD(obj, offset, type_name, v) \
 148   oop p = JNIHandles::resolve(obj); \
 149   type_name v = *(type_name*)index_oop_from_field_offset_long(p, offset)
 150 
 151 #define SET_FIELD(obj, offset, type_name, x) \
 152   oop p = JNIHandles::resolve(obj); \
 153   *(type_name*)index_oop_from_field_offset_long(p, offset) = x
 154 
 155 #define GET_FIELD_VOLATILE(obj, offset, type_name, v) \
 156   oop p = JNIHandles::resolve(obj); \
 157   volatile type_name v = *(volatile type_name*)index_oop_from_field_offset_long(p, offset)
 158 
 159 #define SET_FIELD_VOLATILE(obj, offset, type_name, x) \
 160   oop p = JNIHandles::resolve(obj); \
 161   *(volatile type_name*)index_oop_from_field_offset_long(p, offset) = x; \
 162   OrderAccess::fence();
 163 
 164 // Macros for oops that check UseCompressedOops
 165 
 166 #define GET_OOP_FIELD(obj, offset, v) \
 167   oop p = JNIHandles::resolve(obj);   \
 168   oop v;                              \
 169   if (UseCompressedOops) {            \
 170     narrowOop n = *(narrowOop*)index_oop_from_field_offset_long(p, offset); \
 171     v = oopDesc::decode_heap_oop(n);                                \
 172   } else {                            \
 173     v = *(oop*)index_oop_from_field_offset_long(p, offset);                 \
 174   }
 175 
 176 #define GET_OOP_FIELD_VOLATILE(obj, offset, v) \
 177   oop p = JNIHandles::resolve(obj);   \
 178   volatile oop v;                     \
 179   if (UseCompressedOops) {            \
 180     volatile narrowOop n = *(volatile narrowOop*)index_oop_from_field_offset_long(p, offset); \
 181     v = oopDesc::decode_heap_oop(n);                               \
 182   } else {                            \
 183     v = *(volatile oop*)index_oop_from_field_offset_long(p, offset);       \
 184   }
 185 
 186 
 187 // Get/SetObject must be special-cased, since it works with handles.
 188 
 189 // The xxx140 variants for backward compatibility do not allow a full-width offset.
 190 UNSAFE_ENTRY(jobject, Unsafe_GetObject140(JNIEnv *env, jobject unsafe, jobject obj, jint offset))
 191   UnsafeWrapper("Unsafe_GetObject");
 192   if (obj == NULL)  THROW_0(vmSymbols::java_lang_NullPointerException());
 193   GET_OOP_FIELD(obj, offset, v)
 194   return JNIHandles::make_local(env, v);
 195 UNSAFE_END
 196 
 197 UNSAFE_ENTRY(void, Unsafe_SetObject140(JNIEnv *env, jobject unsafe, jobject obj, jint offset, jobject x_h))
 198   UnsafeWrapper("Unsafe_SetObject");
 199   if (obj == NULL)  THROW(vmSymbols::java_lang_NullPointerException());
 200   oop x = JNIHandles::resolve(x_h);
 201   //SET_FIELD(obj, offset, oop, x);
 202   oop p = JNIHandles::resolve(obj);
 203   if (UseCompressedOops) {
 204     if (x != NULL) {
 205       // If there is a heap base pointer, we are obliged to emit a store barrier.
 206       oop_store((narrowOop*)index_oop_from_field_offset_long(p, offset), x);
 207     } else {
 208       narrowOop n = oopDesc::encode_heap_oop_not_null(x);
 209       *(narrowOop*)index_oop_from_field_offset_long(p, offset) = n;
 210     }
 211   } else {
 212     if (x != NULL) {
 213       // If there is a heap base pointer, we are obliged to emit a store barrier.
 214       oop_store((oop*)index_oop_from_field_offset_long(p, offset), x);
 215     } else {
 216       *(oop*)index_oop_from_field_offset_long(p, offset) = x;
 217     }
 218   }
 219 UNSAFE_END
 220 
 221 // The normal variants allow a null base pointer with an arbitrary address.
 222 // But if the base pointer is non-null, the offset should make some sense.
 223 // That is, it should be in the range [0, MAX_OBJECT_SIZE].
 224 UNSAFE_ENTRY(jobject, Unsafe_GetObject(JNIEnv *env, jobject unsafe, jobject obj, jlong offset))
 225   UnsafeWrapper("Unsafe_GetObject");
 226   GET_OOP_FIELD(obj, offset, v)
 227   return JNIHandles::make_local(env, v);
 228 UNSAFE_END
 229 
 230 UNSAFE_ENTRY(void, Unsafe_SetObject(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject x_h))
 231   UnsafeWrapper("Unsafe_SetObject");
 232   oop x = JNIHandles::resolve(x_h);
 233   oop p = JNIHandles::resolve(obj);
 234   if (UseCompressedOops) {
 235     oop_store((narrowOop*)index_oop_from_field_offset_long(p, offset), x);
 236   } else {
 237     oop_store((oop*)index_oop_from_field_offset_long(p, offset), x);
 238   }
 239 UNSAFE_END
 240 
 241 UNSAFE_ENTRY(jobject, Unsafe_GetObjectVolatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset))
 242   UnsafeWrapper("Unsafe_GetObjectVolatile");
 243   GET_OOP_FIELD_VOLATILE(obj, offset, v)
 244   return JNIHandles::make_local(env, v);
 245 UNSAFE_END
 246 
 247 UNSAFE_ENTRY(void, Unsafe_SetObjectVolatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject x_h))
 248   UnsafeWrapper("Unsafe_SetObjectVolatile");
 249   oop x = JNIHandles::resolve(x_h);
 250   oop p = JNIHandles::resolve(obj);
 251   if (UseCompressedOops) {
 252     oop_store((narrowOop*)index_oop_from_field_offset_long(p, offset), x);
 253   } else {
 254     oop_store((oop*)index_oop_from_field_offset_long(p, offset), x);
 255   }
 256   OrderAccess::fence();
 257 UNSAFE_END
 258 
 259 // Volatile long versions must use locks if !VM_Version::supports_cx8().
 260 // support_cx8 is a surrogate for 'supports atomic long memory ops'.
 261 
 262 UNSAFE_ENTRY(jlong, Unsafe_GetLongVolatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset))
 263   UnsafeWrapper("Unsafe_GetLongVolatile");
 264   {
 265     if (VM_Version::supports_cx8()) {
 266       GET_FIELD_VOLATILE(obj, offset, jlong, v);
 267       return v;
 268     }
 269     else {
 270       Handle p (THREAD, JNIHandles::resolve(obj));
 271       jlong* addr = (jlong*)(index_oop_from_field_offset_long(p(), offset));
 272       ObjectLocker ol(p, THREAD);
 273       jlong value = *addr;
 274       return value;
 275     }
 276   }
 277 UNSAFE_END
 278 
 279 UNSAFE_ENTRY(void, Unsafe_SetLongVolatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jlong x))
 280   UnsafeWrapper("Unsafe_SetLongVolatile");
 281   {
 282     if (VM_Version::supports_cx8()) {
 283       SET_FIELD_VOLATILE(obj, offset, jlong, x);
 284     }
 285     else {
 286       Handle p (THREAD, JNIHandles::resolve(obj));
 287       jlong* addr = (jlong*)(index_oop_from_field_offset_long(p(), offset));
 288       ObjectLocker ol(p, THREAD);
 289       *addr = x;
 290     }
 291   }
 292 UNSAFE_END
 293 
 294 
 295 #define DEFINE_GETSETOOP(jboolean, Boolean) \
 296  \
 297 UNSAFE_ENTRY(jboolean, Unsafe_Get##Boolean##140(JNIEnv *env, jobject unsafe, jobject obj, jint offset)) \
 298   UnsafeWrapper("Unsafe_Get"#Boolean); \
 299   if (obj == NULL)  THROW_0(vmSymbols::java_lang_NullPointerException()); \
 300   GET_FIELD(obj, offset, jboolean, v); \
 301   return v; \
 302 UNSAFE_END \
 303  \
 304 UNSAFE_ENTRY(void, Unsafe_Set##Boolean##140(JNIEnv *env, jobject unsafe, jobject obj, jint offset, jboolean x)) \
 305   UnsafeWrapper("Unsafe_Set"#Boolean); \
 306   if (obj == NULL)  THROW(vmSymbols::java_lang_NullPointerException()); \
 307   SET_FIELD(obj, offset, jboolean, x); \
 308 UNSAFE_END \
 309  \
 310 UNSAFE_ENTRY(jboolean, Unsafe_Get##Boolean(JNIEnv *env, jobject unsafe, jobject obj, jlong offset)) \
 311   UnsafeWrapper("Unsafe_Get"#Boolean); \
 312   GET_FIELD(obj, offset, jboolean, v); \
 313   return v; \
 314 UNSAFE_END \
 315  \
 316 UNSAFE_ENTRY(void, Unsafe_Set##Boolean(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jboolean x)) \
 317   UnsafeWrapper("Unsafe_Set"#Boolean); \
 318   SET_FIELD(obj, offset, jboolean, x); \
 319 UNSAFE_END \
 320  \
 321 // END DEFINE_GETSETOOP.
 322 
 323 
 324 #define DEFINE_GETSETOOP_VOLATILE(jboolean, Boolean) \
 325  \
 326 UNSAFE_ENTRY(jboolean, Unsafe_Get##Boolean##Volatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset)) \
 327   UnsafeWrapper("Unsafe_Get"#Boolean); \
 328   GET_FIELD_VOLATILE(obj, offset, jboolean, v); \
 329   return v; \
 330 UNSAFE_END \
 331  \
 332 UNSAFE_ENTRY(void, Unsafe_Set##Boolean##Volatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jboolean x)) \
 333   UnsafeWrapper("Unsafe_Set"#Boolean); \
 334   SET_FIELD_VOLATILE(obj, offset, jboolean, x); \
 335 UNSAFE_END \
 336  \
 337 // END DEFINE_GETSETOOP_VOLATILE.
 338 
 339 DEFINE_GETSETOOP(jboolean, Boolean)
 340 DEFINE_GETSETOOP(jbyte, Byte)
 341 DEFINE_GETSETOOP(jshort, Short);
 342 DEFINE_GETSETOOP(jchar, Char);
 343 DEFINE_GETSETOOP(jint, Int);
 344 DEFINE_GETSETOOP(jlong, Long);
 345 DEFINE_GETSETOOP(jfloat, Float);
 346 DEFINE_GETSETOOP(jdouble, Double);
 347 
 348 DEFINE_GETSETOOP_VOLATILE(jboolean, Boolean)
 349 DEFINE_GETSETOOP_VOLATILE(jbyte, Byte)
 350 DEFINE_GETSETOOP_VOLATILE(jshort, Short);
 351 DEFINE_GETSETOOP_VOLATILE(jchar, Char);
 352 DEFINE_GETSETOOP_VOLATILE(jint, Int);
 353 // no long -- handled specially
 354 DEFINE_GETSETOOP_VOLATILE(jfloat, Float);
 355 DEFINE_GETSETOOP_VOLATILE(jdouble, Double);
 356 
 357 #undef DEFINE_GETSETOOP
 358 
 359 // The non-intrinsified versions of setOrdered just use setVolatile
 360 
 361 UNSAFE_ENTRY(void, Unsafe_SetOrderedInt(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jint x)) \
 362   UnsafeWrapper("Unsafe_SetOrderedInt"); \
 363   SET_FIELD_VOLATILE(obj, offset, jint, x); \
 364 UNSAFE_END
 365 
 366 UNSAFE_ENTRY(void, Unsafe_SetOrderedObject(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject x_h))
 367   UnsafeWrapper("Unsafe_SetOrderedObject");
 368   oop x = JNIHandles::resolve(x_h);
 369   oop p = JNIHandles::resolve(obj);
 370   if (UseCompressedOops) {
 371     oop_store((narrowOop*)index_oop_from_field_offset_long(p, offset), x);
 372   } else {
 373     oop_store((oop*)index_oop_from_field_offset_long(p, offset), x);
 374   }
 375   OrderAccess::fence();
 376 UNSAFE_END
 377 
 378 UNSAFE_ENTRY(void, Unsafe_SetOrderedLong(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jlong x))
 379   UnsafeWrapper("Unsafe_SetOrderedLong");
 380   {
 381     if (VM_Version::supports_cx8()) {
 382       SET_FIELD_VOLATILE(obj, offset, jlong, x);
 383     }
 384     else {
 385       Handle p (THREAD, JNIHandles::resolve(obj));
 386       jlong* addr = (jlong*)(index_oop_from_field_offset_long(p(), offset));
 387       ObjectLocker ol(p, THREAD);
 388       *addr = x;
 389     }
 390   }
 391 UNSAFE_END
 392 
 393 ////// Data in the C heap.
 394 
 395 // Note:  These do not throw NullPointerException for bad pointers.
 396 // They just crash.  Only a oop base pointer can generate a NullPointerException.
 397 //
 398 #define DEFINE_GETSETNATIVE(java_type, Type, native_type) \
 399  \
 400 UNSAFE_ENTRY(java_type, Unsafe_GetNative##Type(JNIEnv *env, jobject unsafe, jlong addr)) \
 401   UnsafeWrapper("Unsafe_GetNative"#Type); \
 402   void* p = addr_from_java(addr); \
 403   JavaThread* t = JavaThread::current(); \
 404   t->set_doing_unsafe_access(true); \
 405   java_type x = *(volatile native_type*)p; \
 406   t->set_doing_unsafe_access(false); \
 407   return x; \
 408 UNSAFE_END \
 409  \
 410 UNSAFE_ENTRY(void, Unsafe_SetNative##Type(JNIEnv *env, jobject unsafe, jlong addr, java_type x)) \
 411   UnsafeWrapper("Unsafe_SetNative"#Type); \
 412   JavaThread* t = JavaThread::current(); \
 413   t->set_doing_unsafe_access(true); \
 414   void* p = addr_from_java(addr); \
 415   *(volatile native_type*)p = x; \
 416   t->set_doing_unsafe_access(false); \
 417 UNSAFE_END \
 418  \
 419 // END DEFINE_GETSETNATIVE.
 420 
 421 DEFINE_GETSETNATIVE(jbyte, Byte, signed char)
 422 DEFINE_GETSETNATIVE(jshort, Short, signed short);
 423 DEFINE_GETSETNATIVE(jchar, Char, unsigned short);
 424 DEFINE_GETSETNATIVE(jint, Int, jint);
 425 // no long -- handled specially
 426 DEFINE_GETSETNATIVE(jfloat, Float, float);
 427 DEFINE_GETSETNATIVE(jdouble, Double, double);
 428 
 429 #undef DEFINE_GETSETNATIVE
 430 
 431 UNSAFE_ENTRY(jlong, Unsafe_GetNativeLong(JNIEnv *env, jobject unsafe, jlong addr))
 432   UnsafeWrapper("Unsafe_GetNativeLong");
 433   JavaThread* t = JavaThread::current();
 434   // We do it this way to avoid problems with access to heap using 64
 435   // bit loads, as jlong in heap could be not 64-bit aligned, and on
 436   // some CPUs (SPARC) it leads to SIGBUS.
 437   t->set_doing_unsafe_access(true);
 438   void* p = addr_from_java(addr);
 439   jlong x;
 440   if (((intptr_t)p & 7) == 0) {
 441     // jlong is aligned, do a volatile access
 442     x = *(volatile jlong*)p;
 443   } else {
 444     jlong_accessor acc;
 445     acc.words[0] = ((volatile jint*)p)[0];
 446     acc.words[1] = ((volatile jint*)p)[1];
 447     x = acc.long_value;
 448   }
 449   t->set_doing_unsafe_access(false);
 450   return x;
 451 UNSAFE_END
 452 
 453 UNSAFE_ENTRY(void, Unsafe_SetNativeLong(JNIEnv *env, jobject unsafe, jlong addr, jlong x))
 454   UnsafeWrapper("Unsafe_SetNativeLong");
 455   JavaThread* t = JavaThread::current();
 456   // see comment for Unsafe_GetNativeLong
 457   t->set_doing_unsafe_access(true);
 458   void* p = addr_from_java(addr);
 459   if (((intptr_t)p & 7) == 0) {
 460     // jlong is aligned, do a volatile access
 461     *(volatile jlong*)p = x;
 462   } else {
 463     jlong_accessor acc;
 464     acc.long_value = x;
 465     ((volatile jint*)p)[0] = acc.words[0];
 466     ((volatile jint*)p)[1] = acc.words[1];
 467   }
 468   t->set_doing_unsafe_access(false);
 469 UNSAFE_END
 470 
 471 
 472 UNSAFE_ENTRY(jlong, Unsafe_GetNativeAddress(JNIEnv *env, jobject unsafe, jlong addr))
 473   UnsafeWrapper("Unsafe_GetNativeAddress");
 474   void* p = addr_from_java(addr);
 475   return addr_to_java(*(void**)p);
 476 UNSAFE_END
 477 
 478 UNSAFE_ENTRY(void, Unsafe_SetNativeAddress(JNIEnv *env, jobject unsafe, jlong addr, jlong x))
 479   UnsafeWrapper("Unsafe_SetNativeAddress");
 480   void* p = addr_from_java(addr);
 481   *(void**)p = addr_from_java(x);
 482 UNSAFE_END
 483 
 484 
 485 ////// Allocation requests
 486 
 487 UNSAFE_ENTRY(jobject, Unsafe_AllocateInstance(JNIEnv *env, jobject unsafe, jclass cls))
 488   UnsafeWrapper("Unsafe_AllocateInstance");
 489   {
 490     ThreadToNativeFromVM ttnfv(thread);
 491     return env->AllocObject(cls);
 492   }
 493 UNSAFE_END
 494 
 495 UNSAFE_ENTRY(jlong, Unsafe_AllocateMemory(JNIEnv *env, jobject unsafe, jlong size))
 496   UnsafeWrapper("Unsafe_AllocateMemory");
 497   size_t sz = (size_t)size;
 498   if (sz != (julong)size || size < 0) {
 499     THROW_0(vmSymbols::java_lang_IllegalArgumentException());
 500   }
 501   if (sz == 0) {
 502     return 0;
 503   }
 504   sz = round_to(sz, HeapWordSize);
 505   void* x = os::malloc(sz);
 506   if (x == NULL) {
 507     THROW_0(vmSymbols::java_lang_OutOfMemoryError());
 508   }
 509   //Copy::fill_to_words((HeapWord*)x, sz / HeapWordSize);
 510   return addr_to_java(x);
 511 UNSAFE_END
 512 
 513 UNSAFE_ENTRY(jlong, Unsafe_ReallocateMemory(JNIEnv *env, jobject unsafe, jlong addr, jlong size))
 514   UnsafeWrapper("Unsafe_ReallocateMemory");
 515   void* p = addr_from_java(addr);
 516   size_t sz = (size_t)size;
 517   if (sz != (julong)size || size < 0) {
 518     THROW_0(vmSymbols::java_lang_IllegalArgumentException());
 519   }
 520   if (sz == 0) {
 521     os::free(p);
 522     return 0;
 523   }
 524   sz = round_to(sz, HeapWordSize);
 525   void* x = (p == NULL) ? os::malloc(sz) : os::realloc(p, sz);
 526   if (x == NULL) {
 527     THROW_0(vmSymbols::java_lang_OutOfMemoryError());
 528   }
 529   return addr_to_java(x);
 530 UNSAFE_END
 531 
 532 UNSAFE_ENTRY(void, Unsafe_FreeMemory(JNIEnv *env, jobject unsafe, jlong addr))
 533   UnsafeWrapper("Unsafe_FreeMemory");
 534   void* p = addr_from_java(addr);
 535   if (p == NULL) {
 536     return;
 537   }
 538   os::free(p);
 539 UNSAFE_END
 540 
 541 UNSAFE_ENTRY(void, Unsafe_SetMemory(JNIEnv *env, jobject unsafe, jlong addr, jlong size, jbyte value))
 542   UnsafeWrapper("Unsafe_SetMemory");
 543   size_t sz = (size_t)size;
 544   if (sz != (julong)size || size < 0) {
 545     THROW(vmSymbols::java_lang_IllegalArgumentException());
 546   }
 547   char* p = (char*) addr_from_java(addr);
 548   Copy::fill_to_memory_atomic(p, sz, value);
 549 UNSAFE_END
 550 
 551 UNSAFE_ENTRY(void, Unsafe_SetMemory2(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jlong size, jbyte value))
 552   UnsafeWrapper("Unsafe_SetMemory");
 553   size_t sz = (size_t)size;
 554   if (sz != (julong)size || size < 0) {
 555     THROW(vmSymbols::java_lang_IllegalArgumentException());
 556   }
 557   oop base = JNIHandles::resolve(obj);
 558   void* p = index_oop_from_field_offset_long(base, offset);
 559   Copy::fill_to_memory_atomic(p, sz, value);
 560 UNSAFE_END
 561 
 562 UNSAFE_ENTRY(void, Unsafe_CopyMemory(JNIEnv *env, jobject unsafe, jlong srcAddr, jlong dstAddr, jlong size))
 563   UnsafeWrapper("Unsafe_CopyMemory");
 564   if (size == 0) {
 565     return;
 566   }
 567   size_t sz = (size_t)size;
 568   if (sz != (julong)size || size < 0) {
 569     THROW(vmSymbols::java_lang_IllegalArgumentException());
 570   }
 571   void* src = addr_from_java(srcAddr);
 572   void* dst = addr_from_java(dstAddr);
 573   Copy::conjoint_memory_atomic(src, dst, sz);
 574 UNSAFE_END
 575 
 576 UNSAFE_ENTRY(void, Unsafe_CopyMemory2(JNIEnv *env, jobject unsafe, jobject srcObj, jlong srcOffset, jobject dstObj, jlong dstOffset, jlong size))
 577   UnsafeWrapper("Unsafe_CopyMemory");
 578   if (size == 0) {
 579     return;
 580   }
 581   size_t sz = (size_t)size;
 582   if (sz != (julong)size || size < 0) {
 583     THROW(vmSymbols::java_lang_IllegalArgumentException());
 584   }
 585   oop srcp = JNIHandles::resolve(srcObj);
 586   oop dstp = JNIHandles::resolve(dstObj);
 587   if (dstp != NULL && !dstp->is_typeArray()) {
 588     // NYI:  This works only for non-oop arrays at present.
 589     // Generalizing it would be reasonable, but requires card marking.
 590     // Also, autoboxing a Long from 0L in copyMemory(x,y, 0L,z, n) would be bad.
 591     THROW(vmSymbols::java_lang_IllegalArgumentException());
 592   }
 593   void* src = index_oop_from_field_offset_long(srcp, srcOffset);
 594   void* dst = index_oop_from_field_offset_long(dstp, dstOffset);
 595   Copy::conjoint_memory_atomic(src, dst, sz);
 596 UNSAFE_END
 597 
 598 
 599 ////// Random queries
 600 
 601 // See comment at file start about UNSAFE_LEAF
 602 //UNSAFE_LEAF(jint, Unsafe_AddressSize())
 603 UNSAFE_ENTRY(jint, Unsafe_AddressSize(JNIEnv *env, jobject unsafe))
 604   UnsafeWrapper("Unsafe_AddressSize");
 605   return sizeof(void*);
 606 UNSAFE_END
 607 
 608 // See comment at file start about UNSAFE_LEAF
 609 //UNSAFE_LEAF(jint, Unsafe_PageSize())
 610 UNSAFE_ENTRY(jint, Unsafe_PageSize(JNIEnv *env, jobject unsafe))
 611   UnsafeWrapper("Unsafe_PageSize");
 612   return os::vm_page_size();
 613 UNSAFE_END
 614 
 615 jint find_field_offset(jobject field, int must_be_static, TRAPS) {
 616   if (field == NULL) {
 617     THROW_0(vmSymbols::java_lang_NullPointerException());
 618   }
 619 
 620   oop reflected   = JNIHandles::resolve_non_null(field);
 621   oop mirror      = java_lang_reflect_Field::clazz(reflected);
 622   klassOop k      = java_lang_Class::as_klassOop(mirror);
 623   int slot        = java_lang_reflect_Field::slot(reflected);
 624   int modifiers   = java_lang_reflect_Field::modifiers(reflected);
 625 
 626   if (must_be_static >= 0) {
 627     int really_is_static = ((modifiers & JVM_ACC_STATIC) != 0);
 628     if (must_be_static != really_is_static) {
 629       THROW_0(vmSymbols::java_lang_IllegalArgumentException());
 630     }
 631   }
 632 
 633   int offset = instanceKlass::cast(k)->offset_from_fields(slot);
 634   return field_offset_from_byte_offset(offset);
 635 }
 636 
 637 UNSAFE_ENTRY(jlong, Unsafe_ObjectFieldOffset(JNIEnv *env, jobject unsafe, jobject field))
 638   UnsafeWrapper("Unsafe_ObjectFieldOffset");
 639   return find_field_offset(field, 0, THREAD);
 640 UNSAFE_END
 641 
 642 UNSAFE_ENTRY(jlong, Unsafe_StaticFieldOffset(JNIEnv *env, jobject unsafe, jobject field))
 643   UnsafeWrapper("Unsafe_StaticFieldOffset");
 644   return find_field_offset(field, 1, THREAD);
 645 UNSAFE_END
 646 
 647 UNSAFE_ENTRY(jobject, Unsafe_StaticFieldBaseFromField(JNIEnv *env, jobject unsafe, jobject field))
 648   UnsafeWrapper("Unsafe_StaticFieldBase");
 649   // Note:  In this VM implementation, a field address is always a short
 650   // offset from the base of a a klass metaobject.  Thus, the full dynamic
 651   // range of the return type is never used.  However, some implementations
 652   // might put the static field inside an array shared by many classes,
 653   // or even at a fixed address, in which case the address could be quite
 654   // large.  In that last case, this function would return NULL, since
 655   // the address would operate alone, without any base pointer.
 656 
 657   if (field == NULL)  THROW_0(vmSymbols::java_lang_NullPointerException());
 658 
 659   oop reflected   = JNIHandles::resolve_non_null(field);
 660   oop mirror      = java_lang_reflect_Field::clazz(reflected);
 661   int modifiers   = java_lang_reflect_Field::modifiers(reflected);
 662 
 663   if ((modifiers & JVM_ACC_STATIC) == 0) {
 664     THROW_0(vmSymbols::java_lang_IllegalArgumentException());
 665   }
 666 
 667   return JNIHandles::make_local(env, java_lang_Class::as_klassOop(mirror));
 668 UNSAFE_END
 669 
 670 //@deprecated
 671 UNSAFE_ENTRY(jint, Unsafe_FieldOffset(JNIEnv *env, jobject unsafe, jobject field))
 672   UnsafeWrapper("Unsafe_FieldOffset");
 673   // tries (but fails) to be polymorphic between static and non-static:
 674   jlong offset = find_field_offset(field, -1, THREAD);
 675   guarantee(offset == (jint)offset, "offset fits in 32 bits");
 676   return (jint)offset;
 677 UNSAFE_END
 678 
 679 //@deprecated
 680 UNSAFE_ENTRY(jobject, Unsafe_StaticFieldBaseFromClass(JNIEnv *env, jobject unsafe, jobject clazz))
 681   UnsafeWrapper("Unsafe_StaticFieldBase");
 682   if (clazz == NULL) {
 683     THROW_0(vmSymbols::java_lang_NullPointerException());
 684   }
 685   return JNIHandles::make_local(env, java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(clazz)));
 686 UNSAFE_END
 687 
 688 UNSAFE_ENTRY(void, Unsafe_EnsureClassInitialized(JNIEnv *env, jobject unsafe, jobject clazz))
 689   UnsafeWrapper("Unsafe_EnsureClassInitialized");
 690   if (clazz == NULL) {
 691     THROW(vmSymbols::java_lang_NullPointerException());
 692   }
 693   oop mirror = JNIHandles::resolve_non_null(clazz);
 694   instanceKlass* k = instanceKlass::cast(java_lang_Class::as_klassOop(mirror));
 695   if (k != NULL) {
 696     k->initialize(CHECK);
 697   }
 698 UNSAFE_END
 699 
 700 static void getBaseAndScale(int& base, int& scale, jclass acls, TRAPS) {
 701   if (acls == NULL) {
 702     THROW(vmSymbols::java_lang_NullPointerException());
 703   }
 704   oop      mirror = JNIHandles::resolve_non_null(acls);
 705   klassOop k      = java_lang_Class::as_klassOop(mirror);
 706   if (k == NULL || !k->klass_part()->oop_is_array()) {
 707     THROW(vmSymbols::java_lang_InvalidClassException());
 708   } else if (k->klass_part()->oop_is_objArray()) {
 709     base  = arrayOopDesc::base_offset_in_bytes(T_OBJECT);
 710     scale = heapOopSize;
 711   } else if (k->klass_part()->oop_is_typeArray()) {
 712     typeArrayKlass* tak = typeArrayKlass::cast(k);
 713     base  = tak->array_header_in_bytes();
 714     assert(base == arrayOopDesc::base_offset_in_bytes(tak->element_type()), "array_header_size semantics ok");
 715     scale = (1 << tak->log2_element_size());
 716   } else {
 717     ShouldNotReachHere();
 718   }
 719 }
 720 
 721 UNSAFE_ENTRY(jint, Unsafe_ArrayBaseOffset(JNIEnv *env, jobject unsafe, jclass acls))
 722   UnsafeWrapper("Unsafe_ArrayBaseOffset");
 723   int base, scale;
 724   getBaseAndScale(base, scale, acls, CHECK_0);
 725   return field_offset_from_byte_offset(base);
 726 UNSAFE_END
 727 
 728 
 729 UNSAFE_ENTRY(jint, Unsafe_ArrayIndexScale(JNIEnv *env, jobject unsafe, jclass acls))
 730   UnsafeWrapper("Unsafe_ArrayIndexScale");
 731   int base, scale;
 732   getBaseAndScale(base, scale, acls, CHECK_0);
 733   // This VM packs both fields and array elements down to the byte.
 734   // But watch out:  If this changes, so that array references for
 735   // a given primitive type (say, T_BOOLEAN) use different memory units
 736   // than fields, this method MUST return zero for such arrays.
 737   // For example, the VM used to store sub-word sized fields in full
 738   // words in the object layout, so that accessors like getByte(Object,int)
 739   // did not really do what one might expect for arrays.  Therefore,
 740   // this function used to report a zero scale factor, so that the user
 741   // would know not to attempt to access sub-word array elements.
 742   // // Code for unpacked fields:
 743   // if (scale < wordSize)  return 0;
 744 
 745   // The following allows for a pretty general fieldOffset cookie scheme,
 746   // but requires it to be linear in byte offset.
 747   return field_offset_from_byte_offset(scale) - field_offset_from_byte_offset(0);
 748 UNSAFE_END
 749 
 750 
 751 static inline void throw_new(JNIEnv *env, const char *ename) {
 752   char buf[100];
 753   strcpy(buf, "java/lang/");
 754   strcat(buf, ename);
 755   jclass cls = env->FindClass(buf);
 756   char* msg = NULL;
 757   env->ThrowNew(cls, msg);
 758 }
 759 
 760 static jclass Unsafe_DefineClass(JNIEnv *env, jstring name, jbyteArray data, int offset, int length, jobject loader, jobject pd) {
 761   {
 762     // Code lifted from JDK 1.3 ClassLoader.c
 763 
 764     jbyte *body;
 765     char *utfName;
 766     jclass result = 0;
 767     char buf[128];
 768 
 769     if (UsePerfData) {
 770       ClassLoader::unsafe_defineClassCallCounter()->inc();
 771     }
 772 
 773     if (data == NULL) {
 774         throw_new(env, "NullPointerException");
 775         return 0;
 776     }
 777 
 778     /* Work around 4153825. malloc crashes on Solaris when passed a
 779      * negative size.
 780      */
 781     if (length < 0) {
 782         throw_new(env, "ArrayIndexOutOfBoundsException");
 783         return 0;
 784     }
 785 
 786     body = NEW_C_HEAP_ARRAY(jbyte, length);
 787 
 788     if (body == 0) {
 789         throw_new(env, "OutOfMemoryError");
 790         return 0;
 791     }
 792 
 793     env->GetByteArrayRegion(data, offset, length, body);
 794 
 795     if (env->ExceptionOccurred())
 796         goto free_body;
 797 
 798     if (name != NULL) {
 799         uint len = env->GetStringUTFLength(name);
 800         int unicode_len = env->GetStringLength(name);
 801         if (len >= sizeof(buf)) {
 802             utfName = NEW_C_HEAP_ARRAY(char, len + 1);
 803             if (utfName == NULL) {
 804                 throw_new(env, "OutOfMemoryError");
 805                 goto free_body;
 806             }
 807         } else {
 808             utfName = buf;
 809         }
 810         env->GetStringUTFRegion(name, 0, unicode_len, utfName);
 811         //VerifyFixClassname(utfName);
 812         for (uint i = 0; i < len; i++) {
 813           if (utfName[i] == '.')   utfName[i] = '/';
 814         }
 815     } else {
 816         utfName = NULL;
 817     }
 818 
 819     result = JVM_DefineClass(env, utfName, loader, body, length, pd);
 820 
 821     if (utfName && utfName != buf)
 822         FREE_C_HEAP_ARRAY(char, utfName);
 823 
 824  free_body:
 825     FREE_C_HEAP_ARRAY(jbyte, body);
 826     return result;
 827   }
 828 }
 829 
 830 
 831 UNSAFE_ENTRY(jclass, Unsafe_DefineClass0(JNIEnv *env, jobject unsafe, jstring name, jbyteArray data, int offset, int length))
 832   UnsafeWrapper("Unsafe_DefineClass");
 833   {
 834     ThreadToNativeFromVM ttnfv(thread);
 835 
 836     int depthFromDefineClass0 = 1;
 837     jclass  caller = JVM_GetCallerClass(env, depthFromDefineClass0);
 838     jobject loader = (caller == NULL) ? NULL : JVM_GetClassLoader(env, caller);
 839     jobject pd     = (caller == NULL) ? NULL : JVM_GetProtectionDomain(env, caller);
 840 
 841     return Unsafe_DefineClass(env, name, data, offset, length, loader, pd);
 842   }
 843 UNSAFE_END
 844 
 845 
 846 UNSAFE_ENTRY(jclass, Unsafe_DefineClass1(JNIEnv *env, jobject unsafe, jstring name, jbyteArray data, int offset, int length, jobject loader, jobject pd))
 847   UnsafeWrapper("Unsafe_DefineClass");
 848   {
 849     ThreadToNativeFromVM ttnfv(thread);
 850 
 851     return Unsafe_DefineClass(env, name, data, offset, length, loader, pd);
 852   }
 853 UNSAFE_END
 854 
 855 #define DAC_Args CLS"[B["OBJ
 856 // define a class but do not make it known to the class loader or system dictionary
 857 // - host_class:  supplies context for linkage, access control, protection domain, and class loader
 858 // - data:  bytes of a class file, a raw memory address (length gives the number of bytes)
 859 // - cp_patches:  where non-null entries exist, they replace corresponding CP entries in data
 860 
 861 // When you load an anonymous class U, it works as if you changed its name just before loading,
 862 // to a name that you will never use again.  Since the name is lost, no other class can directly
 863 // link to any member of U.  Just after U is loaded, the only way to use it is reflectively,
 864 // through java.lang.Class methods like Class.newInstance.
 865 
 866 // Access checks for linkage sites within U continue to follow the same rules as for named classes.
 867 // The package of an anonymous class is given by the package qualifier on the name under which it was loaded.
 868 // An anonymous class also has special privileges to access any member of its host class.
 869 // This is the main reason why this loading operation is unsafe.  The purpose of this is to
 870 // allow language implementations to simulate "open classes"; a host class in effect gets
 871 // new code when an anonymous class is loaded alongside it.  A less convenient but more
 872 // standard way to do this is with reflection, which can also be set to ignore access
 873 // restrictions.
 874 
 875 // Access into an anonymous class is possible only through reflection.  Therefore, there
 876 // are no special access rules for calling into an anonymous class.  The relaxed access
 877 // rule for the host class is applied in the opposite direction:  A host class reflectively
 878 // access one of its anonymous classes.
 879 
 880 // If you load the same bytecodes twice, you get two different classes.  You can reload
 881 // the same bytecodes with or without varying CP patches.
 882 
 883 // By using the CP patching array, you can have a new anonymous class U2 refer to an older one U1.
 884 // The bytecodes for U2 should refer to U1 by a symbolic name (doesn't matter what the name is).
 885 // The CONSTANT_Class entry for that name can be patched to refer directly to U1.
 886 
 887 // This allows, for example, U2 to use U1 as a superclass or super-interface, or as
 888 // an outer class (so that U2 is an anonymous inner class of anonymous U1).
 889 // It is not possible for a named class, or an older anonymous class, to refer by
 890 // name (via its CP) to a newer anonymous class.
 891 
 892 // CP patching may also be used to modify (i.e., hack) the names of methods, classes,
 893 // or type descriptors used in the loaded anonymous class.
 894 
 895 // Finally, CP patching may be used to introduce "live" objects into the constant pool,
 896 // instead of "dead" strings.  A compiled statement like println((Object)"hello") can
 897 // be changed to println(greeting), where greeting is an arbitrary object created before
 898 // the anonymous class is loaded.  This is useful in dynamic languages, in which
 899 // various kinds of metaobjects must be introduced as constants into bytecode.
 900 // Note the cast (Object), which tells the verifier to expect an arbitrary object,
 901 // not just a literal string.  For such ldc instructions, the verifier uses the
 902 // type Object instead of String, if the loaded constant is not in fact a String.
 903 
 904 static oop
 905 Unsafe_DefineAnonymousClass_impl(JNIEnv *env,
 906                                  jclass host_class, jbyteArray data, jobjectArray cp_patches_jh,
 907                                  HeapWord* *temp_alloc,
 908                                  TRAPS) {
 909 
 910   if (UsePerfData) {
 911     ClassLoader::unsafe_defineClassCallCounter()->inc();
 912   }
 913 
 914   if (data == NULL) {
 915     THROW_0(vmSymbols::java_lang_NullPointerException());
 916   }
 917 
 918   jint length = typeArrayOop(JNIHandles::resolve_non_null(data))->length();
 919   jint word_length = (length + sizeof(HeapWord)-1) / sizeof(HeapWord);
 920   HeapWord* body = NEW_C_HEAP_ARRAY(HeapWord, word_length);
 921   if (body == NULL) {
 922     THROW_0(vmSymbols::java_lang_OutOfMemoryError());
 923   }
 924 
 925   // caller responsible to free it:
 926   (*temp_alloc) = body;
 927 
 928   {
 929     jbyte* array_base = typeArrayOop(JNIHandles::resolve_non_null(data))->byte_at_addr(0);
 930     Copy::conjoint_words((HeapWord*) array_base, body, word_length);
 931   }
 932 
 933   u1* class_bytes = (u1*) body;
 934   int class_bytes_length = (int) length;
 935   if (class_bytes_length < 0)  class_bytes_length = 0;
 936   if (class_bytes == NULL
 937       || host_class == NULL
 938       || length != class_bytes_length)
 939     THROW_0(vmSymbols::java_lang_IllegalArgumentException());
 940 
 941   objArrayHandle cp_patches_h;
 942   if (cp_patches_jh != NULL) {
 943     oop p = JNIHandles::resolve_non_null(cp_patches_jh);
 944     if (!p->is_objArray())
 945       THROW_0(vmSymbols::java_lang_IllegalArgumentException());
 946     cp_patches_h = objArrayHandle(THREAD, (objArrayOop)p);
 947   }
 948 
 949   KlassHandle host_klass(THREAD, java_lang_Class::as_klassOop(JNIHandles::resolve_non_null(host_class)));
 950   const char* host_source = host_klass->external_name();
 951   Handle      host_loader(THREAD, host_klass->class_loader());
 952   Handle      host_domain(THREAD, host_klass->protection_domain());
 953 
 954   GrowableArray<Handle>* cp_patches = NULL;
 955   if (cp_patches_h.not_null()) {
 956     int alen = cp_patches_h->length();
 957     for (int i = alen-1; i >= 0; i--) {
 958       oop p = cp_patches_h->obj_at(i);
 959       if (p != NULL) {
 960         Handle patch(THREAD, p);
 961         if (cp_patches == NULL)
 962           cp_patches = new GrowableArray<Handle>(i+1, i+1, Handle());
 963         cp_patches->at_put(i, patch);
 964       }
 965     }
 966   }
 967 
 968   ClassFileStream st(class_bytes, class_bytes_length, (char*) host_source);
 969 
 970   instanceKlassHandle anon_klass;
 971   {
 972     symbolHandle no_class_name;
 973     klassOop anonk = SystemDictionary::parse_stream(no_class_name,
 974                                                     host_loader, host_domain,
 975                                                     &st, host_klass, cp_patches,
 976                                                     CHECK_NULL);
 977     if (anonk == NULL)  return NULL;
 978     anon_klass = instanceKlassHandle(THREAD, anonk);
 979   }
 980 
 981   // let caller initialize it as needed...
 982 
 983   return anon_klass->java_mirror();
 984 }
 985 
 986 UNSAFE_ENTRY(jclass, Unsafe_DefineAnonymousClass(JNIEnv *env, jobject unsafe, jclass host_class, jbyteArray data, jobjectArray cp_patches_jh))
 987 {
 988   UnsafeWrapper("Unsafe_DefineAnonymousClass");
 989   ResourceMark rm(THREAD);
 990 
 991   HeapWord* temp_alloc = NULL;
 992 
 993   jobject res_jh = NULL;
 994 
 995   { oop res_oop = Unsafe_DefineAnonymousClass_impl(env,
 996                                                    host_class, data, cp_patches_jh,
 997                                                    &temp_alloc, THREAD);
 998     if (res_oop != NULL)
 999       res_jh = JNIHandles::make_local(env, res_oop);
1000   }
1001 
1002   // try/finally clause:
1003   if (temp_alloc != NULL) {
1004     FREE_C_HEAP_ARRAY(HeapWord, temp_alloc);
1005   }
1006 
1007   return (jclass) res_jh;
1008 }
1009 UNSAFE_END
1010 
1011 
1012 
1013 UNSAFE_ENTRY(void, Unsafe_MonitorEnter(JNIEnv *env, jobject unsafe, jobject jobj))
1014   UnsafeWrapper("Unsafe_MonitorEnter");
1015   {
1016     if (jobj == NULL) {
1017       THROW(vmSymbols::java_lang_NullPointerException());
1018     }
1019     Handle obj(thread, JNIHandles::resolve_non_null(jobj));
1020     ObjectSynchronizer::jni_enter(obj, CHECK);
1021   }
1022 UNSAFE_END
1023 
1024 
1025 UNSAFE_ENTRY(jboolean, Unsafe_TryMonitorEnter(JNIEnv *env, jobject unsafe, jobject jobj))
1026   UnsafeWrapper("Unsafe_TryMonitorEnter");
1027   {
1028     if (jobj == NULL) {
1029       THROW_(vmSymbols::java_lang_NullPointerException(), JNI_FALSE);
1030     }
1031     Handle obj(thread, JNIHandles::resolve_non_null(jobj));
1032     bool res = ObjectSynchronizer::jni_try_enter(obj, CHECK_0);
1033     return (res ? JNI_TRUE : JNI_FALSE);
1034   }
1035 UNSAFE_END
1036 
1037 
1038 UNSAFE_ENTRY(void, Unsafe_MonitorExit(JNIEnv *env, jobject unsafe, jobject jobj))
1039   UnsafeWrapper("Unsafe_MonitorExit");
1040   {
1041     if (jobj == NULL) {
1042       THROW(vmSymbols::java_lang_NullPointerException());
1043     }
1044     Handle obj(THREAD, JNIHandles::resolve_non_null(jobj));
1045     ObjectSynchronizer::jni_exit(obj(), CHECK);
1046   }
1047 UNSAFE_END
1048 
1049 
1050 UNSAFE_ENTRY(void, Unsafe_ThrowException(JNIEnv *env, jobject unsafe, jthrowable thr))
1051   UnsafeWrapper("Unsafe_ThrowException");
1052   {
1053     ThreadToNativeFromVM ttnfv(thread);
1054     env->Throw(thr);
1055   }
1056 UNSAFE_END
1057 
1058 // JSR166 ------------------------------------------------------------------
1059 
1060 UNSAFE_ENTRY(jboolean, Unsafe_CompareAndSwapObject(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject e_h, jobject x_h))
1061   UnsafeWrapper("Unsafe_CompareAndSwapObject");
1062   oop x = JNIHandles::resolve(x_h);
1063   oop e = JNIHandles::resolve(e_h);
1064   oop p = JNIHandles::resolve(obj);
1065   HeapWord* addr = (HeapWord *)index_oop_from_field_offset_long(p, offset);
1066   if (UseCompressedOops) {
1067     update_barrier_set_pre((narrowOop*)addr, e);
1068   } else {
1069     update_barrier_set_pre((oop*)addr, e);
1070   }
1071   oop res = oopDesc::atomic_compare_exchange_oop(x, addr, e);
1072   jboolean success  = (res == e);
1073   if (success)
1074     update_barrier_set((void*)addr, x);
1075   return success;
1076 UNSAFE_END
1077 
1078 UNSAFE_ENTRY(jboolean, Unsafe_CompareAndSwapInt(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jint e, jint x))
1079   UnsafeWrapper("Unsafe_CompareAndSwapInt");
1080   oop p = JNIHandles::resolve(obj);
1081   jint* addr = (jint *) index_oop_from_field_offset_long(p, offset);
1082   return (jint)(Atomic::cmpxchg(x, addr, e)) == e;
1083 UNSAFE_END
1084 
1085 UNSAFE_ENTRY(jboolean, Unsafe_CompareAndSwapLong(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jlong e, jlong x))
1086   UnsafeWrapper("Unsafe_CompareAndSwapLong");
1087   Handle p (THREAD, JNIHandles::resolve(obj));
1088   jlong* addr = (jlong*)(index_oop_from_field_offset_long(p(), offset));
1089   if (VM_Version::supports_cx8())
1090     return (jlong)(Atomic::cmpxchg(x, addr, e)) == e;
1091   else {
1092     jboolean success = false;
1093     ObjectLocker ol(p, THREAD);
1094     if (*addr == e) { *addr = x; success = true; }
1095     return success;
1096   }
1097 UNSAFE_END
1098 
1099 UNSAFE_ENTRY(void, Unsafe_Park(JNIEnv *env, jobject unsafe, jboolean isAbsolute, jlong time))
1100   UnsafeWrapper("Unsafe_Park");
1101   HS_DTRACE_PROBE3(hotspot, thread__park__begin, thread->parker(), (int) isAbsolute, time);
1102   JavaThreadParkedState jtps(thread, time != 0);
1103   thread->parker()->park(isAbsolute != 0, time);
1104   HS_DTRACE_PROBE1(hotspot, thread__park__end, thread->parker());
1105 UNSAFE_END
1106 
1107 UNSAFE_ENTRY(void, Unsafe_Unpark(JNIEnv *env, jobject unsafe, jobject jthread))
1108   UnsafeWrapper("Unsafe_Unpark");
1109   Parker* p = NULL;
1110   if (jthread != NULL) {
1111     oop java_thread = JNIHandles::resolve_non_null(jthread);
1112     if (java_thread != NULL) {
1113       jlong lp = java_lang_Thread::park_event(java_thread);
1114       if (lp != 0) {
1115         // This cast is OK even though the jlong might have been read
1116         // non-atomically on 32bit systems, since there, one word will
1117         // always be zero anyway and the value set is always the same
1118         p = (Parker*)addr_from_java(lp);
1119       } else {
1120         // Grab lock if apparently null or using older version of library
1121         MutexLocker mu(Threads_lock);
1122         java_thread = JNIHandles::resolve_non_null(jthread);
1123         if (java_thread != NULL) {
1124           JavaThread* thr = java_lang_Thread::thread(java_thread);
1125           if (thr != NULL) {
1126             p = thr->parker();
1127             if (p != NULL) { // Bind to Java thread for next time.
1128               java_lang_Thread::set_park_event(java_thread, addr_to_java(p));
1129             }
1130           }
1131         }
1132       }
1133     }
1134   }
1135   if (p != NULL) {
1136     HS_DTRACE_PROBE1(hotspot, thread__unpark, p);
1137     p->unpark();
1138   }
1139 UNSAFE_END
1140 
1141 UNSAFE_ENTRY(jint, Unsafe_Loadavg(JNIEnv *env, jobject unsafe, jdoubleArray loadavg, jint nelem))
1142   UnsafeWrapper("Unsafe_Loadavg");
1143   const int max_nelem = 3;
1144   double la[max_nelem];
1145   jint ret;
1146 
1147   typeArrayOop a = typeArrayOop(JNIHandles::resolve_non_null(loadavg));
1148   assert(a->is_typeArray(), "must be type array");
1149 
1150   if (nelem < 0 || nelem > max_nelem || a->length() < nelem) {
1151     ThreadToNativeFromVM ttnfv(thread);
1152     throw_new(env, "ArrayIndexOutOfBoundsException");
1153     return -1;
1154   }
1155 
1156   ret = os::loadavg(la, nelem);
1157   if (ret == -1) return -1;
1158 
1159   // if successful, ret is the number of samples actually retrieved.
1160   assert(ret >= 0 && ret <= max_nelem, "Unexpected loadavg return value");
1161   switch(ret) {
1162     case 3: a->double_at_put(2, (jdouble)la[2]); // fall through
1163     case 2: a->double_at_put(1, (jdouble)la[1]); // fall through
1164     case 1: a->double_at_put(0, (jdouble)la[0]); break;
1165   }
1166   return ret;
1167 UNSAFE_END
1168 
1169 UNSAFE_ENTRY(void, Unsafe_PrefetchRead(JNIEnv* env, jclass ignored, jobject obj, jlong offset))
1170   UnsafeWrapper("Unsafe_PrefetchRead");
1171   oop p = JNIHandles::resolve(obj);
1172   void* addr = index_oop_from_field_offset_long(p, 0);
1173   Prefetch::read(addr, (intx)offset);
1174 UNSAFE_END
1175 
1176 UNSAFE_ENTRY(void, Unsafe_PrefetchWrite(JNIEnv* env, jclass ignored, jobject obj, jlong offset))
1177   UnsafeWrapper("Unsafe_PrefetchWrite");
1178   oop p = JNIHandles::resolve(obj);
1179   void* addr = index_oop_from_field_offset_long(p, 0);
1180   Prefetch::write(addr, (intx)offset);
1181 UNSAFE_END
1182 
1183 
1184 /// JVM_RegisterUnsafeMethods
1185 
1186 #define ADR "J"
1187 
1188 #define LANG "Ljava/lang/"
1189 
1190 #define OBJ LANG"Object;"
1191 #define CLS LANG"Class;"
1192 #define CTR LANG"reflect/Constructor;"
1193 #define FLD LANG"reflect/Field;"
1194 #define MTH LANG"reflect/Method;"
1195 #define THR LANG"Throwable;"
1196 
1197 #define DC0_Args LANG"String;[BII"
1198 #define DC1_Args DC0_Args LANG"ClassLoader;" "Ljava/security/ProtectionDomain;"
1199 
1200 #define CC (char*)  /*cast a literal from (const char*)*/
1201 #define FN_PTR(f) CAST_FROM_FN_PTR(void*, &f)
1202 
1203 // define deprecated accessors for compabitility with 1.4.0
1204 #define DECLARE_GETSETOOP_140(Boolean, Z) \
1205     {CC"get"#Boolean,      CC"("OBJ"I)"#Z,      FN_PTR(Unsafe_Get##Boolean##140)}, \
1206     {CC"put"#Boolean,      CC"("OBJ"I"#Z")V",   FN_PTR(Unsafe_Set##Boolean##140)}
1207 
1208 // Note:  In 1.4.1, getObject and kin take both int and long offsets.
1209 #define DECLARE_GETSETOOP_141(Boolean, Z) \
1210     {CC"get"#Boolean,      CC"("OBJ"J)"#Z,      FN_PTR(Unsafe_Get##Boolean)}, \
1211     {CC"put"#Boolean,      CC"("OBJ"J"#Z")V",   FN_PTR(Unsafe_Set##Boolean)}
1212 
1213 // Note:  In 1.5.0, there are volatile versions too
1214 #define DECLARE_GETSETOOP(Boolean, Z) \
1215     {CC"get"#Boolean,      CC"("OBJ"J)"#Z,      FN_PTR(Unsafe_Get##Boolean)}, \
1216     {CC"put"#Boolean,      CC"("OBJ"J"#Z")V",   FN_PTR(Unsafe_Set##Boolean)}, \
1217     {CC"get"#Boolean"Volatile",      CC"("OBJ"J)"#Z,      FN_PTR(Unsafe_Get##Boolean##Volatile)}, \
1218     {CC"put"#Boolean"Volatile",      CC"("OBJ"J"#Z")V",   FN_PTR(Unsafe_Set##Boolean##Volatile)}
1219 
1220 
1221 #define DECLARE_GETSETNATIVE(Byte, B) \
1222     {CC"get"#Byte,         CC"("ADR")"#B,       FN_PTR(Unsafe_GetNative##Byte)}, \
1223     {CC"put"#Byte,         CC"("ADR#B")V",      FN_PTR(Unsafe_SetNative##Byte)}
1224 
1225 
1226 
1227 // %%% These are temporarily supported until the SDK sources
1228 // contain the necessarily updated Unsafe.java.
1229 static JNINativeMethod methods_140[] = {
1230 
1231     {CC"getObject",        CC"("OBJ"I)"OBJ"",   FN_PTR(Unsafe_GetObject140)},
1232     {CC"putObject",        CC"("OBJ"I"OBJ")V",  FN_PTR(Unsafe_SetObject140)},
1233 
1234     DECLARE_GETSETOOP_140(Boolean, Z),
1235     DECLARE_GETSETOOP_140(Byte, B),
1236     DECLARE_GETSETOOP_140(Short, S),
1237     DECLARE_GETSETOOP_140(Char, C),
1238     DECLARE_GETSETOOP_140(Int, I),
1239     DECLARE_GETSETOOP_140(Long, J),
1240     DECLARE_GETSETOOP_140(Float, F),
1241     DECLARE_GETSETOOP_140(Double, D),
1242 
1243     DECLARE_GETSETNATIVE(Byte, B),
1244     DECLARE_GETSETNATIVE(Short, S),
1245     DECLARE_GETSETNATIVE(Char, C),
1246     DECLARE_GETSETNATIVE(Int, I),
1247     DECLARE_GETSETNATIVE(Long, J),
1248     DECLARE_GETSETNATIVE(Float, F),
1249     DECLARE_GETSETNATIVE(Double, D),
1250 
1251     {CC"getAddress",         CC"("ADR")"ADR,             FN_PTR(Unsafe_GetNativeAddress)},
1252     {CC"putAddress",         CC"("ADR""ADR")V",          FN_PTR(Unsafe_SetNativeAddress)},
1253 
1254     {CC"allocateMemory",     CC"(J)"ADR,                 FN_PTR(Unsafe_AllocateMemory)},
1255     {CC"reallocateMemory",   CC"("ADR"J)"ADR,            FN_PTR(Unsafe_ReallocateMemory)},
1256 //  {CC"setMemory",          CC"("ADR"JB)V",             FN_PTR(Unsafe_SetMemory)},
1257 //  {CC"copyMemory",         CC"("ADR ADR"J)V",          FN_PTR(Unsafe_CopyMemory)},
1258     {CC"freeMemory",         CC"("ADR")V",               FN_PTR(Unsafe_FreeMemory)},
1259 
1260     {CC"fieldOffset",        CC"("FLD")I",               FN_PTR(Unsafe_FieldOffset)}, //deprecated
1261     {CC"staticFieldBase",    CC"("CLS")"OBJ,             FN_PTR(Unsafe_StaticFieldBaseFromClass)}, //deprecated
1262     {CC"ensureClassInitialized",CC"("CLS")V",            FN_PTR(Unsafe_EnsureClassInitialized)},
1263     {CC"arrayBaseOffset",    CC"("CLS")I",               FN_PTR(Unsafe_ArrayBaseOffset)},
1264     {CC"arrayIndexScale",    CC"("CLS")I",               FN_PTR(Unsafe_ArrayIndexScale)},
1265     {CC"addressSize",        CC"()I",                    FN_PTR(Unsafe_AddressSize)},
1266     {CC"pageSize",           CC"()I",                    FN_PTR(Unsafe_PageSize)},
1267 
1268     {CC"defineClass",        CC"("DC0_Args")"CLS,        FN_PTR(Unsafe_DefineClass0)},
1269     {CC"defineClass",        CC"("DC1_Args")"CLS,        FN_PTR(Unsafe_DefineClass1)},
1270     {CC"allocateInstance",   CC"("CLS")"OBJ,             FN_PTR(Unsafe_AllocateInstance)},
1271     {CC"monitorEnter",       CC"("OBJ")V",               FN_PTR(Unsafe_MonitorEnter)},
1272     {CC"monitorExit",        CC"("OBJ")V",               FN_PTR(Unsafe_MonitorExit)},
1273     {CC"throwException",     CC"("THR")V",               FN_PTR(Unsafe_ThrowException)}
1274 };
1275 
1276 // These are the old methods prior to the JSR 166 changes in 1.5.0
1277 static JNINativeMethod methods_141[] = {
1278 
1279     {CC"getObject",        CC"("OBJ"J)"OBJ"",   FN_PTR(Unsafe_GetObject)},
1280     {CC"putObject",        CC"("OBJ"J"OBJ")V",  FN_PTR(Unsafe_SetObject)},
1281 
1282     DECLARE_GETSETOOP_141(Boolean, Z),
1283     DECLARE_GETSETOOP_141(Byte, B),
1284     DECLARE_GETSETOOP_141(Short, S),
1285     DECLARE_GETSETOOP_141(Char, C),
1286     DECLARE_GETSETOOP_141(Int, I),
1287     DECLARE_GETSETOOP_141(Long, J),
1288     DECLARE_GETSETOOP_141(Float, F),
1289     DECLARE_GETSETOOP_141(Double, D),
1290 
1291     DECLARE_GETSETNATIVE(Byte, B),
1292     DECLARE_GETSETNATIVE(Short, S),
1293     DECLARE_GETSETNATIVE(Char, C),
1294     DECLARE_GETSETNATIVE(Int, I),
1295     DECLARE_GETSETNATIVE(Long, J),
1296     DECLARE_GETSETNATIVE(Float, F),
1297     DECLARE_GETSETNATIVE(Double, D),
1298 
1299     {CC"getAddress",         CC"("ADR")"ADR,             FN_PTR(Unsafe_GetNativeAddress)},
1300     {CC"putAddress",         CC"("ADR""ADR")V",          FN_PTR(Unsafe_SetNativeAddress)},
1301 
1302     {CC"allocateMemory",     CC"(J)"ADR,                 FN_PTR(Unsafe_AllocateMemory)},
1303     {CC"reallocateMemory",   CC"("ADR"J)"ADR,            FN_PTR(Unsafe_ReallocateMemory)},
1304 //  {CC"setMemory",          CC"("ADR"JB)V",             FN_PTR(Unsafe_SetMemory)},
1305 //  {CC"copyMemory",         CC"("ADR ADR"J)V",          FN_PTR(Unsafe_CopyMemory)},
1306     {CC"freeMemory",         CC"("ADR")V",               FN_PTR(Unsafe_FreeMemory)},
1307 
1308     {CC"objectFieldOffset",  CC"("FLD")J",               FN_PTR(Unsafe_ObjectFieldOffset)},
1309     {CC"staticFieldOffset",  CC"("FLD")J",               FN_PTR(Unsafe_StaticFieldOffset)},
1310     {CC"staticFieldBase",    CC"("FLD")"OBJ,             FN_PTR(Unsafe_StaticFieldBaseFromField)},
1311     {CC"ensureClassInitialized",CC"("CLS")V",            FN_PTR(Unsafe_EnsureClassInitialized)},
1312     {CC"arrayBaseOffset",    CC"("CLS")I",               FN_PTR(Unsafe_ArrayBaseOffset)},
1313     {CC"arrayIndexScale",    CC"("CLS")I",               FN_PTR(Unsafe_ArrayIndexScale)},
1314     {CC"addressSize",        CC"()I",                    FN_PTR(Unsafe_AddressSize)},
1315     {CC"pageSize",           CC"()I",                    FN_PTR(Unsafe_PageSize)},
1316 
1317     {CC"defineClass",        CC"("DC0_Args")"CLS,        FN_PTR(Unsafe_DefineClass0)},
1318     {CC"defineClass",        CC"("DC1_Args")"CLS,        FN_PTR(Unsafe_DefineClass1)},
1319     {CC"allocateInstance",   CC"("CLS")"OBJ,             FN_PTR(Unsafe_AllocateInstance)},
1320     {CC"monitorEnter",       CC"("OBJ")V",               FN_PTR(Unsafe_MonitorEnter)},
1321     {CC"monitorExit",        CC"("OBJ")V",               FN_PTR(Unsafe_MonitorExit)},
1322     {CC"throwException",     CC"("THR")V",               FN_PTR(Unsafe_ThrowException)}
1323 
1324 };
1325 
1326 // These are the old methods prior to the JSR 166 changes in 1.6.0
1327 static JNINativeMethod methods_15[] = {
1328 
1329     {CC"getObject",        CC"("OBJ"J)"OBJ"",   FN_PTR(Unsafe_GetObject)},
1330     {CC"putObject",        CC"("OBJ"J"OBJ")V",  FN_PTR(Unsafe_SetObject)},
1331     {CC"getObjectVolatile",CC"("OBJ"J)"OBJ"",   FN_PTR(Unsafe_GetObjectVolatile)},
1332     {CC"putObjectVolatile",CC"("OBJ"J"OBJ")V",  FN_PTR(Unsafe_SetObjectVolatile)},
1333 
1334 
1335     DECLARE_GETSETOOP(Boolean, Z),
1336     DECLARE_GETSETOOP(Byte, B),
1337     DECLARE_GETSETOOP(Short, S),
1338     DECLARE_GETSETOOP(Char, C),
1339     DECLARE_GETSETOOP(Int, I),
1340     DECLARE_GETSETOOP(Long, J),
1341     DECLARE_GETSETOOP(Float, F),
1342     DECLARE_GETSETOOP(Double, D),
1343 
1344     DECLARE_GETSETNATIVE(Byte, B),
1345     DECLARE_GETSETNATIVE(Short, S),
1346     DECLARE_GETSETNATIVE(Char, C),
1347     DECLARE_GETSETNATIVE(Int, I),
1348     DECLARE_GETSETNATIVE(Long, J),
1349     DECLARE_GETSETNATIVE(Float, F),
1350     DECLARE_GETSETNATIVE(Double, D),
1351 
1352     {CC"getAddress",         CC"("ADR")"ADR,             FN_PTR(Unsafe_GetNativeAddress)},
1353     {CC"putAddress",         CC"("ADR""ADR")V",          FN_PTR(Unsafe_SetNativeAddress)},
1354 
1355     {CC"allocateMemory",     CC"(J)"ADR,                 FN_PTR(Unsafe_AllocateMemory)},
1356     {CC"reallocateMemory",   CC"("ADR"J)"ADR,            FN_PTR(Unsafe_ReallocateMemory)},
1357 //  {CC"setMemory",          CC"("ADR"JB)V",             FN_PTR(Unsafe_SetMemory)},
1358 //  {CC"copyMemory",         CC"("ADR ADR"J)V",          FN_PTR(Unsafe_CopyMemory)},
1359     {CC"freeMemory",         CC"("ADR")V",               FN_PTR(Unsafe_FreeMemory)},
1360 
1361     {CC"objectFieldOffset",  CC"("FLD")J",               FN_PTR(Unsafe_ObjectFieldOffset)},
1362     {CC"staticFieldOffset",  CC"("FLD")J",               FN_PTR(Unsafe_StaticFieldOffset)},
1363     {CC"staticFieldBase",    CC"("FLD")"OBJ,             FN_PTR(Unsafe_StaticFieldBaseFromField)},
1364     {CC"ensureClassInitialized",CC"("CLS")V",            FN_PTR(Unsafe_EnsureClassInitialized)},
1365     {CC"arrayBaseOffset",    CC"("CLS")I",               FN_PTR(Unsafe_ArrayBaseOffset)},
1366     {CC"arrayIndexScale",    CC"("CLS")I",               FN_PTR(Unsafe_ArrayIndexScale)},
1367     {CC"addressSize",        CC"()I",                    FN_PTR(Unsafe_AddressSize)},
1368     {CC"pageSize",           CC"()I",                    FN_PTR(Unsafe_PageSize)},
1369 
1370     {CC"defineClass",        CC"("DC0_Args")"CLS,        FN_PTR(Unsafe_DefineClass0)},
1371     {CC"defineClass",        CC"("DC1_Args")"CLS,        FN_PTR(Unsafe_DefineClass1)},
1372     {CC"allocateInstance",   CC"("CLS")"OBJ,             FN_PTR(Unsafe_AllocateInstance)},
1373     {CC"monitorEnter",       CC"("OBJ")V",               FN_PTR(Unsafe_MonitorEnter)},
1374     {CC"monitorExit",        CC"("OBJ")V",               FN_PTR(Unsafe_MonitorExit)},
1375     {CC"throwException",     CC"("THR")V",               FN_PTR(Unsafe_ThrowException)},
1376     {CC"compareAndSwapObject", CC"("OBJ"J"OBJ""OBJ")Z",  FN_PTR(Unsafe_CompareAndSwapObject)},
1377     {CC"compareAndSwapInt",  CC"("OBJ"J""I""I"")Z",      FN_PTR(Unsafe_CompareAndSwapInt)},
1378     {CC"compareAndSwapLong", CC"("OBJ"J""J""J"")Z",      FN_PTR(Unsafe_CompareAndSwapLong)},
1379     {CC"park",               CC"(ZJ)V",                  FN_PTR(Unsafe_Park)},
1380     {CC"unpark",             CC"("OBJ")V",               FN_PTR(Unsafe_Unpark)}
1381 
1382 };
1383 
1384 // These are the correct methods, moving forward:
1385 static JNINativeMethod methods[] = {
1386 
1387     {CC"getObject",        CC"("OBJ"J)"OBJ"",   FN_PTR(Unsafe_GetObject)},
1388     {CC"putObject",        CC"("OBJ"J"OBJ")V",  FN_PTR(Unsafe_SetObject)},
1389     {CC"getObjectVolatile",CC"("OBJ"J)"OBJ"",   FN_PTR(Unsafe_GetObjectVolatile)},
1390     {CC"putObjectVolatile",CC"("OBJ"J"OBJ")V",  FN_PTR(Unsafe_SetObjectVolatile)},
1391 
1392 
1393     DECLARE_GETSETOOP(Boolean, Z),
1394     DECLARE_GETSETOOP(Byte, B),
1395     DECLARE_GETSETOOP(Short, S),
1396     DECLARE_GETSETOOP(Char, C),
1397     DECLARE_GETSETOOP(Int, I),
1398     DECLARE_GETSETOOP(Long, J),
1399     DECLARE_GETSETOOP(Float, F),
1400     DECLARE_GETSETOOP(Double, D),
1401 
1402     DECLARE_GETSETNATIVE(Byte, B),
1403     DECLARE_GETSETNATIVE(Short, S),
1404     DECLARE_GETSETNATIVE(Char, C),
1405     DECLARE_GETSETNATIVE(Int, I),
1406     DECLARE_GETSETNATIVE(Long, J),
1407     DECLARE_GETSETNATIVE(Float, F),
1408     DECLARE_GETSETNATIVE(Double, D),
1409 
1410     {CC"getAddress",         CC"("ADR")"ADR,             FN_PTR(Unsafe_GetNativeAddress)},
1411     {CC"putAddress",         CC"("ADR""ADR")V",          FN_PTR(Unsafe_SetNativeAddress)},
1412 
1413     {CC"allocateMemory",     CC"(J)"ADR,                 FN_PTR(Unsafe_AllocateMemory)},
1414     {CC"reallocateMemory",   CC"("ADR"J)"ADR,            FN_PTR(Unsafe_ReallocateMemory)},
1415 //  {CC"setMemory",          CC"("ADR"JB)V",             FN_PTR(Unsafe_SetMemory)},
1416 //  {CC"copyMemory",         CC"("ADR ADR"J)V",          FN_PTR(Unsafe_CopyMemory)},
1417     {CC"freeMemory",         CC"("ADR")V",               FN_PTR(Unsafe_FreeMemory)},
1418 
1419     {CC"objectFieldOffset",  CC"("FLD")J",               FN_PTR(Unsafe_ObjectFieldOffset)},
1420     {CC"staticFieldOffset",  CC"("FLD")J",               FN_PTR(Unsafe_StaticFieldOffset)},
1421     {CC"staticFieldBase",    CC"("FLD")"OBJ,             FN_PTR(Unsafe_StaticFieldBaseFromField)},
1422     {CC"ensureClassInitialized",CC"("CLS")V",            FN_PTR(Unsafe_EnsureClassInitialized)},
1423     {CC"arrayBaseOffset",    CC"("CLS")I",               FN_PTR(Unsafe_ArrayBaseOffset)},
1424     {CC"arrayIndexScale",    CC"("CLS")I",               FN_PTR(Unsafe_ArrayIndexScale)},
1425     {CC"addressSize",        CC"()I",                    FN_PTR(Unsafe_AddressSize)},
1426     {CC"pageSize",           CC"()I",                    FN_PTR(Unsafe_PageSize)},
1427 
1428     {CC"defineClass",        CC"("DC0_Args")"CLS,        FN_PTR(Unsafe_DefineClass0)},
1429     {CC"defineClass",        CC"("DC1_Args")"CLS,        FN_PTR(Unsafe_DefineClass1)},
1430     {CC"allocateInstance",   CC"("CLS")"OBJ,             FN_PTR(Unsafe_AllocateInstance)},
1431     {CC"monitorEnter",       CC"("OBJ")V",               FN_PTR(Unsafe_MonitorEnter)},
1432     {CC"monitorExit",        CC"("OBJ")V",               FN_PTR(Unsafe_MonitorExit)},
1433     {CC"tryMonitorEnter",    CC"("OBJ")Z",               FN_PTR(Unsafe_TryMonitorEnter)},
1434     {CC"throwException",     CC"("THR")V",               FN_PTR(Unsafe_ThrowException)},
1435     {CC"compareAndSwapObject", CC"("OBJ"J"OBJ""OBJ")Z",  FN_PTR(Unsafe_CompareAndSwapObject)},
1436     {CC"compareAndSwapInt",  CC"("OBJ"J""I""I"")Z",      FN_PTR(Unsafe_CompareAndSwapInt)},
1437     {CC"compareAndSwapLong", CC"("OBJ"J""J""J"")Z",      FN_PTR(Unsafe_CompareAndSwapLong)},
1438     {CC"putOrderedObject",   CC"("OBJ"J"OBJ")V",         FN_PTR(Unsafe_SetOrderedObject)},
1439     {CC"putOrderedInt",      CC"("OBJ"JI)V",             FN_PTR(Unsafe_SetOrderedInt)},
1440     {CC"putOrderedLong",     CC"("OBJ"JJ)V",             FN_PTR(Unsafe_SetOrderedLong)},
1441     {CC"park",               CC"(ZJ)V",                  FN_PTR(Unsafe_Park)},
1442     {CC"unpark",             CC"("OBJ")V",               FN_PTR(Unsafe_Unpark)}
1443 
1444 //    {CC"getLoadAverage",     CC"([DI)I",                 FN_PTR(Unsafe_Loadavg)},
1445 
1446 //    {CC"prefetchRead",       CC"("OBJ"J)V",              FN_PTR(Unsafe_PrefetchRead)},
1447 //    {CC"prefetchWrite",      CC"("OBJ"J)V",              FN_PTR(Unsafe_PrefetchWrite)}
1448 //    {CC"prefetchReadStatic", CC"("OBJ"J)V",              FN_PTR(Unsafe_PrefetchRead)},
1449 //    {CC"prefetchWriteStatic",CC"("OBJ"J)V",              FN_PTR(Unsafe_PrefetchWrite)}
1450 
1451 };
1452 
1453 JNINativeMethod loadavg_method[] = {
1454     {CC"getLoadAverage",            CC"([DI)I",                 FN_PTR(Unsafe_Loadavg)}
1455 };
1456 
1457 JNINativeMethod prefetch_methods[] = {
1458     {CC"prefetchRead",       CC"("OBJ"J)V",              FN_PTR(Unsafe_PrefetchRead)},
1459     {CC"prefetchWrite",      CC"("OBJ"J)V",              FN_PTR(Unsafe_PrefetchWrite)},
1460     {CC"prefetchReadStatic", CC"("OBJ"J)V",              FN_PTR(Unsafe_PrefetchRead)},
1461     {CC"prefetchWriteStatic",CC"("OBJ"J)V",              FN_PTR(Unsafe_PrefetchWrite)}
1462 };
1463 
1464 JNINativeMethod memcopy_methods[] = {
1465     {CC"copyMemory",         CC"("OBJ"J"OBJ"JJ)V",       FN_PTR(Unsafe_CopyMemory2)},
1466     {CC"setMemory",          CC"("OBJ"JJB)V",            FN_PTR(Unsafe_SetMemory2)}
1467 };
1468 
1469 JNINativeMethod memcopy_methods_15[] = {
1470     {CC"setMemory",          CC"("ADR"JB)V",             FN_PTR(Unsafe_SetMemory)},
1471     {CC"copyMemory",         CC"("ADR ADR"J)V",          FN_PTR(Unsafe_CopyMemory)}
1472 };
1473 
1474 JNINativeMethod anonk_methods[] = {
1475     {CC"defineAnonymousClass", CC"("DAC_Args")"CLS,      FN_PTR(Unsafe_DefineAnonymousClass)},
1476 };
1477 
1478 #undef CC
1479 #undef FN_PTR
1480 
1481 #undef ADR
1482 #undef LANG
1483 #undef OBJ
1484 #undef CLS
1485 #undef CTR
1486 #undef FLD
1487 #undef MTH
1488 #undef THR
1489 #undef DC0_Args
1490 #undef DC1_Args
1491 
1492 #undef DECLARE_GETSETOOP
1493 #undef DECLARE_GETSETNATIVE
1494 
1495 
1496 // This one function is exported, used by NativeLookup.
1497 // The Unsafe_xxx functions above are called only from the interpreter.
1498 // The optimizer looks at names and signatures to recognize
1499 // individual functions.
1500 
1501 JVM_ENTRY(void, JVM_RegisterUnsafeMethods(JNIEnv *env, jclass unsafecls))
1502   UnsafeWrapper("JVM_RegisterUnsafeMethods");
1503   {
1504     ThreadToNativeFromVM ttnfv(thread);
1505     {
1506       env->RegisterNatives(unsafecls, loadavg_method, sizeof(loadavg_method)/sizeof(JNINativeMethod));
1507       if (env->ExceptionOccurred()) {
1508         if (PrintMiscellaneous && (Verbose || WizardMode)) {
1509           tty->print_cr("Warning:  SDK 1.6 Unsafe.loadavg not found.");
1510         }
1511         env->ExceptionClear();
1512       }
1513     }
1514     {
1515       env->RegisterNatives(unsafecls, prefetch_methods, sizeof(prefetch_methods)/sizeof(JNINativeMethod));
1516       if (env->ExceptionOccurred()) {
1517         if (PrintMiscellaneous && (Verbose || WizardMode)) {
1518           tty->print_cr("Warning:  SDK 1.6 Unsafe.prefetchRead/Write not found.");
1519         }
1520         env->ExceptionClear();
1521       }
1522     }
1523     {
1524       env->RegisterNatives(unsafecls, memcopy_methods, sizeof(memcopy_methods)/sizeof(JNINativeMethod));
1525       if (env->ExceptionOccurred()) {
1526         if (PrintMiscellaneous && (Verbose || WizardMode)) {
1527           tty->print_cr("Warning:  SDK 1.7 Unsafe.copyMemory not found.");
1528         }
1529         env->ExceptionClear();
1530         env->RegisterNatives(unsafecls, memcopy_methods_15, sizeof(memcopy_methods_15)/sizeof(JNINativeMethod));
1531         if (env->ExceptionOccurred()) {
1532           if (PrintMiscellaneous && (Verbose || WizardMode)) {
1533             tty->print_cr("Warning:  SDK 1.5 Unsafe.copyMemory not found.");
1534           }
1535           env->ExceptionClear();
1536         }
1537       }
1538     }
1539     if (AnonymousClasses) {
1540       env->RegisterNatives(unsafecls, anonk_methods, sizeof(anonk_methods)/sizeof(JNINativeMethod));
1541       if (env->ExceptionOccurred()) {
1542         if (PrintMiscellaneous && (Verbose || WizardMode)) {
1543           tty->print_cr("Warning:  SDK 1.7 Unsafe.defineClass (anonymous version) not found.");
1544         }
1545         env->ExceptionClear();
1546       }
1547     }
1548     int status = env->RegisterNatives(unsafecls, methods, sizeof(methods)/sizeof(JNINativeMethod));
1549     if (env->ExceptionOccurred()) {
1550       if (PrintMiscellaneous && (Verbose || WizardMode)) {
1551         tty->print_cr("Warning:  SDK 1.6 version of Unsafe not found.");
1552       }
1553       env->ExceptionClear();
1554       // %%% For now, be backward compatible with an older class:
1555       status = env->RegisterNatives(unsafecls, methods_15, sizeof(methods_15)/sizeof(JNINativeMethod));
1556     }
1557     if (env->ExceptionOccurred()) {
1558       if (PrintMiscellaneous && (Verbose || WizardMode)) {
1559         tty->print_cr("Warning:  SDK 1.5 version of Unsafe not found.");
1560       }
1561       env->ExceptionClear();
1562       // %%% For now, be backward compatible with an older class:
1563       status = env->RegisterNatives(unsafecls, methods_141, sizeof(methods_141)/sizeof(JNINativeMethod));
1564     }
1565     if (env->ExceptionOccurred()) {
1566       if (PrintMiscellaneous && (Verbose || WizardMode)) {
1567         tty->print_cr("Warning:  SDK 1.4.1 version of Unsafe not found.");
1568       }
1569       env->ExceptionClear();
1570       // %%% For now, be backward compatible with an older class:
1571       status = env->RegisterNatives(unsafecls, methods_140, sizeof(methods_140)/sizeof(JNINativeMethod));
1572     }
1573     guarantee(status == 0, "register unsafe natives");
1574   }
1575 JVM_END