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