1 /* 2 * Copyright (c) 2000, 2015, 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 "oops/objArrayOop.inline.hpp" 29 #include "oops/oop.inline.hpp" 30 #include "prims/jni.h" 31 #include "prims/jvm.h" 32 #include "runtime/atomic.inline.hpp" 33 #include "runtime/globals.hpp" 34 #include "runtime/interfaceSupport.hpp" 35 #include "runtime/orderAccess.inline.hpp" 36 #include "runtime/reflection.hpp" 37 #include "runtime/vm_version.hpp" 38 #include "services/threadService.hpp" 39 #include "trace/tracing.hpp" 40 #include "utilities/copy.hpp" 41 #include "utilities/dtrace.hpp" 42 #include "utilities/macros.hpp" 43 #if INCLUDE_ALL_GCS 44 #include "gc_implementation/g1/g1SATBCardTableModRefBS.hpp" 45 #endif // INCLUDE_ALL_GCS 46 47 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC 48 49 /* 50 * Implementation of class sun.misc.Unsafe 51 */ 52 53 54 #define MAX_OBJECT_SIZE \ 55 ( arrayOopDesc::header_size(T_DOUBLE) * HeapWordSize \ 56 + ((julong)max_jint * sizeof(double)) ) 57 58 59 #define UNSAFE_ENTRY(result_type, header) \ 60 JVM_ENTRY(result_type, header) 61 62 // Can't use UNSAFE_LEAF because it has the signature of a straight 63 // call into the runtime (just like JVM_LEAF, funny that) but it's 64 // called like a Java Native and thus the wrapper built for it passes 65 // arguments like a JNI call. It expects those arguments to be popped 66 // from the stack on Intel like all good JNI args are, and adjusts the 67 // stack according. Since the JVM_LEAF call expects no extra 68 // arguments the stack isn't popped in the C code, is pushed by the 69 // wrapper and we get sick. 70 //#define UNSAFE_LEAF(result_type, header) \ 71 // JVM_LEAF(result_type, header) 72 73 #define UNSAFE_END JVM_END 74 75 #define UnsafeWrapper(arg) /*nothing, for the present*/ 76 77 78 inline void* addr_from_java(jlong addr) { 79 // This assert fails in a variety of ways on 32-bit systems. 80 // It is impossible to predict whether native code that converts 81 // pointers to longs will sign-extend or zero-extend the addresses. 82 //assert(addr == (uintptr_t)addr, "must not be odd high bits"); 83 return (void*)(uintptr_t)addr; 84 } 85 86 inline jlong addr_to_java(void* p) { 87 assert(p == (void*)(uintptr_t)p, "must not be odd high bits"); 88 return (uintptr_t)p; 89 } 90 91 92 // Note: The VM's obj_field and related accessors use byte-scaled 93 // ("unscaled") offsets, just as the unsafe methods do. 94 95 // However, the method Unsafe.fieldOffset explicitly declines to 96 // guarantee this. The field offset values manipulated by the Java user 97 // through the Unsafe API are opaque cookies that just happen to be byte 98 // offsets. We represent this state of affairs by passing the cookies 99 // through conversion functions when going between the VM and the Unsafe API. 100 // The conversion functions just happen to be no-ops at present. 101 102 inline jlong field_offset_to_byte_offset(jlong field_offset) { 103 return field_offset; 104 } 105 106 inline jlong field_offset_from_byte_offset(jlong byte_offset) { 107 return byte_offset; 108 } 109 110 inline jint invocation_key_from_method_slot(jint slot) { 111 return slot; 112 } 113 114 inline jint invocation_key_to_method_slot(jint key) { 115 return key; 116 } 117 118 inline void* index_oop_from_field_offset_long(oop p, jlong field_offset) { 119 jlong byte_offset = field_offset_to_byte_offset(field_offset); 120 #ifdef ASSERT 121 if (p != NULL) { 122 assert(byte_offset >= 0 && byte_offset <= (jlong)MAX_OBJECT_SIZE, "sane offset"); 123 if (byte_offset == (jint)byte_offset) { 124 void* ptr_plus_disp = (address)p + byte_offset; 125 assert((void*)p->obj_field_addr<oop>((jint)byte_offset) == ptr_plus_disp, 126 "raw [ptr+disp] must be consistent with oop::field_base"); 127 } 128 jlong p_size = HeapWordSize * (jlong)(p->size()); 129 assert(byte_offset < p_size, err_msg("Unsafe access: offset " INT64_FORMAT " > object's size " INT64_FORMAT, byte_offset, p_size)); 130 } 131 #endif 132 if (sizeof(char*) == sizeof(jint)) // (this constant folds!) 133 return (address)p + (jint) byte_offset; 134 else 135 return (address)p + byte_offset; 136 } 137 138 // Externally callable versions: 139 // (Use these in compiler intrinsics which emulate unsafe primitives.) 140 jlong Unsafe_field_offset_to_byte_offset(jlong field_offset) { 141 return field_offset; 142 } 143 jlong Unsafe_field_offset_from_byte_offset(jlong byte_offset) { 144 return byte_offset; 145 } 146 jint Unsafe_invocation_key_from_method_slot(jint slot) { 147 return invocation_key_from_method_slot(slot); 148 } 149 jint Unsafe_invocation_key_to_method_slot(jint key) { 150 return invocation_key_to_method_slot(key); 151 } 152 153 154 ///// Data in the Java heap. 155 156 #define GET_FIELD(obj, offset, type_name, v) \ 157 oop p = JNIHandles::resolve(obj); \ 158 type_name v = *(type_name*)index_oop_from_field_offset_long(p, offset) 159 160 #define SET_FIELD(obj, offset, type_name, x) \ 161 oop p = JNIHandles::resolve(obj); \ 162 *(type_name*)index_oop_from_field_offset_long(p, offset) = x 163 164 #define GET_FIELD_VOLATILE(obj, offset, type_name, v) \ 165 oop p = JNIHandles::resolve(obj); \ 166 if (support_IRIW_for_not_multiple_copy_atomic_cpu) { \ 167 OrderAccess::fence(); \ 168 } \ 169 volatile type_name v = OrderAccess::load_acquire((volatile type_name*)index_oop_from_field_offset_long(p, offset)); 170 171 #define SET_FIELD_VOLATILE(obj, offset, type_name, x) \ 172 oop p = JNIHandles::resolve(obj); \ 173 OrderAccess::release_store_fence((volatile type_name*)index_oop_from_field_offset_long(p, offset), x); 174 175 // Macros for oops that check UseCompressedOops 176 177 #define GET_OOP_FIELD(obj, offset, v) \ 178 oop p = JNIHandles::resolve(obj); \ 179 oop v; \ 180 if (UseCompressedOops) { \ 181 narrowOop n = *(narrowOop*)index_oop_from_field_offset_long(p, offset); \ 182 v = oopDesc::decode_heap_oop(n); \ 183 } else { \ 184 v = *(oop*)index_oop_from_field_offset_long(p, offset); \ 185 } 186 187 188 // Get/SetObject must be special-cased, since it works with handles. 189 190 // These functions allow a null base pointer with an arbitrary address. 191 // But if the base pointer is non-null, the offset should make some sense. 192 // That is, it should be in the range [0, MAX_OBJECT_SIZE]. 193 UNSAFE_ENTRY(jobject, Unsafe_GetObject(JNIEnv *env, jobject unsafe, jobject obj, jlong offset)) 194 UnsafeWrapper("Unsafe_GetObject"); 195 GET_OOP_FIELD(obj, offset, v) 196 jobject ret = JNIHandles::make_local(env, v); 197 #if INCLUDE_ALL_GCS 198 // We could be accessing the referent field in a reference 199 // object. If G1 is enabled then we need to register non-null 200 // referent with the SATB barrier. 201 if (UseG1GC) { 202 bool needs_barrier = false; 203 204 if (ret != NULL) { 205 if (offset == java_lang_ref_Reference::referent_offset && obj != NULL) { 206 oop o = JNIHandles::resolve(obj); 207 Klass* k = o->klass(); 208 if (InstanceKlass::cast(k)->reference_type() != REF_NONE) { 209 assert(InstanceKlass::cast(k)->is_subclass_of(SystemDictionary::Reference_klass()), "sanity"); 210 needs_barrier = true; 211 } 212 } 213 } 214 215 if (needs_barrier) { 216 oop referent = JNIHandles::resolve(ret); 217 G1SATBCardTableModRefBS::enqueue(referent); 218 } 219 } 220 #endif // INCLUDE_ALL_GCS 221 return ret; 222 UNSAFE_END 223 224 UNSAFE_ENTRY(void, Unsafe_SetObject(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject x_h)) 225 UnsafeWrapper("Unsafe_SetObject"); 226 oop x = JNIHandles::resolve(x_h); 227 oop p = JNIHandles::resolve(obj); 228 if (UseCompressedOops) { 229 oop_store((narrowOop*)index_oop_from_field_offset_long(p, offset), x); 230 } else { 231 oop_store((oop*)index_oop_from_field_offset_long(p, offset), x); 232 } 233 UNSAFE_END 234 235 UNSAFE_ENTRY(jobject, Unsafe_GetObjectVolatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset)) 236 UnsafeWrapper("Unsafe_GetObjectVolatile"); 237 oop p = JNIHandles::resolve(obj); 238 void* addr = index_oop_from_field_offset_long(p, offset); 239 volatile oop v; 240 if (UseCompressedOops) { 241 volatile narrowOop n = *(volatile narrowOop*) addr; 242 (void)const_cast<oop&>(v = oopDesc::decode_heap_oop(n)); 243 } else { 244 (void)const_cast<oop&>(v = *(volatile oop*) addr); 245 } 246 OrderAccess::acquire(); 247 return JNIHandles::make_local(env, v); 248 UNSAFE_END 249 250 UNSAFE_ENTRY(void, Unsafe_SetObjectVolatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject x_h)) 251 UnsafeWrapper("Unsafe_SetObjectVolatile"); 252 oop x = JNIHandles::resolve(x_h); 253 oop p = JNIHandles::resolve(obj); 254 void* addr = index_oop_from_field_offset_long(p, offset); 255 OrderAccess::release(); 256 if (UseCompressedOops) { 257 oop_store((narrowOop*)addr, x); 258 } else { 259 oop_store((oop*)addr, x); 260 } 261 OrderAccess::fence(); 262 UNSAFE_END 263 264 #ifndef SUPPORTS_NATIVE_CX8 265 266 // VM_Version::supports_cx8() is a surrogate for 'supports atomic long memory ops'. 267 // 268 // On platforms which do not support atomic compare-and-swap of jlong (8 byte) 269 // values we have to use a lock-based scheme to enforce atomicity. This has to be 270 // applied to all Unsafe operations that set the value of a jlong field. Even so 271 // the compareAndSwapLong operation will not be atomic with respect to direct stores 272 // to the field from Java code. It is important therefore that any Java code that 273 // utilizes these Unsafe jlong operations does not perform direct stores. To permit 274 // direct loads of the field from Java code we must also use Atomic::store within the 275 // locked regions. And for good measure, in case there are direct stores, we also 276 // employ Atomic::load within those regions. Note that the field in question must be 277 // volatile and so must have atomic load/store accesses applied at the Java level. 278 // 279 // The locking scheme could utilize a range of strategies for controlling the locking 280 // granularity: from a lock per-field through to a single global lock. The latter is 281 // the simplest and is used for the current implementation. Note that the Java object 282 // that contains the field, can not, in general, be used for locking. To do so can lead 283 // to deadlocks as we may introduce locking into what appears to the Java code to be a 284 // lock-free path. 285 // 286 // As all the locked-regions are very short and themselves non-blocking we can treat 287 // them as leaf routines and elide safepoint checks (ie we don't perform any thread 288 // state transitions even when blocking for the lock). Note that if we do choose to 289 // add safepoint checks and thread state transitions, we must ensure that we calculate 290 // the address of the field _after_ we have acquired the lock, else the object may have 291 // been moved by the GC 292 293 UNSAFE_ENTRY(jlong, Unsafe_GetLongVolatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset)) 294 UnsafeWrapper("Unsafe_GetLongVolatile"); 295 { 296 if (VM_Version::supports_cx8()) { 297 GET_FIELD_VOLATILE(obj, offset, jlong, v); 298 return v; 299 } 300 else { 301 Handle p (THREAD, JNIHandles::resolve(obj)); 302 jlong* addr = (jlong*)(index_oop_from_field_offset_long(p(), offset)); 303 MutexLockerEx mu(UnsafeJlong_lock, Mutex::_no_safepoint_check_flag); 304 jlong value = Atomic::load(addr); 305 return value; 306 } 307 } 308 UNSAFE_END 309 310 UNSAFE_ENTRY(void, Unsafe_SetLongVolatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jlong x)) 311 UnsafeWrapper("Unsafe_SetLongVolatile"); 312 { 313 if (VM_Version::supports_cx8()) { 314 SET_FIELD_VOLATILE(obj, offset, jlong, x); 315 } 316 else { 317 Handle p (THREAD, JNIHandles::resolve(obj)); 318 jlong* addr = (jlong*)(index_oop_from_field_offset_long(p(), offset)); 319 MutexLockerEx mu(UnsafeJlong_lock, Mutex::_no_safepoint_check_flag); 320 Atomic::store(x, addr); 321 } 322 } 323 UNSAFE_END 324 325 #endif // not SUPPORTS_NATIVE_CX8 326 327 UNSAFE_ENTRY(jboolean, Unsafe_isBigEndian0(JNIEnv *env, jobject unsafe)) 328 UnsafeWrapper("Unsafe_IsBigEndian0"); 329 { 330 #ifdef VM_LITTLE_ENDIAN 331 return false; 332 #else 333 return true; 334 #endif 335 } 336 UNSAFE_END 337 338 UNSAFE_ENTRY(jint, Unsafe_unalignedAccess0(JNIEnv *env, jobject unsafe)) 339 UnsafeWrapper("Unsafe_UnalignedAccess0"); 340 { 341 return UseUnalignedAccesses; 342 } 343 UNSAFE_END 344 345 #define DEFINE_GETSETOOP(jboolean, Boolean) \ 346 \ 347 UNSAFE_ENTRY(jboolean, Unsafe_Get##Boolean##140(JNIEnv *env, jobject unsafe, jobject obj, jint offset)) \ 348 UnsafeWrapper("Unsafe_Get"#Boolean); \ 349 if (obj == NULL) THROW_0(vmSymbols::java_lang_NullPointerException()); \ 350 GET_FIELD(obj, offset, jboolean, v); \ 351 return v; \ 352 UNSAFE_END \ 353 \ 354 UNSAFE_ENTRY(void, Unsafe_Set##Boolean##140(JNIEnv *env, jobject unsafe, jobject obj, jint offset, jboolean x)) \ 355 UnsafeWrapper("Unsafe_Set"#Boolean); \ 356 if (obj == NULL) THROW(vmSymbols::java_lang_NullPointerException()); \ 357 SET_FIELD(obj, offset, jboolean, x); \ 358 UNSAFE_END \ 359 \ 360 UNSAFE_ENTRY(jboolean, Unsafe_Get##Boolean(JNIEnv *env, jobject unsafe, jobject obj, jlong offset)) \ 361 UnsafeWrapper("Unsafe_Get"#Boolean); \ 362 GET_FIELD(obj, offset, jboolean, v); \ 363 return v; \ 364 UNSAFE_END \ 365 \ 366 UNSAFE_ENTRY(void, Unsafe_Set##Boolean(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jboolean x)) \ 367 UnsafeWrapper("Unsafe_Set"#Boolean); \ 368 SET_FIELD(obj, offset, jboolean, x); \ 369 UNSAFE_END \ 370 \ 371 // END DEFINE_GETSETOOP. 372 373 DEFINE_GETSETOOP(jboolean, Boolean) 374 DEFINE_GETSETOOP(jbyte, Byte) 375 DEFINE_GETSETOOP(jshort, Short); 376 DEFINE_GETSETOOP(jchar, Char); 377 DEFINE_GETSETOOP(jint, Int); 378 DEFINE_GETSETOOP(jlong, Long); 379 DEFINE_GETSETOOP(jfloat, Float); 380 DEFINE_GETSETOOP(jdouble, Double); 381 382 #undef DEFINE_GETSETOOP 383 384 #define DEFINE_GETSETOOP_VOLATILE(jboolean, Boolean) \ 385 \ 386 UNSAFE_ENTRY(jboolean, Unsafe_Get##Boolean##Volatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset)) \ 387 UnsafeWrapper("Unsafe_Get"#Boolean); \ 388 GET_FIELD_VOLATILE(obj, offset, jboolean, v); \ 389 return v; \ 390 UNSAFE_END \ 391 \ 392 UNSAFE_ENTRY(void, Unsafe_Set##Boolean##Volatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jboolean x)) \ 393 UnsafeWrapper("Unsafe_Set"#Boolean); \ 394 SET_FIELD_VOLATILE(obj, offset, jboolean, x); \ 395 UNSAFE_END \ 396 \ 397 // END DEFINE_GETSETOOP_VOLATILE. 398 399 DEFINE_GETSETOOP_VOLATILE(jboolean, Boolean) 400 DEFINE_GETSETOOP_VOLATILE(jbyte, Byte) 401 DEFINE_GETSETOOP_VOLATILE(jshort, Short); 402 DEFINE_GETSETOOP_VOLATILE(jchar, Char); 403 DEFINE_GETSETOOP_VOLATILE(jint, Int); 404 DEFINE_GETSETOOP_VOLATILE(jfloat, Float); 405 DEFINE_GETSETOOP_VOLATILE(jdouble, Double); 406 407 #ifdef SUPPORTS_NATIVE_CX8 408 DEFINE_GETSETOOP_VOLATILE(jlong, Long); 409 #endif 410 411 #undef DEFINE_GETSETOOP_VOLATILE 412 413 // The non-intrinsified versions of setOrdered just use setVolatile 414 415 UNSAFE_ENTRY(void, Unsafe_SetOrderedInt(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jint x)) 416 UnsafeWrapper("Unsafe_SetOrderedInt"); 417 SET_FIELD_VOLATILE(obj, offset, jint, x); 418 UNSAFE_END 419 420 UNSAFE_ENTRY(void, Unsafe_SetOrderedObject(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject x_h)) 421 UnsafeWrapper("Unsafe_SetOrderedObject"); 422 oop x = JNIHandles::resolve(x_h); 423 oop p = JNIHandles::resolve(obj); 424 void* addr = index_oop_from_field_offset_long(p, offset); 425 OrderAccess::release(); 426 if (UseCompressedOops) { 427 oop_store((narrowOop*)addr, x); 428 } else { 429 oop_store((oop*)addr, x); 430 } 431 OrderAccess::fence(); 432 UNSAFE_END 433 434 UNSAFE_ENTRY(void, Unsafe_SetOrderedLong(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jlong x)) 435 UnsafeWrapper("Unsafe_SetOrderedLong"); 436 #ifdef SUPPORTS_NATIVE_CX8 437 SET_FIELD_VOLATILE(obj, offset, jlong, x); 438 #else 439 // Keep old code for platforms which may not have atomic long (8 bytes) instructions 440 { 441 if (VM_Version::supports_cx8()) { 442 SET_FIELD_VOLATILE(obj, offset, jlong, x); 443 } 444 else { 445 Handle p (THREAD, JNIHandles::resolve(obj)); 446 jlong* addr = (jlong*)(index_oop_from_field_offset_long(p(), offset)); 447 MutexLockerEx mu(UnsafeJlong_lock, Mutex::_no_safepoint_check_flag); 448 Atomic::store(x, addr); 449 } 450 } 451 #endif 452 UNSAFE_END 453 454 UNSAFE_ENTRY(void, Unsafe_LoadFence(JNIEnv *env, jobject unsafe)) 455 UnsafeWrapper("Unsafe_LoadFence"); 456 OrderAccess::acquire(); 457 UNSAFE_END 458 459 UNSAFE_ENTRY(void, Unsafe_StoreFence(JNIEnv *env, jobject unsafe)) 460 UnsafeWrapper("Unsafe_StoreFence"); 461 OrderAccess::release(); 462 UNSAFE_END 463 464 UNSAFE_ENTRY(void, Unsafe_FullFence(JNIEnv *env, jobject unsafe)) 465 UnsafeWrapper("Unsafe_FullFence"); 466 OrderAccess::fence(); 467 UNSAFE_END 468 469 ////// Data in the C heap. 470 471 // Note: These do not throw NullPointerException for bad pointers. 472 // They just crash. Only a oop base pointer can generate a NullPointerException. 473 // 474 #define DEFINE_GETSETNATIVE(java_type, Type, native_type) \ 475 \ 476 UNSAFE_ENTRY(java_type, Unsafe_GetNative##Type(JNIEnv *env, jobject unsafe, jlong addr)) \ 477 UnsafeWrapper("Unsafe_GetNative"#Type); \ 478 void* p = addr_from_java(addr); \ 479 JavaThread* t = JavaThread::current(); \ 480 t->set_doing_unsafe_access(true); \ 481 java_type x = *(volatile native_type*)p; \ 482 t->set_doing_unsafe_access(false); \ 483 return x; \ 484 UNSAFE_END \ 485 \ 486 UNSAFE_ENTRY(void, Unsafe_SetNative##Type(JNIEnv *env, jobject unsafe, jlong addr, java_type x)) \ 487 UnsafeWrapper("Unsafe_SetNative"#Type); \ 488 JavaThread* t = JavaThread::current(); \ 489 t->set_doing_unsafe_access(true); \ 490 void* p = addr_from_java(addr); \ 491 *(volatile native_type*)p = x; \ 492 t->set_doing_unsafe_access(false); \ 493 UNSAFE_END \ 494 \ 495 // END DEFINE_GETSETNATIVE. 496 497 DEFINE_GETSETNATIVE(jbyte, Byte, signed char) 498 DEFINE_GETSETNATIVE(jshort, Short, signed short); 499 DEFINE_GETSETNATIVE(jchar, Char, unsigned short); 500 DEFINE_GETSETNATIVE(jint, Int, jint); 501 // no long -- handled specially 502 DEFINE_GETSETNATIVE(jfloat, Float, float); 503 DEFINE_GETSETNATIVE(jdouble, Double, double); 504 505 #undef DEFINE_GETSETNATIVE 506 507 UNSAFE_ENTRY(jlong, Unsafe_GetNativeLong(JNIEnv *env, jobject unsafe, jlong addr)) 508 UnsafeWrapper("Unsafe_GetNativeLong"); 509 JavaThread* t = JavaThread::current(); 510 // We do it this way to avoid problems with access to heap using 64 511 // bit loads, as jlong in heap could be not 64-bit aligned, and on 512 // some CPUs (SPARC) it leads to SIGBUS. 513 t->set_doing_unsafe_access(true); 514 void* p = addr_from_java(addr); 515 jlong x; 516 if (((intptr_t)p & 7) == 0) { 517 // jlong is aligned, do a volatile access 518 x = *(volatile jlong*)p; 519 } else { 520 jlong_accessor acc; 521 acc.words[0] = ((volatile jint*)p)[0]; 522 acc.words[1] = ((volatile jint*)p)[1]; 523 x = acc.long_value; 524 } 525 t->set_doing_unsafe_access(false); 526 return x; 527 UNSAFE_END 528 529 UNSAFE_ENTRY(void, Unsafe_SetNativeLong(JNIEnv *env, jobject unsafe, jlong addr, jlong x)) 530 UnsafeWrapper("Unsafe_SetNativeLong"); 531 JavaThread* t = JavaThread::current(); 532 // see comment for Unsafe_GetNativeLong 533 t->set_doing_unsafe_access(true); 534 void* p = addr_from_java(addr); 535 if (((intptr_t)p & 7) == 0) { 536 // jlong is aligned, do a volatile access 537 *(volatile jlong*)p = x; 538 } else { 539 jlong_accessor acc; 540 acc.long_value = x; 541 ((volatile jint*)p)[0] = acc.words[0]; 542 ((volatile jint*)p)[1] = acc.words[1]; 543 } 544 t->set_doing_unsafe_access(false); 545 UNSAFE_END 546 547 548 UNSAFE_ENTRY(jlong, Unsafe_GetNativeAddress(JNIEnv *env, jobject unsafe, jlong addr)) 549 UnsafeWrapper("Unsafe_GetNativeAddress"); 550 void* p = addr_from_java(addr); 551 return addr_to_java(*(void**)p); 552 UNSAFE_END 553 554 UNSAFE_ENTRY(void, Unsafe_SetNativeAddress(JNIEnv *env, jobject unsafe, jlong addr, jlong x)) 555 UnsafeWrapper("Unsafe_SetNativeAddress"); 556 void* p = addr_from_java(addr); 557 *(void**)p = addr_from_java(x); 558 UNSAFE_END 559 560 561 ////// Allocation requests 562 563 UNSAFE_ENTRY(jobject, Unsafe_AllocateInstance(JNIEnv *env, jobject unsafe, jclass cls)) 564 UnsafeWrapper("Unsafe_AllocateInstance"); 565 { 566 ThreadToNativeFromVM ttnfv(thread); 567 return env->AllocObject(cls); 568 } 569 UNSAFE_END 570 571 UNSAFE_ENTRY(jlong, Unsafe_AllocateMemory(JNIEnv *env, jobject unsafe, jlong size)) 572 UnsafeWrapper("Unsafe_AllocateMemory"); 573 size_t sz = (size_t)size; 574 if (sz != (julong)size || size < 0) { 575 THROW_0(vmSymbols::java_lang_IllegalArgumentException()); 576 } 577 if (sz == 0) { 578 return 0; 579 } 580 sz = round_to(sz, HeapWordSize); 581 void* x = os::malloc(sz, mtInternal); 582 if (x == NULL) { 583 THROW_0(vmSymbols::java_lang_OutOfMemoryError()); 584 } 585 //Copy::fill_to_words((HeapWord*)x, sz / HeapWordSize); 586 return addr_to_java(x); 587 UNSAFE_END 588 589 UNSAFE_ENTRY(jlong, Unsafe_ReallocateMemory(JNIEnv *env, jobject unsafe, jlong addr, jlong size)) 590 UnsafeWrapper("Unsafe_ReallocateMemory"); 591 void* p = addr_from_java(addr); 592 size_t sz = (size_t)size; 593 if (sz != (julong)size || size < 0) { 594 THROW_0(vmSymbols::java_lang_IllegalArgumentException()); 595 } 596 if (sz == 0) { 597 os::free(p); 598 return 0; 599 } 600 sz = round_to(sz, HeapWordSize); 601 void* x = (p == NULL) ? os::malloc(sz, mtInternal) : os::realloc(p, sz, mtInternal); 602 if (x == NULL) { 603 THROW_0(vmSymbols::java_lang_OutOfMemoryError()); 604 } 605 return addr_to_java(x); 606 UNSAFE_END 607 608 UNSAFE_ENTRY(void, Unsafe_FreeMemory(JNIEnv *env, jobject unsafe, jlong addr)) 609 UnsafeWrapper("Unsafe_FreeMemory"); 610 void* p = addr_from_java(addr); 611 if (p == NULL) { 612 return; 613 } 614 os::free(p); 615 UNSAFE_END 616 617 UNSAFE_ENTRY(void, Unsafe_SetMemory(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jlong size, jbyte value)) 618 UnsafeWrapper("Unsafe_SetMemory"); 619 size_t sz = (size_t)size; 620 if (sz != (julong)size || size < 0) { 621 THROW(vmSymbols::java_lang_IllegalArgumentException()); 622 } 623 oop base = JNIHandles::resolve(obj); 624 void* p = index_oop_from_field_offset_long(base, offset); 625 Copy::fill_to_memory_atomic(p, sz, value); 626 UNSAFE_END 627 628 UNSAFE_ENTRY(void, Unsafe_CopyMemory(JNIEnv *env, jobject unsafe, jobject srcObj, jlong srcOffset, jobject dstObj, jlong dstOffset, jlong size)) 629 UnsafeWrapper("Unsafe_CopyMemory"); 630 if (size == 0) { 631 return; 632 } 633 size_t sz = (size_t)size; 634 if (sz != (julong)size || size < 0) { 635 THROW(vmSymbols::java_lang_IllegalArgumentException()); 636 } 637 oop srcp = JNIHandles::resolve(srcObj); 638 oop dstp = JNIHandles::resolve(dstObj); 639 if (dstp != NULL && !dstp->is_typeArray()) { 640 // NYI: This works only for non-oop arrays at present. 641 // Generalizing it would be reasonable, but requires card marking. 642 // Also, autoboxing a Long from 0L in copyMemory(x,y, 0L,z, n) would be bad. 643 THROW(vmSymbols::java_lang_IllegalArgumentException()); 644 } 645 void* src = index_oop_from_field_offset_long(srcp, srcOffset); 646 void* dst = index_oop_from_field_offset_long(dstp, dstOffset); 647 Copy::conjoint_memory_atomic(src, dst, sz); 648 UNSAFE_END 649 650 651 ////// Random queries 652 653 // See comment at file start about UNSAFE_LEAF 654 //UNSAFE_LEAF(jint, Unsafe_AddressSize()) 655 UNSAFE_ENTRY(jint, Unsafe_AddressSize(JNIEnv *env, jobject unsafe)) 656 UnsafeWrapper("Unsafe_AddressSize"); 657 return sizeof(void*); 658 UNSAFE_END 659 660 // See comment at file start about UNSAFE_LEAF 661 //UNSAFE_LEAF(jint, Unsafe_PageSize()) 662 UNSAFE_ENTRY(jint, Unsafe_PageSize(JNIEnv *env, jobject unsafe)) 663 UnsafeWrapper("Unsafe_PageSize"); 664 return os::vm_page_size(); 665 UNSAFE_END 666 667 jint find_field_offset(jobject field, int must_be_static, TRAPS) { 668 if (field == NULL) { 669 THROW_0(vmSymbols::java_lang_NullPointerException()); 670 } 671 672 oop reflected = JNIHandles::resolve_non_null(field); 673 oop mirror = java_lang_reflect_Field::clazz(reflected); 674 Klass* k = java_lang_Class::as_Klass(mirror); 675 int slot = java_lang_reflect_Field::slot(reflected); 676 int modifiers = java_lang_reflect_Field::modifiers(reflected); 677 678 if (must_be_static >= 0) { 679 int really_is_static = ((modifiers & JVM_ACC_STATIC) != 0); 680 if (must_be_static != really_is_static) { 681 THROW_0(vmSymbols::java_lang_IllegalArgumentException()); 682 } 683 } 684 685 int offset = InstanceKlass::cast(k)->field_offset(slot); 686 return field_offset_from_byte_offset(offset); 687 } 688 689 UNSAFE_ENTRY(jlong, Unsafe_ObjectFieldOffset(JNIEnv *env, jobject unsafe, jobject field)) 690 UnsafeWrapper("Unsafe_ObjectFieldOffset"); 691 return find_field_offset(field, 0, THREAD); 692 UNSAFE_END 693 694 UNSAFE_ENTRY(jlong, Unsafe_StaticFieldOffset(JNIEnv *env, jobject unsafe, jobject field)) 695 UnsafeWrapper("Unsafe_StaticFieldOffset"); 696 return find_field_offset(field, 1, THREAD); 697 UNSAFE_END 698 699 UNSAFE_ENTRY(jobject, Unsafe_StaticFieldBaseFromField(JNIEnv *env, jobject unsafe, jobject field)) 700 UnsafeWrapper("Unsafe_StaticFieldBase"); 701 // Note: In this VM implementation, a field address is always a short 702 // offset from the base of a a klass metaobject. Thus, the full dynamic 703 // range of the return type is never used. However, some implementations 704 // might put the static field inside an array shared by many classes, 705 // or even at a fixed address, in which case the address could be quite 706 // large. In that last case, this function would return NULL, since 707 // the address would operate alone, without any base pointer. 708 709 if (field == NULL) THROW_0(vmSymbols::java_lang_NullPointerException()); 710 711 oop reflected = JNIHandles::resolve_non_null(field); 712 oop mirror = java_lang_reflect_Field::clazz(reflected); 713 int modifiers = java_lang_reflect_Field::modifiers(reflected); 714 715 if ((modifiers & JVM_ACC_STATIC) == 0) { 716 THROW_0(vmSymbols::java_lang_IllegalArgumentException()); 717 } 718 719 return JNIHandles::make_local(env, mirror); 720 UNSAFE_END 721 722 UNSAFE_ENTRY(void, Unsafe_EnsureClassInitialized(JNIEnv *env, jobject unsafe, jobject clazz)) { 723 UnsafeWrapper("Unsafe_EnsureClassInitialized"); 724 if (clazz == NULL) { 725 THROW(vmSymbols::java_lang_NullPointerException()); 726 } 727 oop mirror = JNIHandles::resolve_non_null(clazz); 728 729 Klass* klass = java_lang_Class::as_Klass(mirror); 730 if (klass != NULL && klass->should_be_initialized()) { 731 InstanceKlass* k = InstanceKlass::cast(klass); 732 k->initialize(CHECK); 733 } 734 } 735 UNSAFE_END 736 737 UNSAFE_ENTRY(jboolean, Unsafe_ShouldBeInitialized(JNIEnv *env, jobject unsafe, jobject clazz)) { 738 UnsafeWrapper("Unsafe_ShouldBeInitialized"); 739 if (clazz == NULL) { 740 THROW_(vmSymbols::java_lang_NullPointerException(), false); 741 } 742 oop mirror = JNIHandles::resolve_non_null(clazz); 743 Klass* klass = java_lang_Class::as_Klass(mirror); 744 if (klass != NULL && klass->should_be_initialized()) { 745 return true; 746 } 747 return false; 748 } 749 UNSAFE_END 750 751 static void getBaseAndScale(int& base, int& scale, jclass acls, TRAPS) { 752 if (acls == NULL) { 753 THROW(vmSymbols::java_lang_NullPointerException()); 754 } 755 oop mirror = JNIHandles::resolve_non_null(acls); 756 Klass* k = java_lang_Class::as_Klass(mirror); 757 if (k == NULL || !k->oop_is_array()) { 758 THROW(vmSymbols::java_lang_InvalidClassException()); 759 } else if (k->oop_is_objArray()) { 760 base = arrayOopDesc::base_offset_in_bytes(T_OBJECT); 761 scale = heapOopSize; 762 } else if (k->oop_is_typeArray()) { 763 TypeArrayKlass* tak = TypeArrayKlass::cast(k); 764 base = tak->array_header_in_bytes(); 765 assert(base == arrayOopDesc::base_offset_in_bytes(tak->element_type()), "array_header_size semantics ok"); 766 scale = (1 << tak->log2_element_size()); 767 } else { 768 ShouldNotReachHere(); 769 } 770 } 771 772 UNSAFE_ENTRY(jint, Unsafe_ArrayBaseOffset(JNIEnv *env, jobject unsafe, jclass acls)) 773 UnsafeWrapper("Unsafe_ArrayBaseOffset"); 774 int base, scale; 775 getBaseAndScale(base, scale, acls, CHECK_0); 776 return field_offset_from_byte_offset(base); 777 UNSAFE_END 778 779 780 UNSAFE_ENTRY(jint, Unsafe_ArrayIndexScale(JNIEnv *env, jobject unsafe, jclass acls)) 781 UnsafeWrapper("Unsafe_ArrayIndexScale"); 782 int base, scale; 783 getBaseAndScale(base, scale, acls, CHECK_0); 784 // This VM packs both fields and array elements down to the byte. 785 // But watch out: If this changes, so that array references for 786 // a given primitive type (say, T_BOOLEAN) use different memory units 787 // than fields, this method MUST return zero for such arrays. 788 // For example, the VM used to store sub-word sized fields in full 789 // words in the object layout, so that accessors like getByte(Object,int) 790 // did not really do what one might expect for arrays. Therefore, 791 // this function used to report a zero scale factor, so that the user 792 // would know not to attempt to access sub-word array elements. 793 // // Code for unpacked fields: 794 // if (scale < wordSize) return 0; 795 796 // The following allows for a pretty general fieldOffset cookie scheme, 797 // but requires it to be linear in byte offset. 798 return field_offset_from_byte_offset(scale) - field_offset_from_byte_offset(0); 799 UNSAFE_END 800 801 802 static inline void throw_new(JNIEnv *env, const char *ename) { 803 char buf[100]; 804 jio_snprintf(buf, 100, "%s%s", "java/lang/", ename); 805 jclass cls = env->FindClass(buf); 806 if (env->ExceptionCheck()) { 807 env->ExceptionClear(); 808 tty->print_cr("Unsafe: cannot throw %s because FindClass has failed", buf); 809 return; 810 } 811 char* msg = NULL; 812 env->ThrowNew(cls, msg); 813 } 814 815 static jclass Unsafe_DefineClass_impl(JNIEnv *env, jstring name, jbyteArray data, int offset, int length, jobject loader, jobject pd) { 816 { 817 // Code lifted from JDK 1.3 ClassLoader.c 818 819 jbyte *body; 820 char *utfName; 821 jclass result = 0; 822 char buf[128]; 823 824 if (UsePerfData) { 825 ClassLoader::unsafe_defineClassCallCounter()->inc(); 826 } 827 828 if (data == NULL) { 829 throw_new(env, "NullPointerException"); 830 return 0; 831 } 832 833 /* Work around 4153825. malloc crashes on Solaris when passed a 834 * negative size. 835 */ 836 if (length < 0) { 837 throw_new(env, "ArrayIndexOutOfBoundsException"); 838 return 0; 839 } 840 841 body = NEW_C_HEAP_ARRAY(jbyte, length, mtInternal); 842 843 if (body == 0) { 844 throw_new(env, "OutOfMemoryError"); 845 return 0; 846 } 847 848 env->GetByteArrayRegion(data, offset, length, body); 849 850 if (env->ExceptionOccurred()) 851 goto free_body; 852 853 if (name != NULL) { 854 uint len = env->GetStringUTFLength(name); 855 int unicode_len = env->GetStringLength(name); 856 if (len >= sizeof(buf)) { 857 utfName = NEW_C_HEAP_ARRAY(char, len + 1, mtInternal); 858 if (utfName == NULL) { 859 throw_new(env, "OutOfMemoryError"); 860 goto free_body; 861 } 862 } else { 863 utfName = buf; 864 } 865 env->GetStringUTFRegion(name, 0, unicode_len, utfName); 866 //VerifyFixClassname(utfName); 867 for (uint i = 0; i < len; i++) { 868 if (utfName[i] == '.') utfName[i] = '/'; 869 } 870 } else { 871 utfName = NULL; 872 } 873 874 result = JVM_DefineClass(env, utfName, loader, body, length, pd); 875 876 if (utfName && utfName != buf) 877 FREE_C_HEAP_ARRAY(char, utfName); 878 879 free_body: 880 FREE_C_HEAP_ARRAY(jbyte, body); 881 return result; 882 } 883 } 884 885 886 UNSAFE_ENTRY(jclass, Unsafe_DefineClass(JNIEnv *env, jobject unsafe, jstring name, jbyteArray data, int offset, int length, jobject loader, jobject pd)) 887 UnsafeWrapper("Unsafe_DefineClass"); 888 { 889 ThreadToNativeFromVM ttnfv(thread); 890 return Unsafe_DefineClass_impl(env, name, data, offset, length, loader, pd); 891 } 892 UNSAFE_END 893 894 895 // define a class but do not make it known to the class loader or system dictionary 896 // - host_class: supplies context for linkage, access control, protection domain, and class loader 897 // - data: bytes of a class file, a raw memory address (length gives the number of bytes) 898 // - cp_patches: where non-null entries exist, they replace corresponding CP entries in data 899 900 // When you load an anonymous class U, it works as if you changed its name just before loading, 901 // to a name that you will never use again. Since the name is lost, no other class can directly 902 // link to any member of U. Just after U is loaded, the only way to use it is reflectively, 903 // through java.lang.Class methods like Class.newInstance. 904 905 // Access checks for linkage sites within U continue to follow the same rules as for named classes. 906 // The package of an anonymous class is given by the package qualifier on the name under which it was loaded. 907 // An anonymous class also has special privileges to access any member of its host class. 908 // This is the main reason why this loading operation is unsafe. The purpose of this is to 909 // allow language implementations to simulate "open classes"; a host class in effect gets 910 // new code when an anonymous class is loaded alongside it. A less convenient but more 911 // standard way to do this is with reflection, which can also be set to ignore access 912 // restrictions. 913 914 // Access into an anonymous class is possible only through reflection. Therefore, there 915 // are no special access rules for calling into an anonymous class. The relaxed access 916 // rule for the host class is applied in the opposite direction: A host class reflectively 917 // access one of its anonymous classes. 918 919 // If you load the same bytecodes twice, you get two different classes. You can reload 920 // the same bytecodes with or without varying CP patches. 921 922 // By using the CP patching array, you can have a new anonymous class U2 refer to an older one U1. 923 // The bytecodes for U2 should refer to U1 by a symbolic name (doesn't matter what the name is). 924 // The CONSTANT_Class entry for that name can be patched to refer directly to U1. 925 926 // This allows, for example, U2 to use U1 as a superclass or super-interface, or as 927 // an outer class (so that U2 is an anonymous inner class of anonymous U1). 928 // It is not possible for a named class, or an older anonymous class, to refer by 929 // name (via its CP) to a newer anonymous class. 930 931 // CP patching may also be used to modify (i.e., hack) the names of methods, classes, 932 // or type descriptors used in the loaded anonymous class. 933 934 // Finally, CP patching may be used to introduce "live" objects into the constant pool, 935 // instead of "dead" strings. A compiled statement like println((Object)"hello") can 936 // be changed to println(greeting), where greeting is an arbitrary object created before 937 // the anonymous class is loaded. This is useful in dynamic languages, in which 938 // various kinds of metaobjects must be introduced as constants into bytecode. 939 // Note the cast (Object), which tells the verifier to expect an arbitrary object, 940 // not just a literal string. For such ldc instructions, the verifier uses the 941 // type Object instead of String, if the loaded constant is not in fact a String. 942 943 static instanceKlassHandle 944 Unsafe_DefineAnonymousClass_impl(JNIEnv *env, 945 jclass host_class, jbyteArray data, jobjectArray cp_patches_jh, 946 HeapWord* *temp_alloc, 947 TRAPS) { 948 949 if (UsePerfData) { 950 ClassLoader::unsafe_defineClassCallCounter()->inc(); 951 } 952 953 if (data == NULL) { 954 THROW_0(vmSymbols::java_lang_NullPointerException()); 955 } 956 957 jint length = typeArrayOop(JNIHandles::resolve_non_null(data))->length(); 958 jint word_length = (length + sizeof(HeapWord)-1) / sizeof(HeapWord); 959 HeapWord* body = NEW_C_HEAP_ARRAY(HeapWord, word_length, mtInternal); 960 if (body == NULL) { 961 THROW_0(vmSymbols::java_lang_OutOfMemoryError()); 962 } 963 964 // caller responsible to free it: 965 (*temp_alloc) = body; 966 967 { 968 jbyte* array_base = typeArrayOop(JNIHandles::resolve_non_null(data))->byte_at_addr(0); 969 Copy::conjoint_words((HeapWord*) array_base, body, word_length); 970 } 971 972 u1* class_bytes = (u1*) body; 973 int class_bytes_length = (int) length; 974 if (class_bytes_length < 0) class_bytes_length = 0; 975 if (class_bytes == NULL 976 || host_class == NULL 977 || length != class_bytes_length) 978 THROW_0(vmSymbols::java_lang_IllegalArgumentException()); 979 980 objArrayHandle cp_patches_h; 981 if (cp_patches_jh != NULL) { 982 oop p = JNIHandles::resolve_non_null(cp_patches_jh); 983 if (!p->is_objArray()) 984 THROW_0(vmSymbols::java_lang_IllegalArgumentException()); 985 cp_patches_h = objArrayHandle(THREAD, (objArrayOop)p); 986 } 987 988 KlassHandle host_klass(THREAD, java_lang_Class::as_Klass(JNIHandles::resolve_non_null(host_class))); 989 const char* host_source = host_klass->external_name(); 990 Handle host_loader(THREAD, host_klass->class_loader()); 991 Handle host_domain(THREAD, host_klass->protection_domain()); 992 993 GrowableArray<Handle>* cp_patches = NULL; 994 if (cp_patches_h.not_null()) { 995 int alen = cp_patches_h->length(); 996 for (int i = alen-1; i >= 0; i--) { 997 oop p = cp_patches_h->obj_at(i); 998 if (p != NULL) { 999 Handle patch(THREAD, p); 1000 if (cp_patches == NULL) 1001 cp_patches = new GrowableArray<Handle>(i+1, i+1, Handle()); 1002 cp_patches->at_put(i, patch); 1003 } 1004 } 1005 } 1006 1007 ClassFileStream st(class_bytes, class_bytes_length, (char*) host_source); 1008 1009 instanceKlassHandle anon_klass; 1010 { 1011 Symbol* no_class_name = NULL; 1012 Klass* anonk = SystemDictionary::parse_stream(no_class_name, 1013 host_loader, host_domain, 1014 &st, host_klass, cp_patches, 1015 CHECK_NULL); 1016 if (anonk == NULL) return NULL; 1017 anon_klass = instanceKlassHandle(THREAD, anonk); 1018 } 1019 1020 return anon_klass; 1021 } 1022 1023 UNSAFE_ENTRY(jclass, Unsafe_DefineAnonymousClass(JNIEnv *env, jobject unsafe, jclass host_class, jbyteArray data, jobjectArray cp_patches_jh)) 1024 { 1025 instanceKlassHandle anon_klass; 1026 jobject res_jh = NULL; 1027 1028 UnsafeWrapper("Unsafe_DefineAnonymousClass"); 1029 ResourceMark rm(THREAD); 1030 1031 HeapWord* temp_alloc = NULL; 1032 1033 anon_klass = Unsafe_DefineAnonymousClass_impl(env, host_class, data, 1034 cp_patches_jh, 1035 &temp_alloc, THREAD); 1036 if (anon_klass() != NULL) 1037 res_jh = JNIHandles::make_local(env, anon_klass->java_mirror()); 1038 1039 // try/finally clause: 1040 if (temp_alloc != NULL) { 1041 FREE_C_HEAP_ARRAY(HeapWord, temp_alloc); 1042 } 1043 1044 // The anonymous class loader data has been artificially been kept alive to 1045 // this point. The mirror and any instances of this class have to keep 1046 // it alive afterwards. 1047 if (anon_klass() != NULL) { 1048 anon_klass->class_loader_data()->set_keep_alive(false); 1049 } 1050 1051 // let caller initialize it as needed... 1052 1053 return (jclass) res_jh; 1054 } 1055 UNSAFE_END 1056 1057 1058 1059 UNSAFE_ENTRY(void, Unsafe_ThrowException(JNIEnv *env, jobject unsafe, jthrowable thr)) 1060 UnsafeWrapper("Unsafe_ThrowException"); 1061 { 1062 ThreadToNativeFromVM ttnfv(thread); 1063 env->Throw(thr); 1064 } 1065 UNSAFE_END 1066 1067 // JSR166 ------------------------------------------------------------------ 1068 1069 UNSAFE_ENTRY(jboolean, Unsafe_CompareAndSwapObject(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject e_h, jobject x_h)) 1070 UnsafeWrapper("Unsafe_CompareAndSwapObject"); 1071 oop x = JNIHandles::resolve(x_h); 1072 oop e = JNIHandles::resolve(e_h); 1073 oop p = JNIHandles::resolve(obj); 1074 HeapWord* addr = (HeapWord *)index_oop_from_field_offset_long(p, offset); 1075 oop res = oopDesc::atomic_compare_exchange_oop(x, addr, e, true); 1076 jboolean success = (res == e); 1077 if (success) 1078 update_barrier_set((void*)addr, x); 1079 return success; 1080 UNSAFE_END 1081 1082 UNSAFE_ENTRY(jboolean, Unsafe_CompareAndSwapInt(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jint e, jint x)) 1083 UnsafeWrapper("Unsafe_CompareAndSwapInt"); 1084 oop p = JNIHandles::resolve(obj); 1085 jint* addr = (jint *) index_oop_from_field_offset_long(p, offset); 1086 return (jint)(Atomic::cmpxchg(x, addr, e)) == e; 1087 UNSAFE_END 1088 1089 UNSAFE_ENTRY(jboolean, Unsafe_CompareAndSwapLong(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jlong e, jlong x)) 1090 UnsafeWrapper("Unsafe_CompareAndSwapLong"); 1091 Handle p (THREAD, JNIHandles::resolve(obj)); 1092 jlong* addr = (jlong*)(index_oop_from_field_offset_long(p(), offset)); 1093 #ifdef SUPPORTS_NATIVE_CX8 1094 return (jlong)(Atomic::cmpxchg(x, addr, e)) == e; 1095 #else 1096 if (VM_Version::supports_cx8()) 1097 return (jlong)(Atomic::cmpxchg(x, addr, e)) == e; 1098 else { 1099 jboolean success = false; 1100 MutexLockerEx mu(UnsafeJlong_lock, Mutex::_no_safepoint_check_flag); 1101 jlong val = Atomic::load(addr); 1102 if (val == e) { Atomic::store(x, addr); success = true; } 1103 return success; 1104 } 1105 #endif 1106 UNSAFE_END 1107 1108 UNSAFE_ENTRY(void, Unsafe_Park(JNIEnv *env, jobject unsafe, jboolean isAbsolute, jlong time)) 1109 UnsafeWrapper("Unsafe_Park"); 1110 EventThreadPark event; 1111 HOTSPOT_THREAD_PARK_BEGIN((uintptr_t) thread->parker(), (int) isAbsolute, time); 1112 1113 JavaThreadParkedState jtps(thread, time != 0); 1114 thread->parker()->park(isAbsolute != 0, time); 1115 1116 HOTSPOT_THREAD_PARK_END((uintptr_t) thread->parker()); 1117 if (event.should_commit()) { 1118 oop obj = thread->current_park_blocker(); 1119 event.set_klass((obj != NULL) ? obj->klass() : NULL); 1120 event.set_timeout(time); 1121 event.set_address((obj != NULL) ? (TYPE_ADDRESS) cast_from_oop<uintptr_t>(obj) : 0); 1122 event.commit(); 1123 } 1124 UNSAFE_END 1125 1126 UNSAFE_ENTRY(void, Unsafe_Unpark(JNIEnv *env, jobject unsafe, jobject jthread)) 1127 UnsafeWrapper("Unsafe_Unpark"); 1128 Parker* p = NULL; 1129 if (jthread != NULL) { 1130 oop java_thread = JNIHandles::resolve_non_null(jthread); 1131 if (java_thread != NULL) { 1132 jlong lp = java_lang_Thread::park_event(java_thread); 1133 if (lp != 0) { 1134 // This cast is OK even though the jlong might have been read 1135 // non-atomically on 32bit systems, since there, one word will 1136 // always be zero anyway and the value set is always the same 1137 p = (Parker*)addr_from_java(lp); 1138 } else { 1139 // Grab lock if apparently null or using older version of library 1140 MutexLocker mu(Threads_lock); 1141 java_thread = JNIHandles::resolve_non_null(jthread); 1142 if (java_thread != NULL) { 1143 JavaThread* thr = java_lang_Thread::thread(java_thread); 1144 if (thr != NULL) { 1145 p = thr->parker(); 1146 if (p != NULL) { // Bind to Java thread for next time. 1147 java_lang_Thread::set_park_event(java_thread, addr_to_java(p)); 1148 } 1149 } 1150 } 1151 } 1152 } 1153 } 1154 if (p != NULL) { 1155 HOTSPOT_THREAD_UNPARK((uintptr_t) p); 1156 p->unpark(); 1157 } 1158 UNSAFE_END 1159 1160 UNSAFE_ENTRY(jint, Unsafe_Loadavg(JNIEnv *env, jobject unsafe, jdoubleArray loadavg, jint nelem)) 1161 UnsafeWrapper("Unsafe_Loadavg"); 1162 const int max_nelem = 3; 1163 double la[max_nelem]; 1164 jint ret; 1165 1166 typeArrayOop a = typeArrayOop(JNIHandles::resolve_non_null(loadavg)); 1167 assert(a->is_typeArray(), "must be type array"); 1168 1169 if (nelem < 0 || nelem > max_nelem || a->length() < nelem) { 1170 ThreadToNativeFromVM ttnfv(thread); 1171 throw_new(env, "ArrayIndexOutOfBoundsException"); 1172 return -1; 1173 } 1174 1175 ret = os::loadavg(la, nelem); 1176 if (ret == -1) return -1; 1177 1178 // if successful, ret is the number of samples actually retrieved. 1179 assert(ret >= 0 && ret <= max_nelem, "Unexpected loadavg return value"); 1180 switch(ret) { 1181 case 3: a->double_at_put(2, (jdouble)la[2]); // fall through 1182 case 2: a->double_at_put(1, (jdouble)la[1]); // fall through 1183 case 1: a->double_at_put(0, (jdouble)la[0]); break; 1184 } 1185 return ret; 1186 UNSAFE_END 1187 1188 1189 /// JVM_RegisterUnsafeMethods 1190 1191 #define ADR "J" 1192 1193 #define LANG "Ljava/lang/" 1194 1195 #define OBJ LANG"Object;" 1196 #define CLS LANG"Class;" 1197 #define FLD LANG"reflect/Field;" 1198 #define THR LANG"Throwable;" 1199 1200 #define DC_Args LANG"String;[BII" LANG"ClassLoader;" "Ljava/security/ProtectionDomain;" 1201 #define DAC_Args CLS"[B["OBJ 1202 1203 #define CC (char*) /*cast a literal from (const char*)*/ 1204 #define FN_PTR(f) CAST_FROM_FN_PTR(void*, &f) 1205 1206 #define DECLARE_GETPUTOOP(Boolean, Z) \ 1207 {CC"get"#Boolean, CC"("OBJ"J)"#Z, FN_PTR(Unsafe_Get##Boolean)}, \ 1208 {CC"put"#Boolean, CC"("OBJ"J"#Z")V", FN_PTR(Unsafe_Set##Boolean)}, \ 1209 {CC"get"#Boolean"Volatile", CC"("OBJ"J)"#Z, FN_PTR(Unsafe_Get##Boolean##Volatile)}, \ 1210 {CC"put"#Boolean"Volatile", CC"("OBJ"J"#Z")V", FN_PTR(Unsafe_Set##Boolean##Volatile)} 1211 1212 1213 #define DECLARE_GETPUTNATIVE(Byte, B) \ 1214 {CC"get"#Byte, CC"("ADR")"#B, FN_PTR(Unsafe_GetNative##Byte)}, \ 1215 {CC"put"#Byte, CC"("ADR#B")V", FN_PTR(Unsafe_SetNative##Byte)} 1216 1217 1218 1219 static JNINativeMethod methods[] = { 1220 {CC"getObject", CC"("OBJ"J)"OBJ"", FN_PTR(Unsafe_GetObject)}, 1221 {CC"putObject", CC"("OBJ"J"OBJ")V", FN_PTR(Unsafe_SetObject)}, 1222 {CC"getObjectVolatile",CC"("OBJ"J)"OBJ"", FN_PTR(Unsafe_GetObjectVolatile)}, 1223 {CC"putObjectVolatile",CC"("OBJ"J"OBJ")V", FN_PTR(Unsafe_SetObjectVolatile)}, 1224 1225 DECLARE_GETPUTOOP(Boolean, Z), 1226 DECLARE_GETPUTOOP(Byte, B), 1227 DECLARE_GETPUTOOP(Short, S), 1228 DECLARE_GETPUTOOP(Char, C), 1229 DECLARE_GETPUTOOP(Int, I), 1230 DECLARE_GETPUTOOP(Long, J), 1231 DECLARE_GETPUTOOP(Float, F), 1232 DECLARE_GETPUTOOP(Double, D), 1233 1234 DECLARE_GETPUTNATIVE(Byte, B), 1235 DECLARE_GETPUTNATIVE(Short, S), 1236 DECLARE_GETPUTNATIVE(Char, C), 1237 DECLARE_GETPUTNATIVE(Int, I), 1238 DECLARE_GETPUTNATIVE(Long, J), 1239 DECLARE_GETPUTNATIVE(Float, F), 1240 DECLARE_GETPUTNATIVE(Double, D), 1241 1242 {CC"getAddress", CC"("ADR")"ADR, FN_PTR(Unsafe_GetNativeAddress)}, 1243 {CC"putAddress", CC"("ADR""ADR")V", FN_PTR(Unsafe_SetNativeAddress)}, 1244 1245 {CC"allocateMemory", CC"(J)"ADR, FN_PTR(Unsafe_AllocateMemory)}, 1246 {CC"reallocateMemory", CC"("ADR"J)"ADR, FN_PTR(Unsafe_ReallocateMemory)}, 1247 {CC"freeMemory", CC"("ADR")V", FN_PTR(Unsafe_FreeMemory)}, 1248 1249 {CC"objectFieldOffset", CC"("FLD")J", FN_PTR(Unsafe_ObjectFieldOffset)}, 1250 {CC"staticFieldOffset", CC"("FLD")J", FN_PTR(Unsafe_StaticFieldOffset)}, 1251 {CC"staticFieldBase", CC"("FLD")"OBJ, FN_PTR(Unsafe_StaticFieldBaseFromField)}, 1252 {CC"ensureClassInitialized",CC"("CLS")V", FN_PTR(Unsafe_EnsureClassInitialized)}, 1253 {CC"arrayBaseOffset", CC"("CLS")I", FN_PTR(Unsafe_ArrayBaseOffset)}, 1254 {CC"arrayIndexScale", CC"("CLS")I", FN_PTR(Unsafe_ArrayIndexScale)}, 1255 {CC"addressSize", CC"()I", FN_PTR(Unsafe_AddressSize)}, 1256 {CC"pageSize", CC"()I", FN_PTR(Unsafe_PageSize)}, 1257 1258 {CC"defineClass", CC"("DC_Args")"CLS, FN_PTR(Unsafe_DefineClass)}, 1259 {CC"allocateInstance", CC"("CLS")"OBJ, FN_PTR(Unsafe_AllocateInstance)}, 1260 {CC"throwException", CC"("THR")V", FN_PTR(Unsafe_ThrowException)}, 1261 {CC"compareAndSwapObject", CC"("OBJ"J"OBJ""OBJ")Z", FN_PTR(Unsafe_CompareAndSwapObject)}, 1262 {CC"compareAndSwapInt", CC"("OBJ"J""I""I"")Z", FN_PTR(Unsafe_CompareAndSwapInt)}, 1263 {CC"compareAndSwapLong", CC"("OBJ"J""J""J"")Z", FN_PTR(Unsafe_CompareAndSwapLong)}, 1264 {CC"putOrderedObject", CC"("OBJ"J"OBJ")V", FN_PTR(Unsafe_SetOrderedObject)}, 1265 {CC"putOrderedInt", CC"("OBJ"JI)V", FN_PTR(Unsafe_SetOrderedInt)}, 1266 {CC"putOrderedLong", CC"("OBJ"JJ)V", FN_PTR(Unsafe_SetOrderedLong)}, 1267 {CC"park", CC"(ZJ)V", FN_PTR(Unsafe_Park)}, 1268 {CC"unpark", CC"("OBJ")V", FN_PTR(Unsafe_Unpark)}, 1269 1270 {CC"getLoadAverage", CC"([DI)I", FN_PTR(Unsafe_Loadavg)}, 1271 1272 {CC"copyMemory", CC"("OBJ"J"OBJ"JJ)V", FN_PTR(Unsafe_CopyMemory)}, 1273 {CC"setMemory", CC"("OBJ"JJB)V", FN_PTR(Unsafe_SetMemory)}, 1274 1275 {CC"defineAnonymousClass", CC"("DAC_Args")"CLS, FN_PTR(Unsafe_DefineAnonymousClass)}, 1276 1277 {CC"shouldBeInitialized",CC"("CLS")Z", FN_PTR(Unsafe_ShouldBeInitialized)}, 1278 1279 {CC"loadFence", CC"()V", FN_PTR(Unsafe_LoadFence)}, 1280 {CC"storeFence", CC"()V", FN_PTR(Unsafe_StoreFence)}, 1281 {CC"fullFence", CC"()V", FN_PTR(Unsafe_FullFence)}, 1282 1283 {CC"isBigEndian0", CC"()Z", FN_PTR(Unsafe_isBigEndian0)}, 1284 {CC"unalignedAccess0", CC"()Z", FN_PTR(Unsafe_unalignedAccess0)} 1285 }; 1286 1287 #undef CC 1288 #undef FN_PTR 1289 1290 #undef ADR 1291 #undef LANG 1292 #undef OBJ 1293 #undef CLS 1294 #undef FLD 1295 #undef THR 1296 #undef DC_Args 1297 #undef DAC_Args 1298 1299 #undef DECLARE_GETPUTOOP 1300 #undef DECLARE_GETPUTNATIVE 1301 1302 1303 // This one function is exported, used by NativeLookup. 1304 // The Unsafe_xxx functions above are called only from the interpreter. 1305 // The optimizer looks at names and signatures to recognize 1306 // individual functions. 1307 1308 JVM_ENTRY(void, JVM_RegisterUnsafeMethods(JNIEnv *env, jclass unsafeclass)) 1309 UnsafeWrapper("JVM_RegisterUnsafeMethods"); 1310 { 1311 ThreadToNativeFromVM ttnfv(thread); 1312 1313 int ok = env->RegisterNatives(unsafeclass, methods, sizeof(methods)/sizeof(JNINativeMethod)); 1314 guarantee(ok == 0, "register unsafe natives"); 1315 } 1316 JVM_END