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