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