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