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