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