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