1 /* 2 * Copyright (c) 1997, 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 "jvm.h" 27 #include "classfile/classLoader.hpp" 28 #include "classfile/javaClasses.hpp" 29 #include "classfile/moduleEntry.hpp" 30 #include "classfile/systemDictionary.hpp" 31 #include "classfile/vmSymbols.hpp" 32 #include "code/codeCache.hpp" 33 #include "code/scopeDesc.hpp" 34 #include "compiler/compileBroker.hpp" 35 #include "compiler/compileTask.hpp" 36 #include "gc/shared/barrierSet.hpp" 37 #include "gc/shared/gcId.hpp" 38 #include "gc/shared/gcLocker.inline.hpp" 39 #include "gc/shared/workgroup.hpp" 40 #include "interpreter/interpreter.hpp" 41 #include "interpreter/linkResolver.hpp" 42 #include "interpreter/oopMapCache.hpp" 43 #include "jfr/jfrEvents.hpp" 44 #include "jfr/support/jfrThreadId.hpp" 45 #include "jvmtifiles/jvmtiEnv.hpp" 46 #include "logging/log.hpp" 47 #include "logging/logConfiguration.hpp" 48 #include "logging/logStream.hpp" 49 #include "memory/allocation.inline.hpp" 50 #include "memory/metaspaceShared.hpp" 51 #include "memory/oopFactory.hpp" 52 #include "memory/resourceArea.hpp" 53 #include "memory/universe.hpp" 54 #include "oops/access.inline.hpp" 55 #include "oops/instanceKlass.hpp" 56 #include "oops/objArrayOop.hpp" 57 #include "oops/oop.inline.hpp" 58 #include "oops/symbol.hpp" 59 #include "oops/typeArrayOop.inline.hpp" 60 #include "oops/verifyOopClosure.hpp" 61 #include "prims/jvm_misc.hpp" 62 #include "prims/jvmtiExport.hpp" 63 #include "prims/jvmtiThreadState.hpp" 64 #include "prims/privilegedStack.hpp" 65 #include "runtime/arguments.hpp" 66 #include "runtime/atomic.hpp" 67 #include "runtime/biasedLocking.hpp" 68 #include "runtime/fieldDescriptor.inline.hpp" 69 #include "runtime/flags/jvmFlagConstraintList.hpp" 70 #include "runtime/flags/jvmFlagRangeList.hpp" 71 #include "runtime/flags/jvmFlagWriteableList.hpp" 72 #include "runtime/deoptimization.hpp" 73 #include "runtime/frame.inline.hpp" 74 #include "runtime/handshake.hpp" 75 #include "runtime/init.hpp" 76 #include "runtime/interfaceSupport.inline.hpp" 77 #include "runtime/java.hpp" 78 #include "runtime/javaCalls.hpp" 79 #include "runtime/jniHandles.inline.hpp" 80 #include "runtime/jniPeriodicChecker.hpp" 81 #include "runtime/memprofiler.hpp" 82 #include "runtime/mutexLocker.hpp" 83 #include "runtime/objectMonitor.hpp" 84 #include "runtime/orderAccess.hpp" 85 #include "runtime/osThread.hpp" 86 #include "runtime/prefetch.inline.hpp" 87 #include "runtime/safepoint.hpp" 88 #include "runtime/safepointMechanism.inline.hpp" 89 #include "runtime/safepointVerifiers.hpp" 90 #include "runtime/sharedRuntime.hpp" 91 #include "runtime/statSampler.hpp" 92 #include "runtime/stubRoutines.hpp" 93 #include "runtime/sweeper.hpp" 94 #include "runtime/task.hpp" 95 #include "runtime/thread.inline.hpp" 96 #include "runtime/threadCritical.hpp" 97 #include "runtime/threadSMR.inline.hpp" 98 #include "runtime/threadStatisticalInfo.hpp" 99 #include "runtime/timer.hpp" 100 #include "runtime/timerTrace.hpp" 101 #include "runtime/vframe.inline.hpp" 102 #include "runtime/vframeArray.hpp" 103 #include "runtime/vframe_hp.hpp" 104 #include "runtime/vmThread.hpp" 105 #include "runtime/vm_operations.hpp" 106 #include "runtime/vm_version.hpp" 107 #include "services/attachListener.hpp" 108 #include "services/management.hpp" 109 #include "services/memTracker.hpp" 110 #include "services/threadService.hpp" 111 #include "utilities/align.hpp" 112 #include "utilities/copy.hpp" 113 #include "utilities/defaultStream.hpp" 114 #include "utilities/dtrace.hpp" 115 #include "utilities/events.hpp" 116 #include "utilities/macros.hpp" 117 #include "utilities/preserveException.hpp" 118 #include "utilities/singleWriterSynchronizer.hpp" 119 #include "utilities/vmError.hpp" 120 #if INCLUDE_JVMCI 121 #include "jvmci/jvmciCompiler.hpp" 122 #include "jvmci/jvmciRuntime.hpp" 123 #include "logging/logHandle.hpp" 124 #endif 125 #ifdef COMPILER1 126 #include "c1/c1_Compiler.hpp" 127 #endif 128 #ifdef COMPILER2 129 #include "opto/c2compiler.hpp" 130 #include "opto/idealGraphPrinter.hpp" 131 #endif 132 #if INCLUDE_RTM_OPT 133 #include "runtime/rtmLocking.hpp" 134 #endif 135 #if INCLUDE_JFR 136 #include "jfr/jfr.hpp" 137 #endif 138 139 // Initialization after module runtime initialization 140 void universe_post_module_init(); // must happen after call_initPhase2 141 142 #ifdef DTRACE_ENABLED 143 144 // Only bother with this argument setup if dtrace is available 145 146 #define HOTSPOT_THREAD_PROBE_start HOTSPOT_THREAD_START 147 #define HOTSPOT_THREAD_PROBE_stop HOTSPOT_THREAD_STOP 148 149 #define DTRACE_THREAD_PROBE(probe, javathread) \ 150 { \ 151 ResourceMark rm(this); \ 152 int len = 0; \ 153 const char* name = (javathread)->get_thread_name(); \ 154 len = strlen(name); \ 155 HOTSPOT_THREAD_PROBE_##probe(/* probe = start, stop */ \ 156 (char *) name, len, \ 157 java_lang_Thread::thread_id((javathread)->threadObj()), \ 158 (uintptr_t) (javathread)->osthread()->thread_id(), \ 159 java_lang_Thread::is_daemon((javathread)->threadObj())); \ 160 } 161 162 #else // ndef DTRACE_ENABLED 163 164 #define DTRACE_THREAD_PROBE(probe, javathread) 165 166 #endif // ndef DTRACE_ENABLED 167 168 #ifndef USE_LIBRARY_BASED_TLS_ONLY 169 // Current thread is maintained as a thread-local variable 170 THREAD_LOCAL_DECL Thread* Thread::_thr_current = NULL; 171 #endif 172 173 // ======= Thread ======== 174 // Support for forcing alignment of thread objects for biased locking 175 void* Thread::allocate(size_t size, bool throw_excpt, MEMFLAGS flags) { 176 if (UseBiasedLocking) { 177 const int alignment = markOopDesc::biased_lock_alignment; 178 size_t aligned_size = size + (alignment - sizeof(intptr_t)); 179 void* real_malloc_addr = throw_excpt? AllocateHeap(aligned_size, flags, CURRENT_PC) 180 : AllocateHeap(aligned_size, flags, CURRENT_PC, 181 AllocFailStrategy::RETURN_NULL); 182 void* aligned_addr = align_up(real_malloc_addr, alignment); 183 assert(((uintptr_t) aligned_addr + (uintptr_t) size) <= 184 ((uintptr_t) real_malloc_addr + (uintptr_t) aligned_size), 185 "JavaThread alignment code overflowed allocated storage"); 186 if (aligned_addr != real_malloc_addr) { 187 log_info(biasedlocking)("Aligned thread " INTPTR_FORMAT " to " INTPTR_FORMAT, 188 p2i(real_malloc_addr), 189 p2i(aligned_addr)); 190 } 191 ((Thread*) aligned_addr)->_real_malloc_address = real_malloc_addr; 192 return aligned_addr; 193 } else { 194 return throw_excpt? AllocateHeap(size, flags, CURRENT_PC) 195 : AllocateHeap(size, flags, CURRENT_PC, AllocFailStrategy::RETURN_NULL); 196 } 197 } 198 199 void Thread::operator delete(void* p) { 200 if (UseBiasedLocking) { 201 FreeHeap(((Thread*) p)->_real_malloc_address); 202 } else { 203 FreeHeap(p); 204 } 205 } 206 207 void JavaThread::smr_delete() { 208 if (_on_thread_list) { 209 ThreadsSMRSupport::smr_delete(this); 210 } else { 211 delete this; 212 } 213 } 214 215 // Base class for all threads: VMThread, WatcherThread, ConcurrentMarkSweepThread, 216 // JavaThread 217 218 219 Thread::Thread() { 220 // stack and get_thread 221 set_stack_base(NULL); 222 set_stack_size(0); 223 set_self_raw_id(0); 224 set_lgrp_id(-1); 225 DEBUG_ONLY(clear_suspendible_thread();) 226 227 // allocated data structures 228 set_osthread(NULL); 229 set_resource_area(new (mtThread)ResourceArea()); 230 DEBUG_ONLY(_current_resource_mark = NULL;) 231 set_handle_area(new (mtThread) HandleArea(NULL)); 232 set_metadata_handles(new (ResourceObj::C_HEAP, mtClass) GrowableArray<Metadata*>(30, true)); 233 set_active_handles(NULL); 234 set_free_handle_block(NULL); 235 set_last_handle_mark(NULL); 236 237 // This initial value ==> never claimed. 238 _oops_do_parity = 0; 239 _threads_hazard_ptr = NULL; 240 _threads_list_ptr = NULL; 241 _nested_threads_hazard_ptr_cnt = 0; 242 _rcu_counter = 0; 243 244 // the handle mark links itself to last_handle_mark 245 new HandleMark(this); 246 247 // plain initialization 248 debug_only(_owned_locks = NULL;) 249 debug_only(_allow_allocation_count = 0;) 250 NOT_PRODUCT(_allow_safepoint_count = 0;) 251 NOT_PRODUCT(_skip_gcalot = false;) 252 _jvmti_env_iteration_count = 0; 253 set_allocated_bytes(0); 254 _vm_operation_started_count = 0; 255 _vm_operation_completed_count = 0; 256 _current_pending_monitor = NULL; 257 _current_pending_monitor_is_from_java = true; 258 _current_waiting_monitor = NULL; 259 _num_nested_signal = 0; 260 omFreeList = NULL; 261 omFreeCount = 0; 262 omFreeProvision = 32; 263 omInUseList = NULL; 264 omInUseCount = 0; 265 266 #ifdef ASSERT 267 _visited_for_critical_count = false; 268 #endif 269 270 _SR_lock = new Monitor(Mutex::suspend_resume, "SR_lock", true, 271 Monitor::_safepoint_check_sometimes); 272 _suspend_flags = 0; 273 274 // thread-specific hashCode stream generator state - Marsaglia shift-xor form 275 _hashStateX = os::random(); 276 _hashStateY = 842502087; 277 _hashStateZ = 0x8767; // (int)(3579807591LL & 0xffff) ; 278 _hashStateW = 273326509; 279 280 _OnTrap = 0; 281 _Stalled = 0; 282 _TypeTag = 0x2BAD; 283 284 // Many of the following fields are effectively final - immutable 285 // Note that nascent threads can't use the Native Monitor-Mutex 286 // construct until the _MutexEvent is initialized ... 287 // CONSIDER: instead of using a fixed set of purpose-dedicated ParkEvents 288 // we might instead use a stack of ParkEvents that we could provision on-demand. 289 // The stack would act as a cache to avoid calls to ParkEvent::Allocate() 290 // and ::Release() 291 _ParkEvent = ParkEvent::Allocate(this); 292 _SleepEvent = ParkEvent::Allocate(this); 293 _MutexEvent = ParkEvent::Allocate(this); 294 _MuxEvent = ParkEvent::Allocate(this); 295 296 #ifdef CHECK_UNHANDLED_OOPS 297 if (CheckUnhandledOops) { 298 _unhandled_oops = new UnhandledOops(this); 299 } 300 #endif // CHECK_UNHANDLED_OOPS 301 #ifdef ASSERT 302 if (UseBiasedLocking) { 303 assert((((uintptr_t) this) & (markOopDesc::biased_lock_alignment - 1)) == 0, "forced alignment of thread object failed"); 304 assert(this == _real_malloc_address || 305 this == align_up(_real_malloc_address, (int)markOopDesc::biased_lock_alignment), 306 "bug in forced alignment of thread objects"); 307 } 308 #endif // ASSERT 309 310 // Notify the barrier set that a thread is being created. Note that some 311 // threads are created before a barrier set is available. The call to 312 // BarrierSet::on_thread_create() for these threads is therefore deferred 313 // to BarrierSet::set_barrier_set(). 314 BarrierSet* const barrier_set = BarrierSet::barrier_set(); 315 if (barrier_set != NULL) { 316 barrier_set->on_thread_create(this); 317 } else { 318 DEBUG_ONLY(Threads::inc_threads_before_barrier_set();) 319 } 320 } 321 322 void Thread::initialize_thread_current() { 323 #ifndef USE_LIBRARY_BASED_TLS_ONLY 324 assert(_thr_current == NULL, "Thread::current already initialized"); 325 _thr_current = this; 326 #endif 327 assert(ThreadLocalStorage::thread() == NULL, "ThreadLocalStorage::thread already initialized"); 328 ThreadLocalStorage::set_thread(this); 329 assert(Thread::current() == ThreadLocalStorage::thread(), "TLS mismatch!"); 330 } 331 332 void Thread::clear_thread_current() { 333 assert(Thread::current() == ThreadLocalStorage::thread(), "TLS mismatch!"); 334 #ifndef USE_LIBRARY_BASED_TLS_ONLY 335 _thr_current = NULL; 336 #endif 337 ThreadLocalStorage::set_thread(NULL); 338 } 339 340 void Thread::record_stack_base_and_size() { 341 // Note: at this point, Thread object is not yet initialized. Do not rely on 342 // any members being initialized. Do not rely on Thread::current() being set. 343 // If possible, refrain from doing anything which may crash or assert since 344 // quite probably those crash dumps will be useless. 345 set_stack_base(os::current_stack_base()); 346 set_stack_size(os::current_stack_size()); 347 348 #ifdef SOLARIS 349 if (os::is_primordial_thread()) { 350 os::Solaris::correct_stack_boundaries_for_primordial_thread(this); 351 } 352 #endif 353 354 // Set stack limits after thread is initialized. 355 if (is_Java_thread()) { 356 ((JavaThread*) this)->set_stack_overflow_limit(); 357 ((JavaThread*) this)->set_reserved_stack_activation(stack_base()); 358 } 359 } 360 361 #if INCLUDE_NMT 362 void Thread::register_thread_stack_with_NMT() { 363 MemTracker::record_thread_stack(stack_end(), stack_size()); 364 } 365 #endif // INCLUDE_NMT 366 367 void Thread::call_run() { 368 // At this point, Thread object should be fully initialized and 369 // Thread::current() should be set. 370 371 register_thread_stack_with_NMT(); 372 373 log_debug(os, thread)("Thread " UINTX_FORMAT " stack dimensions: " 374 PTR_FORMAT "-" PTR_FORMAT " (" SIZE_FORMAT "k).", 375 os::current_thread_id(), p2i(stack_base() - stack_size()), 376 p2i(stack_base()), stack_size()/1024); 377 378 // Invoke <ChildClass>::run() 379 this->run(); 380 // Returned from <ChildClass>::run(). Thread finished. 381 382 // Note: at this point the thread object may already have deleted itself. 383 // So from here on do not dereference *this*. 384 385 // If a thread has not deleted itself ("delete this") as part of its 386 // termination sequence, we have to ensure thread-local-storage is 387 // cleared before we actually terminate. No threads should ever be 388 // deleted asynchronously with respect to their termination. 389 if (Thread::current_or_null_safe() != NULL) { 390 assert(Thread::current_or_null_safe() == this, "current thread is wrong"); 391 Thread::clear_thread_current(); 392 } 393 394 } 395 396 Thread::~Thread() { 397 JFR_ONLY(Jfr::on_thread_destruct(this);) 398 399 // Notify the barrier set that a thread is being destroyed. Note that a barrier 400 // set might not be available if we encountered errors during bootstrapping. 401 BarrierSet* const barrier_set = BarrierSet::barrier_set(); 402 if (barrier_set != NULL) { 403 barrier_set->on_thread_destroy(this); 404 } 405 406 407 // stack_base can be NULL if the thread is never started or exited before 408 // record_stack_base_and_size called. Although, we would like to ensure 409 // that all started threads do call record_stack_base_and_size(), there is 410 // not proper way to enforce that. 411 #if INCLUDE_NMT 412 if (_stack_base != NULL) { 413 MemTracker::release_thread_stack(stack_end(), stack_size()); 414 #ifdef ASSERT 415 set_stack_base(NULL); 416 #endif 417 } 418 #endif // INCLUDE_NMT 419 420 // deallocate data structures 421 delete resource_area(); 422 // since the handle marks are using the handle area, we have to deallocated the root 423 // handle mark before deallocating the thread's handle area, 424 assert(last_handle_mark() != NULL, "check we have an element"); 425 delete last_handle_mark(); 426 assert(last_handle_mark() == NULL, "check we have reached the end"); 427 428 // It's possible we can encounter a null _ParkEvent, etc., in stillborn threads. 429 // We NULL out the fields for good hygiene. 430 ParkEvent::Release(_ParkEvent); _ParkEvent = NULL; 431 ParkEvent::Release(_SleepEvent); _SleepEvent = NULL; 432 ParkEvent::Release(_MutexEvent); _MutexEvent = NULL; 433 ParkEvent::Release(_MuxEvent); _MuxEvent = NULL; 434 435 delete handle_area(); 436 delete metadata_handles(); 437 438 // SR_handler uses this as a termination indicator - 439 // needs to happen before os::free_thread() 440 delete _SR_lock; 441 _SR_lock = NULL; 442 443 // osthread() can be NULL, if creation of thread failed. 444 if (osthread() != NULL) os::free_thread(osthread()); 445 446 // clear Thread::current if thread is deleting itself. 447 // Needed to ensure JNI correctly detects non-attached threads. 448 if (this == Thread::current()) { 449 Thread::clear_thread_current(); 450 } 451 452 CHECK_UNHANDLED_OOPS_ONLY(if (CheckUnhandledOops) delete unhandled_oops();) 453 } 454 455 #ifdef ASSERT 456 // A JavaThread is considered "dangling" if it is not the current 457 // thread, has been added the Threads list, the system is not at a 458 // safepoint and the Thread is not "protected". 459 // 460 void Thread::check_for_dangling_thread_pointer(Thread *thread) { 461 assert(!thread->is_Java_thread() || Thread::current() == thread || 462 !((JavaThread *) thread)->on_thread_list() || 463 SafepointSynchronize::is_at_safepoint() || 464 ThreadsSMRSupport::is_a_protected_JavaThread_with_lock((JavaThread *) thread), 465 "possibility of dangling Thread pointer"); 466 } 467 #endif 468 469 ThreadPriority Thread::get_priority(const Thread* const thread) { 470 ThreadPriority priority; 471 // Can return an error! 472 (void)os::get_priority(thread, priority); 473 assert(MinPriority <= priority && priority <= MaxPriority, "non-Java priority found"); 474 return priority; 475 } 476 477 void Thread::set_priority(Thread* thread, ThreadPriority priority) { 478 debug_only(check_for_dangling_thread_pointer(thread);) 479 // Can return an error! 480 (void)os::set_priority(thread, priority); 481 } 482 483 484 void Thread::start(Thread* thread) { 485 // Start is different from resume in that its safety is guaranteed by context or 486 // being called from a Java method synchronized on the Thread object. 487 if (!DisableStartThread) { 488 if (thread->is_Java_thread()) { 489 // Initialize the thread state to RUNNABLE before starting this thread. 490 // Can not set it after the thread started because we do not know the 491 // exact thread state at that time. It could be in MONITOR_WAIT or 492 // in SLEEPING or some other state. 493 java_lang_Thread::set_thread_status(((JavaThread*)thread)->threadObj(), 494 java_lang_Thread::RUNNABLE); 495 } 496 os::start_thread(thread); 497 } 498 } 499 500 // Enqueue a VM_Operation to do the job for us - sometime later 501 void Thread::send_async_exception(oop java_thread, oop java_throwable) { 502 VM_ThreadStop* vm_stop = new VM_ThreadStop(java_thread, java_throwable); 503 VMThread::execute(vm_stop); 504 } 505 506 507 // Check if an external suspend request has completed (or has been 508 // cancelled). Returns true if the thread is externally suspended and 509 // false otherwise. 510 // 511 // The bits parameter returns information about the code path through 512 // the routine. Useful for debugging: 513 // 514 // set in is_ext_suspend_completed(): 515 // 0x00000001 - routine was entered 516 // 0x00000010 - routine return false at end 517 // 0x00000100 - thread exited (return false) 518 // 0x00000200 - suspend request cancelled (return false) 519 // 0x00000400 - thread suspended (return true) 520 // 0x00001000 - thread is in a suspend equivalent state (return true) 521 // 0x00002000 - thread is native and walkable (return true) 522 // 0x00004000 - thread is native_trans and walkable (needed retry) 523 // 524 // set in wait_for_ext_suspend_completion(): 525 // 0x00010000 - routine was entered 526 // 0x00020000 - suspend request cancelled before loop (return false) 527 // 0x00040000 - thread suspended before loop (return true) 528 // 0x00080000 - suspend request cancelled in loop (return false) 529 // 0x00100000 - thread suspended in loop (return true) 530 // 0x00200000 - suspend not completed during retry loop (return false) 531 532 // Helper class for tracing suspend wait debug bits. 533 // 534 // 0x00000100 indicates that the target thread exited before it could 535 // self-suspend which is not a wait failure. 0x00000200, 0x00020000 and 536 // 0x00080000 each indicate a cancelled suspend request so they don't 537 // count as wait failures either. 538 #define DEBUG_FALSE_BITS (0x00000010 | 0x00200000) 539 540 class TraceSuspendDebugBits : public StackObj { 541 private: 542 JavaThread * jt; 543 bool is_wait; 544 bool called_by_wait; // meaningful when !is_wait 545 uint32_t * bits; 546 547 public: 548 TraceSuspendDebugBits(JavaThread *_jt, bool _is_wait, bool _called_by_wait, 549 uint32_t *_bits) { 550 jt = _jt; 551 is_wait = _is_wait; 552 called_by_wait = _called_by_wait; 553 bits = _bits; 554 } 555 556 ~TraceSuspendDebugBits() { 557 if (!is_wait) { 558 #if 1 559 // By default, don't trace bits for is_ext_suspend_completed() calls. 560 // That trace is very chatty. 561 return; 562 #else 563 if (!called_by_wait) { 564 // If tracing for is_ext_suspend_completed() is enabled, then only 565 // trace calls to it from wait_for_ext_suspend_completion() 566 return; 567 } 568 #endif 569 } 570 571 if (AssertOnSuspendWaitFailure || TraceSuspendWaitFailures) { 572 if (bits != NULL && (*bits & DEBUG_FALSE_BITS) != 0) { 573 MutexLocker ml(Threads_lock); // needed for get_thread_name() 574 ResourceMark rm; 575 576 tty->print_cr( 577 "Failed wait_for_ext_suspend_completion(thread=%s, debug_bits=%x)", 578 jt->get_thread_name(), *bits); 579 580 guarantee(!AssertOnSuspendWaitFailure, "external suspend wait failed"); 581 } 582 } 583 } 584 }; 585 #undef DEBUG_FALSE_BITS 586 587 588 bool JavaThread::is_ext_suspend_completed(bool called_by_wait, int delay, 589 uint32_t *bits) { 590 TraceSuspendDebugBits tsdb(this, false /* !is_wait */, called_by_wait, bits); 591 592 bool did_trans_retry = false; // only do thread_in_native_trans retry once 593 bool do_trans_retry; // flag to force the retry 594 595 *bits |= 0x00000001; 596 597 do { 598 do_trans_retry = false; 599 600 if (is_exiting()) { 601 // Thread is in the process of exiting. This is always checked 602 // first to reduce the risk of dereferencing a freed JavaThread. 603 *bits |= 0x00000100; 604 return false; 605 } 606 607 if (!is_external_suspend()) { 608 // Suspend request is cancelled. This is always checked before 609 // is_ext_suspended() to reduce the risk of a rogue resume 610 // confusing the thread that made the suspend request. 611 *bits |= 0x00000200; 612 return false; 613 } 614 615 if (is_ext_suspended()) { 616 // thread is suspended 617 *bits |= 0x00000400; 618 return true; 619 } 620 621 // Now that we no longer do hard suspends of threads running 622 // native code, the target thread can be changing thread state 623 // while we are in this routine: 624 // 625 // _thread_in_native -> _thread_in_native_trans -> _thread_blocked 626 // 627 // We save a copy of the thread state as observed at this moment 628 // and make our decision about suspend completeness based on the 629 // copy. This closes the race where the thread state is seen as 630 // _thread_in_native_trans in the if-thread_blocked check, but is 631 // seen as _thread_blocked in if-thread_in_native_trans check. 632 JavaThreadState save_state = thread_state(); 633 634 if (save_state == _thread_blocked && is_suspend_equivalent()) { 635 // If the thread's state is _thread_blocked and this blocking 636 // condition is known to be equivalent to a suspend, then we can 637 // consider the thread to be externally suspended. This means that 638 // the code that sets _thread_blocked has been modified to do 639 // self-suspension if the blocking condition releases. We also 640 // used to check for CONDVAR_WAIT here, but that is now covered by 641 // the _thread_blocked with self-suspension check. 642 // 643 // Return true since we wouldn't be here unless there was still an 644 // external suspend request. 645 *bits |= 0x00001000; 646 return true; 647 } else if (save_state == _thread_in_native && frame_anchor()->walkable()) { 648 // Threads running native code will self-suspend on native==>VM/Java 649 // transitions. If its stack is walkable (should always be the case 650 // unless this function is called before the actual java_suspend() 651 // call), then the wait is done. 652 *bits |= 0x00002000; 653 return true; 654 } else if (!called_by_wait && !did_trans_retry && 655 save_state == _thread_in_native_trans && 656 frame_anchor()->walkable()) { 657 // The thread is transitioning from thread_in_native to another 658 // thread state. check_safepoint_and_suspend_for_native_trans() 659 // will force the thread to self-suspend. If it hasn't gotten 660 // there yet we may have caught the thread in-between the native 661 // code check above and the self-suspend. Lucky us. If we were 662 // called by wait_for_ext_suspend_completion(), then it 663 // will be doing the retries so we don't have to. 664 // 665 // Since we use the saved thread state in the if-statement above, 666 // there is a chance that the thread has already transitioned to 667 // _thread_blocked by the time we get here. In that case, we will 668 // make a single unnecessary pass through the logic below. This 669 // doesn't hurt anything since we still do the trans retry. 670 671 *bits |= 0x00004000; 672 673 // Once the thread leaves thread_in_native_trans for another 674 // thread state, we break out of this retry loop. We shouldn't 675 // need this flag to prevent us from getting back here, but 676 // sometimes paranoia is good. 677 did_trans_retry = true; 678 679 // We wait for the thread to transition to a more usable state. 680 for (int i = 1; i <= SuspendRetryCount; i++) { 681 // We used to do an "os::yield_all(i)" call here with the intention 682 // that yielding would increase on each retry. However, the parameter 683 // is ignored on Linux which means the yield didn't scale up. Waiting 684 // on the SR_lock below provides a much more predictable scale up for 685 // the delay. It also provides a simple/direct point to check for any 686 // safepoint requests from the VMThread 687 688 // temporarily drops SR_lock while doing wait with safepoint check 689 // (if we're a JavaThread - the WatcherThread can also call this) 690 // and increase delay with each retry 691 SR_lock()->wait(!Thread::current()->is_Java_thread(), i * delay); 692 693 // check the actual thread state instead of what we saved above 694 if (thread_state() != _thread_in_native_trans) { 695 // the thread has transitioned to another thread state so 696 // try all the checks (except this one) one more time. 697 do_trans_retry = true; 698 break; 699 } 700 } // end retry loop 701 702 703 } 704 } while (do_trans_retry); 705 706 *bits |= 0x00000010; 707 return false; 708 } 709 710 // Wait for an external suspend request to complete (or be cancelled). 711 // Returns true if the thread is externally suspended and false otherwise. 712 // 713 bool JavaThread::wait_for_ext_suspend_completion(int retries, int delay, 714 uint32_t *bits) { 715 TraceSuspendDebugBits tsdb(this, true /* is_wait */, 716 false /* !called_by_wait */, bits); 717 718 // local flag copies to minimize SR_lock hold time 719 bool is_suspended; 720 bool pending; 721 uint32_t reset_bits; 722 723 // set a marker so is_ext_suspend_completed() knows we are the caller 724 *bits |= 0x00010000; 725 726 // We use reset_bits to reinitialize the bits value at the top of 727 // each retry loop. This allows the caller to make use of any 728 // unused bits for their own marking purposes. 729 reset_bits = *bits; 730 731 { 732 MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag); 733 is_suspended = is_ext_suspend_completed(true /* called_by_wait */, 734 delay, bits); 735 pending = is_external_suspend(); 736 } 737 // must release SR_lock to allow suspension to complete 738 739 if (!pending) { 740 // A cancelled suspend request is the only false return from 741 // is_ext_suspend_completed() that keeps us from entering the 742 // retry loop. 743 *bits |= 0x00020000; 744 return false; 745 } 746 747 if (is_suspended) { 748 *bits |= 0x00040000; 749 return true; 750 } 751 752 for (int i = 1; i <= retries; i++) { 753 *bits = reset_bits; // reinit to only track last retry 754 755 // We used to do an "os::yield_all(i)" call here with the intention 756 // that yielding would increase on each retry. However, the parameter 757 // is ignored on Linux which means the yield didn't scale up. Waiting 758 // on the SR_lock below provides a much more predictable scale up for 759 // the delay. It also provides a simple/direct point to check for any 760 // safepoint requests from the VMThread 761 762 { 763 MutexLocker ml(SR_lock()); 764 // wait with safepoint check (if we're a JavaThread - the WatcherThread 765 // can also call this) and increase delay with each retry 766 SR_lock()->wait(!Thread::current()->is_Java_thread(), i * delay); 767 768 is_suspended = is_ext_suspend_completed(true /* called_by_wait */, 769 delay, bits); 770 771 // It is possible for the external suspend request to be cancelled 772 // (by a resume) before the actual suspend operation is completed. 773 // Refresh our local copy to see if we still need to wait. 774 pending = is_external_suspend(); 775 } 776 777 if (!pending) { 778 // A cancelled suspend request is the only false return from 779 // is_ext_suspend_completed() that keeps us from staying in the 780 // retry loop. 781 *bits |= 0x00080000; 782 return false; 783 } 784 785 if (is_suspended) { 786 *bits |= 0x00100000; 787 return true; 788 } 789 } // end retry loop 790 791 // thread did not suspend after all our retries 792 *bits |= 0x00200000; 793 return false; 794 } 795 796 // Called from API entry points which perform stack walking. If the 797 // associated JavaThread is the current thread, then wait_for_suspend 798 // is not used. Otherwise, it determines if we should wait for the 799 // "other" thread to complete external suspension. (NOTE: in future 800 // releases the suspension mechanism should be reimplemented so this 801 // is not necessary.) 802 // 803 bool 804 JavaThread::is_thread_fully_suspended(bool wait_for_suspend, uint32_t *bits) { 805 if (this != JavaThread::current()) { 806 // "other" threads require special handling. 807 if (wait_for_suspend) { 808 // We are allowed to wait for the external suspend to complete 809 // so give the other thread a chance to get suspended. 810 if (!wait_for_ext_suspend_completion(SuspendRetryCount, 811 SuspendRetryDelay, bits)) { 812 // Didn't make it so let the caller know. 813 return false; 814 } 815 } 816 // We aren't allowed to wait for the external suspend to complete 817 // so if the other thread isn't externally suspended we need to 818 // let the caller know. 819 else if (!is_ext_suspend_completed_with_lock(bits)) { 820 return false; 821 } 822 } 823 824 return true; 825 } 826 827 #ifndef PRODUCT 828 void JavaThread::record_jump(address target, address instr, const char* file, 829 int line) { 830 831 // This should not need to be atomic as the only way for simultaneous 832 // updates is via interrupts. Even then this should be rare or non-existent 833 // and we don't care that much anyway. 834 835 int index = _jmp_ring_index; 836 _jmp_ring_index = (index + 1) & (jump_ring_buffer_size - 1); 837 _jmp_ring[index]._target = (intptr_t) target; 838 _jmp_ring[index]._instruction = (intptr_t) instr; 839 _jmp_ring[index]._file = file; 840 _jmp_ring[index]._line = line; 841 } 842 #endif // PRODUCT 843 844 void Thread::interrupt(Thread* thread) { 845 debug_only(check_for_dangling_thread_pointer(thread);) 846 os::interrupt(thread); 847 } 848 849 bool Thread::is_interrupted(Thread* thread, bool clear_interrupted) { 850 debug_only(check_for_dangling_thread_pointer(thread);) 851 // Note: If clear_interrupted==false, this simply fetches and 852 // returns the value of the field osthread()->interrupted(). 853 return os::is_interrupted(thread, clear_interrupted); 854 } 855 856 857 // GC Support 858 bool Thread::claim_oops_do_par_case(int strong_roots_parity) { 859 int thread_parity = _oops_do_parity; 860 if (thread_parity != strong_roots_parity) { 861 jint res = Atomic::cmpxchg(strong_roots_parity, &_oops_do_parity, thread_parity); 862 if (res == thread_parity) { 863 return true; 864 } else { 865 guarantee(res == strong_roots_parity, "Or else what?"); 866 return false; 867 } 868 } 869 return false; 870 } 871 872 void Thread::oops_do(OopClosure* f, CodeBlobClosure* cf) { 873 active_handles()->oops_do(f); 874 // Do oop for ThreadShadow 875 f->do_oop((oop*)&_pending_exception); 876 handle_area()->oops_do(f); 877 878 // We scan thread local monitor lists here, and the remaining global 879 // monitors in ObjectSynchronizer::oops_do(). 880 ObjectSynchronizer::thread_local_used_oops_do(this, f); 881 } 882 883 void Thread::metadata_handles_do(void f(Metadata*)) { 884 // Only walk the Handles in Thread. 885 if (metadata_handles() != NULL) { 886 for (int i = 0; i< metadata_handles()->length(); i++) { 887 f(metadata_handles()->at(i)); 888 } 889 } 890 } 891 892 void Thread::print_on(outputStream* st, bool print_extended_info) const { 893 // get_priority assumes osthread initialized 894 if (osthread() != NULL) { 895 int os_prio; 896 if (os::get_native_priority(this, &os_prio) == OS_OK) { 897 st->print("os_prio=%d ", os_prio); 898 } 899 900 st->print("cpu=%.2fms ", 901 os::thread_cpu_time(const_cast<Thread*>(this), true) / 1000000.0 902 ); 903 st->print("elapsed=%.2fs ", 904 _statistical_info.getElapsedTime() / 1000.0 905 ); 906 if (is_Java_thread() && (PrintExtendedThreadInfo || print_extended_info)) { 907 size_t allocated_bytes = (size_t) const_cast<Thread*>(this)->cooked_allocated_bytes(); 908 st->print("allocated=" SIZE_FORMAT "%s ", 909 byte_size_in_proper_unit(allocated_bytes), 910 proper_unit_for_byte_size(allocated_bytes) 911 ); 912 st->print("defined_classes=" INT64_FORMAT " ", _statistical_info.getDefineClassCount()); 913 } 914 915 st->print("tid=" INTPTR_FORMAT " ", p2i(this)); 916 osthread()->print_on(st); 917 } 918 ThreadsSMRSupport::print_info_on(this, st); 919 st->print(" "); 920 debug_only(if (WizardMode) print_owned_locks_on(st);) 921 } 922 923 // Thread::print_on_error() is called by fatal error handler. Don't use 924 // any lock or allocate memory. 925 void Thread::print_on_error(outputStream* st, char* buf, int buflen) const { 926 assert(!(is_Compiler_thread() || is_Java_thread()), "Can't call name() here if it allocates"); 927 928 if (is_VM_thread()) { st->print("VMThread"); } 929 else if (is_GC_task_thread()) { st->print("GCTaskThread"); } 930 else if (is_Watcher_thread()) { st->print("WatcherThread"); } 931 else if (is_ConcurrentGC_thread()) { st->print("ConcurrentGCThread"); } 932 else { st->print("Thread"); } 933 934 if (is_Named_thread()) { 935 st->print(" \"%s\"", name()); 936 } 937 938 st->print(" [stack: " PTR_FORMAT "," PTR_FORMAT "]", 939 p2i(stack_end()), p2i(stack_base())); 940 941 if (osthread()) { 942 st->print(" [id=%d]", osthread()->thread_id()); 943 } 944 945 ThreadsSMRSupport::print_info_on(this, st); 946 } 947 948 void Thread::print_value_on(outputStream* st) const { 949 if (is_Named_thread()) { 950 st->print(" \"%s\" ", name()); 951 } 952 st->print(INTPTR_FORMAT, p2i(this)); // print address 953 } 954 955 #ifdef ASSERT 956 void Thread::print_owned_locks_on(outputStream* st) const { 957 Monitor *cur = _owned_locks; 958 if (cur == NULL) { 959 st->print(" (no locks) "); 960 } else { 961 st->print_cr(" Locks owned:"); 962 while (cur) { 963 cur->print_on(st); 964 cur = cur->next(); 965 } 966 } 967 } 968 969 static int ref_use_count = 0; 970 971 bool Thread::owns_locks_but_compiled_lock() const { 972 for (Monitor *cur = _owned_locks; cur; cur = cur->next()) { 973 if (cur != Compile_lock) return true; 974 } 975 return false; 976 } 977 978 979 #endif 980 981 #ifndef PRODUCT 982 983 // The flag: potential_vm_operation notifies if this particular safepoint state could potentially 984 // invoke the vm-thread (e.g., an oop allocation). In that case, we also have to make sure that 985 // no locks which allow_vm_block's are held 986 void Thread::check_for_valid_safepoint_state(bool potential_vm_operation) { 987 // Check if current thread is allowed to block at a safepoint 988 if (!(_allow_safepoint_count == 0)) { 989 fatal("Possible safepoint reached by thread that does not allow it"); 990 } 991 if (is_Java_thread() && ((JavaThread*)this)->thread_state() != _thread_in_vm) { 992 fatal("LEAF method calling lock?"); 993 } 994 995 #ifdef ASSERT 996 if (potential_vm_operation && is_Java_thread() 997 && !Universe::is_bootstrapping()) { 998 // Make sure we do not hold any locks that the VM thread also uses. 999 // This could potentially lead to deadlocks 1000 for (Monitor *cur = _owned_locks; cur; cur = cur->next()) { 1001 // Threads_lock is special, since the safepoint synchronization will not start before this is 1002 // acquired. Hence, a JavaThread cannot be holding it at a safepoint. So is VMOperationRequest_lock, 1003 // since it is used to transfer control between JavaThreads and the VMThread 1004 // Do not *exclude* any locks unless you are absolutely sure it is correct. Ask someone else first! 1005 if ((cur->allow_vm_block() && 1006 cur != Threads_lock && 1007 cur != Compile_lock && // Temporary: should not be necessary when we get separate compilation 1008 cur != VMOperationRequest_lock && 1009 cur != VMOperationQueue_lock) || 1010 cur->rank() == Mutex::special) { 1011 fatal("Thread holding lock at safepoint that vm can block on: %s", cur->name()); 1012 } 1013 } 1014 } 1015 1016 if (GCALotAtAllSafepoints) { 1017 // We could enter a safepoint here and thus have a gc 1018 InterfaceSupport::check_gc_alot(); 1019 } 1020 #endif 1021 } 1022 #endif 1023 1024 bool Thread::is_in_stack(address adr) const { 1025 assert(Thread::current() == this, "is_in_stack can only be called from current thread"); 1026 address end = os::current_stack_pointer(); 1027 // Allow non Java threads to call this without stack_base 1028 if (_stack_base == NULL) return true; 1029 if (stack_base() >= adr && adr >= end) return true; 1030 1031 return false; 1032 } 1033 1034 bool Thread::is_in_usable_stack(address adr) const { 1035 size_t stack_guard_size = os::uses_stack_guard_pages() ? JavaThread::stack_guard_zone_size() : 0; 1036 size_t usable_stack_size = _stack_size - stack_guard_size; 1037 1038 return ((adr < stack_base()) && (adr >= stack_base() - usable_stack_size)); 1039 } 1040 1041 1042 // We had to move these methods here, because vm threads get into ObjectSynchronizer::enter 1043 // However, there is a note in JavaThread::is_lock_owned() about the VM threads not being 1044 // used for compilation in the future. If that change is made, the need for these methods 1045 // should be revisited, and they should be removed if possible. 1046 1047 bool Thread::is_lock_owned(address adr) const { 1048 return on_local_stack(adr); 1049 } 1050 1051 bool Thread::set_as_starting_thread() { 1052 // NOTE: this must be called inside the main thread. 1053 return os::create_main_thread((JavaThread*)this); 1054 } 1055 1056 static void initialize_class(Symbol* class_name, TRAPS) { 1057 Klass* klass = SystemDictionary::resolve_or_fail(class_name, true, CHECK); 1058 InstanceKlass::cast(klass)->initialize(CHECK); 1059 } 1060 1061 1062 // Creates the initial ThreadGroup 1063 static Handle create_initial_thread_group(TRAPS) { 1064 Handle system_instance = JavaCalls::construct_new_instance( 1065 SystemDictionary::ThreadGroup_klass(), 1066 vmSymbols::void_method_signature(), 1067 CHECK_NH); 1068 Universe::set_system_thread_group(system_instance()); 1069 1070 Handle string = java_lang_String::create_from_str("main", CHECK_NH); 1071 Handle main_instance = JavaCalls::construct_new_instance( 1072 SystemDictionary::ThreadGroup_klass(), 1073 vmSymbols::threadgroup_string_void_signature(), 1074 system_instance, 1075 string, 1076 CHECK_NH); 1077 return main_instance; 1078 } 1079 1080 // Creates the initial Thread 1081 static oop create_initial_thread(Handle thread_group, JavaThread* thread, 1082 TRAPS) { 1083 InstanceKlass* ik = SystemDictionary::Thread_klass(); 1084 assert(ik->is_initialized(), "must be"); 1085 instanceHandle thread_oop = ik->allocate_instance_handle(CHECK_NULL); 1086 1087 // Cannot use JavaCalls::construct_new_instance because the java.lang.Thread 1088 // constructor calls Thread.current(), which must be set here for the 1089 // initial thread. 1090 java_lang_Thread::set_thread(thread_oop(), thread); 1091 java_lang_Thread::set_priority(thread_oop(), NormPriority); 1092 thread->set_threadObj(thread_oop()); 1093 1094 Handle string = java_lang_String::create_from_str("main", CHECK_NULL); 1095 1096 JavaValue result(T_VOID); 1097 JavaCalls::call_special(&result, thread_oop, 1098 ik, 1099 vmSymbols::object_initializer_name(), 1100 vmSymbols::threadgroup_string_void_signature(), 1101 thread_group, 1102 string, 1103 CHECK_NULL); 1104 return thread_oop(); 1105 } 1106 1107 char java_runtime_name[128] = ""; 1108 char java_runtime_version[128] = ""; 1109 1110 // extract the JRE name from java.lang.VersionProps.java_runtime_name 1111 static const char* get_java_runtime_name(TRAPS) { 1112 Klass* k = SystemDictionary::find(vmSymbols::java_lang_VersionProps(), 1113 Handle(), Handle(), CHECK_AND_CLEAR_NULL); 1114 fieldDescriptor fd; 1115 bool found = k != NULL && 1116 InstanceKlass::cast(k)->find_local_field(vmSymbols::java_runtime_name_name(), 1117 vmSymbols::string_signature(), &fd); 1118 if (found) { 1119 oop name_oop = k->java_mirror()->obj_field(fd.offset()); 1120 if (name_oop == NULL) { 1121 return NULL; 1122 } 1123 const char* name = java_lang_String::as_utf8_string(name_oop, 1124 java_runtime_name, 1125 sizeof(java_runtime_name)); 1126 return name; 1127 } else { 1128 return NULL; 1129 } 1130 } 1131 1132 // extract the JRE version from java.lang.VersionProps.java_runtime_version 1133 static const char* get_java_runtime_version(TRAPS) { 1134 Klass* k = SystemDictionary::find(vmSymbols::java_lang_VersionProps(), 1135 Handle(), Handle(), CHECK_AND_CLEAR_NULL); 1136 fieldDescriptor fd; 1137 bool found = k != NULL && 1138 InstanceKlass::cast(k)->find_local_field(vmSymbols::java_runtime_version_name(), 1139 vmSymbols::string_signature(), &fd); 1140 if (found) { 1141 oop name_oop = k->java_mirror()->obj_field(fd.offset()); 1142 if (name_oop == NULL) { 1143 return NULL; 1144 } 1145 const char* name = java_lang_String::as_utf8_string(name_oop, 1146 java_runtime_version, 1147 sizeof(java_runtime_version)); 1148 return name; 1149 } else { 1150 return NULL; 1151 } 1152 } 1153 1154 // General purpose hook into Java code, run once when the VM is initialized. 1155 // The Java library method itself may be changed independently from the VM. 1156 static void call_postVMInitHook(TRAPS) { 1157 Klass* klass = SystemDictionary::resolve_or_null(vmSymbols::jdk_internal_vm_PostVMInitHook(), THREAD); 1158 if (klass != NULL) { 1159 JavaValue result(T_VOID); 1160 JavaCalls::call_static(&result, klass, vmSymbols::run_method_name(), 1161 vmSymbols::void_method_signature(), 1162 CHECK); 1163 } 1164 } 1165 1166 void JavaThread::allocate_threadObj(Handle thread_group, const char* thread_name, 1167 bool daemon, TRAPS) { 1168 assert(thread_group.not_null(), "thread group should be specified"); 1169 assert(threadObj() == NULL, "should only create Java thread object once"); 1170 1171 InstanceKlass* ik = SystemDictionary::Thread_klass(); 1172 assert(ik->is_initialized(), "must be"); 1173 instanceHandle thread_oop = ik->allocate_instance_handle(CHECK); 1174 1175 // We are called from jni_AttachCurrentThread/jni_AttachCurrentThreadAsDaemon. 1176 // We cannot use JavaCalls::construct_new_instance because the java.lang.Thread 1177 // constructor calls Thread.current(), which must be set here. 1178 java_lang_Thread::set_thread(thread_oop(), this); 1179 java_lang_Thread::set_priority(thread_oop(), NormPriority); 1180 set_threadObj(thread_oop()); 1181 1182 JavaValue result(T_VOID); 1183 if (thread_name != NULL) { 1184 Handle name = java_lang_String::create_from_str(thread_name, CHECK); 1185 // Thread gets assigned specified name and null target 1186 JavaCalls::call_special(&result, 1187 thread_oop, 1188 ik, 1189 vmSymbols::object_initializer_name(), 1190 vmSymbols::threadgroup_string_void_signature(), 1191 thread_group, 1192 name, 1193 THREAD); 1194 } else { 1195 // Thread gets assigned name "Thread-nnn" and null target 1196 // (java.lang.Thread doesn't have a constructor taking only a ThreadGroup argument) 1197 JavaCalls::call_special(&result, 1198 thread_oop, 1199 ik, 1200 vmSymbols::object_initializer_name(), 1201 vmSymbols::threadgroup_runnable_void_signature(), 1202 thread_group, 1203 Handle(), 1204 THREAD); 1205 } 1206 1207 1208 if (daemon) { 1209 java_lang_Thread::set_daemon(thread_oop()); 1210 } 1211 1212 if (HAS_PENDING_EXCEPTION) { 1213 return; 1214 } 1215 1216 Klass* group = SystemDictionary::ThreadGroup_klass(); 1217 Handle threadObj(THREAD, this->threadObj()); 1218 1219 JavaCalls::call_special(&result, 1220 thread_group, 1221 group, 1222 vmSymbols::add_method_name(), 1223 vmSymbols::thread_void_signature(), 1224 threadObj, // Arg 1 1225 THREAD); 1226 } 1227 1228 // List of all NonJavaThreads and safe iteration over that list. 1229 1230 class NonJavaThread::List { 1231 public: 1232 NonJavaThread* volatile _head; 1233 SingleWriterSynchronizer _protect; 1234 1235 List() : _head(NULL), _protect() {} 1236 }; 1237 1238 NonJavaThread::List NonJavaThread::_the_list; 1239 1240 NonJavaThread::Iterator::Iterator() : 1241 _protect_enter(_the_list._protect.enter()), 1242 _current(OrderAccess::load_acquire(&_the_list._head)) 1243 {} 1244 1245 NonJavaThread::Iterator::~Iterator() { 1246 _the_list._protect.exit(_protect_enter); 1247 } 1248 1249 void NonJavaThread::Iterator::step() { 1250 assert(!end(), "precondition"); 1251 _current = OrderAccess::load_acquire(&_current->_next); 1252 } 1253 1254 NonJavaThread::NonJavaThread() : Thread(), _next(NULL) { 1255 // Add this thread to _the_list. 1256 MutexLockerEx lock(NonJavaThreadsList_lock, Mutex::_no_safepoint_check_flag); 1257 _next = _the_list._head; 1258 OrderAccess::release_store(&_the_list._head, this); 1259 } 1260 1261 NonJavaThread::~NonJavaThread() { 1262 // Remove this thread from _the_list. 1263 MutexLockerEx lock(NonJavaThreadsList_lock, Mutex::_no_safepoint_check_flag); 1264 NonJavaThread* volatile* p = &_the_list._head; 1265 for (NonJavaThread* t = *p; t != NULL; p = &t->_next, t = *p) { 1266 if (t == this) { 1267 *p = this->_next; 1268 // Wait for any in-progress iterators. 1269 _the_list._protect.synchronize(); 1270 break; 1271 } 1272 } 1273 } 1274 1275 // NamedThread -- non-JavaThread subclasses with multiple 1276 // uniquely named instances should derive from this. 1277 NamedThread::NamedThread() : 1278 NonJavaThread(), 1279 _name(NULL), 1280 _processed_thread(NULL), 1281 _gc_id(GCId::undefined()) 1282 {} 1283 1284 NamedThread::~NamedThread() { 1285 if (_name != NULL) { 1286 FREE_C_HEAP_ARRAY(char, _name); 1287 _name = NULL; 1288 } 1289 } 1290 1291 void NamedThread::set_name(const char* format, ...) { 1292 guarantee(_name == NULL, "Only get to set name once."); 1293 _name = NEW_C_HEAP_ARRAY(char, max_name_len, mtThread); 1294 guarantee(_name != NULL, "alloc failure"); 1295 va_list ap; 1296 va_start(ap, format); 1297 jio_vsnprintf(_name, max_name_len, format, ap); 1298 va_end(ap); 1299 } 1300 1301 void NamedThread::initialize_named_thread() { 1302 set_native_thread_name(name()); 1303 } 1304 1305 void NamedThread::print_on(outputStream* st) const { 1306 st->print("\"%s\" ", name()); 1307 Thread::print_on(st); 1308 st->cr(); 1309 } 1310 1311 1312 // ======= WatcherThread ======== 1313 1314 // The watcher thread exists to simulate timer interrupts. It should 1315 // be replaced by an abstraction over whatever native support for 1316 // timer interrupts exists on the platform. 1317 1318 WatcherThread* WatcherThread::_watcher_thread = NULL; 1319 bool WatcherThread::_startable = false; 1320 volatile bool WatcherThread::_should_terminate = false; 1321 1322 WatcherThread::WatcherThread() : NonJavaThread() { 1323 assert(watcher_thread() == NULL, "we can only allocate one WatcherThread"); 1324 if (os::create_thread(this, os::watcher_thread)) { 1325 _watcher_thread = this; 1326 1327 // Set the watcher thread to the highest OS priority which should not be 1328 // used, unless a Java thread with priority java.lang.Thread.MAX_PRIORITY 1329 // is created. The only normal thread using this priority is the reference 1330 // handler thread, which runs for very short intervals only. 1331 // If the VMThread's priority is not lower than the WatcherThread profiling 1332 // will be inaccurate. 1333 os::set_priority(this, MaxPriority); 1334 if (!DisableStartThread) { 1335 os::start_thread(this); 1336 } 1337 } 1338 } 1339 1340 int WatcherThread::sleep() const { 1341 // The WatcherThread does not participate in the safepoint protocol 1342 // for the PeriodicTask_lock because it is not a JavaThread. 1343 MutexLockerEx ml(PeriodicTask_lock, Mutex::_no_safepoint_check_flag); 1344 1345 if (_should_terminate) { 1346 // check for termination before we do any housekeeping or wait 1347 return 0; // we did not sleep. 1348 } 1349 1350 // remaining will be zero if there are no tasks, 1351 // causing the WatcherThread to sleep until a task is 1352 // enrolled 1353 int remaining = PeriodicTask::time_to_wait(); 1354 int time_slept = 0; 1355 1356 // we expect this to timeout - we only ever get unparked when 1357 // we should terminate or when a new task has been enrolled 1358 OSThreadWaitState osts(this->osthread(), false /* not Object.wait() */); 1359 1360 jlong time_before_loop = os::javaTimeNanos(); 1361 1362 while (true) { 1363 bool timedout = PeriodicTask_lock->wait(Mutex::_no_safepoint_check_flag, 1364 remaining); 1365 jlong now = os::javaTimeNanos(); 1366 1367 if (remaining == 0) { 1368 // if we didn't have any tasks we could have waited for a long time 1369 // consider the time_slept zero and reset time_before_loop 1370 time_slept = 0; 1371 time_before_loop = now; 1372 } else { 1373 // need to recalculate since we might have new tasks in _tasks 1374 time_slept = (int) ((now - time_before_loop) / 1000000); 1375 } 1376 1377 // Change to task list or spurious wakeup of some kind 1378 if (timedout || _should_terminate) { 1379 break; 1380 } 1381 1382 remaining = PeriodicTask::time_to_wait(); 1383 if (remaining == 0) { 1384 // Last task was just disenrolled so loop around and wait until 1385 // another task gets enrolled 1386 continue; 1387 } 1388 1389 remaining -= time_slept; 1390 if (remaining <= 0) { 1391 break; 1392 } 1393 } 1394 1395 return time_slept; 1396 } 1397 1398 void WatcherThread::run() { 1399 assert(this == watcher_thread(), "just checking"); 1400 1401 this->set_native_thread_name(this->name()); 1402 this->set_active_handles(JNIHandleBlock::allocate_block()); 1403 while (true) { 1404 assert(watcher_thread() == Thread::current(), "thread consistency check"); 1405 assert(watcher_thread() == this, "thread consistency check"); 1406 1407 // Calculate how long it'll be until the next PeriodicTask work 1408 // should be done, and sleep that amount of time. 1409 int time_waited = sleep(); 1410 1411 if (VMError::is_error_reported()) { 1412 // A fatal error has happened, the error handler(VMError::report_and_die) 1413 // should abort JVM after creating an error log file. However in some 1414 // rare cases, the error handler itself might deadlock. Here periodically 1415 // check for error reporting timeouts, and if it happens, just proceed to 1416 // abort the VM. 1417 1418 // This code is in WatcherThread because WatcherThread wakes up 1419 // periodically so the fatal error handler doesn't need to do anything; 1420 // also because the WatcherThread is less likely to crash than other 1421 // threads. 1422 1423 for (;;) { 1424 // Note: we use naked sleep in this loop because we want to avoid using 1425 // any kind of VM infrastructure which may be broken at this point. 1426 if (VMError::check_timeout()) { 1427 // We hit error reporting timeout. Error reporting was interrupted and 1428 // will be wrapping things up now (closing files etc). Give it some more 1429 // time, then quit the VM. 1430 os::naked_short_sleep(200); 1431 // Print a message to stderr. 1432 fdStream err(defaultStream::output_fd()); 1433 err.print_raw_cr("# [ timer expired, abort... ]"); 1434 // skip atexit/vm_exit/vm_abort hooks 1435 os::die(); 1436 } 1437 1438 // Wait a second, then recheck for timeout. 1439 os::naked_short_sleep(999); 1440 } 1441 } 1442 1443 if (_should_terminate) { 1444 // check for termination before posting the next tick 1445 break; 1446 } 1447 1448 PeriodicTask::real_time_tick(time_waited); 1449 } 1450 1451 // Signal that it is terminated 1452 { 1453 MutexLockerEx mu(Terminator_lock, Mutex::_no_safepoint_check_flag); 1454 _watcher_thread = NULL; 1455 Terminator_lock->notify(); 1456 } 1457 } 1458 1459 void WatcherThread::start() { 1460 assert(PeriodicTask_lock->owned_by_self(), "PeriodicTask_lock required"); 1461 1462 if (watcher_thread() == NULL && _startable) { 1463 _should_terminate = false; 1464 // Create the single instance of WatcherThread 1465 new WatcherThread(); 1466 } 1467 } 1468 1469 void WatcherThread::make_startable() { 1470 assert(PeriodicTask_lock->owned_by_self(), "PeriodicTask_lock required"); 1471 _startable = true; 1472 } 1473 1474 void WatcherThread::stop() { 1475 { 1476 // Follow normal safepoint aware lock enter protocol since the 1477 // WatcherThread is stopped by another JavaThread. 1478 MutexLocker ml(PeriodicTask_lock); 1479 _should_terminate = true; 1480 1481 WatcherThread* watcher = watcher_thread(); 1482 if (watcher != NULL) { 1483 // unpark the WatcherThread so it can see that it should terminate 1484 watcher->unpark(); 1485 } 1486 } 1487 1488 MutexLocker mu(Terminator_lock); 1489 1490 while (watcher_thread() != NULL) { 1491 // This wait should make safepoint checks, wait without a timeout, 1492 // and wait as a suspend-equivalent condition. 1493 Terminator_lock->wait(!Mutex::_no_safepoint_check_flag, 0, 1494 Mutex::_as_suspend_equivalent_flag); 1495 } 1496 } 1497 1498 void WatcherThread::unpark() { 1499 assert(PeriodicTask_lock->owned_by_self(), "PeriodicTask_lock required"); 1500 PeriodicTask_lock->notify(); 1501 } 1502 1503 void WatcherThread::print_on(outputStream* st) const { 1504 st->print("\"%s\" ", name()); 1505 Thread::print_on(st); 1506 st->cr(); 1507 } 1508 1509 // ======= JavaThread ======== 1510 1511 #if INCLUDE_JVMCI 1512 1513 jlong* JavaThread::_jvmci_old_thread_counters; 1514 1515 bool jvmci_counters_include(JavaThread* thread) { 1516 return !JVMCICountersExcludeCompiler || !thread->is_Compiler_thread(); 1517 } 1518 1519 void JavaThread::collect_counters(typeArrayOop array) { 1520 if (JVMCICounterSize > 0) { 1521 JavaThreadIteratorWithHandle jtiwh; 1522 for (int i = 0; i < array->length(); i++) { 1523 array->long_at_put(i, _jvmci_old_thread_counters[i]); 1524 } 1525 for (; JavaThread *tp = jtiwh.next(); ) { 1526 if (jvmci_counters_include(tp)) { 1527 for (int i = 0; i < array->length(); i++) { 1528 array->long_at_put(i, array->long_at(i) + tp->_jvmci_counters[i]); 1529 } 1530 } 1531 } 1532 } 1533 } 1534 1535 #endif // INCLUDE_JVMCI 1536 1537 // A JavaThread is a normal Java thread 1538 1539 void JavaThread::initialize() { 1540 // Initialize fields 1541 1542 set_saved_exception_pc(NULL); 1543 set_threadObj(NULL); 1544 _anchor.clear(); 1545 set_entry_point(NULL); 1546 set_jni_functions(jni_functions()); 1547 set_callee_target(NULL); 1548 set_vm_result(NULL); 1549 set_vm_result_2(NULL); 1550 set_vframe_array_head(NULL); 1551 set_vframe_array_last(NULL); 1552 set_deferred_locals(NULL); 1553 set_deopt_mark(NULL); 1554 set_deopt_compiled_method(NULL); 1555 clear_must_deopt_id(); 1556 set_monitor_chunks(NULL); 1557 set_next(NULL); 1558 _on_thread_list = false; 1559 set_thread_state(_thread_new); 1560 _terminated = _not_terminated; 1561 _privileged_stack_top = NULL; 1562 _array_for_gc = NULL; 1563 _suspend_equivalent = false; 1564 _in_deopt_handler = 0; 1565 _doing_unsafe_access = false; 1566 _stack_guard_state = stack_guard_unused; 1567 #if INCLUDE_JVMCI 1568 _pending_monitorenter = false; 1569 _pending_deoptimization = -1; 1570 _pending_failed_speculation = 0; 1571 _pending_transfer_to_interpreter = false; 1572 _adjusting_comp_level = false; 1573 _in_retryable_allocation = false; 1574 _jvmci._alternate_call_target = NULL; 1575 assert(_jvmci._implicit_exception_pc == NULL, "must be"); 1576 if (JVMCICounterSize > 0) { 1577 _jvmci_counters = NEW_C_HEAP_ARRAY(jlong, JVMCICounterSize, mtInternal); 1578 memset(_jvmci_counters, 0, sizeof(jlong) * JVMCICounterSize); 1579 } else { 1580 _jvmci_counters = NULL; 1581 } 1582 #endif // INCLUDE_JVMCI 1583 _reserved_stack_activation = NULL; // stack base not known yet 1584 (void)const_cast<oop&>(_exception_oop = oop(NULL)); 1585 _exception_pc = 0; 1586 _exception_handler_pc = 0; 1587 _is_method_handle_return = 0; 1588 _jvmti_thread_state= NULL; 1589 _should_post_on_exceptions_flag = JNI_FALSE; 1590 _interp_only_mode = 0; 1591 _special_runtime_exit_condition = _no_async_condition; 1592 _pending_async_exception = NULL; 1593 _thread_stat = NULL; 1594 _thread_stat = new ThreadStatistics(); 1595 _blocked_on_compilation = false; 1596 _jni_active_critical = 0; 1597 _pending_jni_exception_check_fn = NULL; 1598 _do_not_unlock_if_synchronized = false; 1599 _cached_monitor_info = NULL; 1600 _parker = Parker::Allocate(this); 1601 1602 #ifndef PRODUCT 1603 _jmp_ring_index = 0; 1604 for (int ji = 0; ji < jump_ring_buffer_size; ji++) { 1605 record_jump(NULL, NULL, NULL, 0); 1606 } 1607 #endif // PRODUCT 1608 1609 // Setup safepoint state info for this thread 1610 ThreadSafepointState::create(this); 1611 1612 debug_only(_java_call_counter = 0); 1613 1614 // JVMTI PopFrame support 1615 _popframe_condition = popframe_inactive; 1616 _popframe_preserved_args = NULL; 1617 _popframe_preserved_args_size = 0; 1618 _frames_to_pop_failed_realloc = 0; 1619 1620 if (SafepointMechanism::uses_thread_local_poll()) { 1621 SafepointMechanism::initialize_header(this); 1622 } 1623 1624 pd_initialize(); 1625 } 1626 1627 JavaThread::JavaThread(bool is_attaching_via_jni) : 1628 Thread() { 1629 initialize(); 1630 if (is_attaching_via_jni) { 1631 _jni_attach_state = _attaching_via_jni; 1632 } else { 1633 _jni_attach_state = _not_attaching_via_jni; 1634 } 1635 assert(deferred_card_mark().is_empty(), "Default MemRegion ctor"); 1636 } 1637 1638 bool JavaThread::reguard_stack(address cur_sp) { 1639 if (_stack_guard_state != stack_guard_yellow_reserved_disabled 1640 && _stack_guard_state != stack_guard_reserved_disabled) { 1641 return true; // Stack already guarded or guard pages not needed. 1642 } 1643 1644 if (register_stack_overflow()) { 1645 // For those architectures which have separate register and 1646 // memory stacks, we must check the register stack to see if 1647 // it has overflowed. 1648 return false; 1649 } 1650 1651 // Java code never executes within the yellow zone: the latter is only 1652 // there to provoke an exception during stack banging. If java code 1653 // is executing there, either StackShadowPages should be larger, or 1654 // some exception code in c1, c2 or the interpreter isn't unwinding 1655 // when it should. 1656 guarantee(cur_sp > stack_reserved_zone_base(), 1657 "not enough space to reguard - increase StackShadowPages"); 1658 if (_stack_guard_state == stack_guard_yellow_reserved_disabled) { 1659 enable_stack_yellow_reserved_zone(); 1660 if (reserved_stack_activation() != stack_base()) { 1661 set_reserved_stack_activation(stack_base()); 1662 } 1663 } else if (_stack_guard_state == stack_guard_reserved_disabled) { 1664 set_reserved_stack_activation(stack_base()); 1665 enable_stack_reserved_zone(); 1666 } 1667 return true; 1668 } 1669 1670 bool JavaThread::reguard_stack(void) { 1671 return reguard_stack(os::current_stack_pointer()); 1672 } 1673 1674 1675 void JavaThread::block_if_vm_exited() { 1676 if (_terminated == _vm_exited) { 1677 // _vm_exited is set at safepoint, and Threads_lock is never released 1678 // we will block here forever 1679 Threads_lock->lock_without_safepoint_check(); 1680 ShouldNotReachHere(); 1681 } 1682 } 1683 1684 1685 // Remove this ifdef when C1 is ported to the compiler interface. 1686 static void compiler_thread_entry(JavaThread* thread, TRAPS); 1687 static void sweeper_thread_entry(JavaThread* thread, TRAPS); 1688 1689 JavaThread::JavaThread(ThreadFunction entry_point, size_t stack_sz) : 1690 Thread() { 1691 initialize(); 1692 _jni_attach_state = _not_attaching_via_jni; 1693 set_entry_point(entry_point); 1694 // Create the native thread itself. 1695 // %note runtime_23 1696 os::ThreadType thr_type = os::java_thread; 1697 thr_type = entry_point == &compiler_thread_entry ? os::compiler_thread : 1698 os::java_thread; 1699 os::create_thread(this, thr_type, stack_sz); 1700 // The _osthread may be NULL here because we ran out of memory (too many threads active). 1701 // We need to throw and OutOfMemoryError - however we cannot do this here because the caller 1702 // may hold a lock and all locks must be unlocked before throwing the exception (throwing 1703 // the exception consists of creating the exception object & initializing it, initialization 1704 // will leave the VM via a JavaCall and then all locks must be unlocked). 1705 // 1706 // The thread is still suspended when we reach here. Thread must be explicit started 1707 // by creator! Furthermore, the thread must also explicitly be added to the Threads list 1708 // by calling Threads:add. The reason why this is not done here, is because the thread 1709 // object must be fully initialized (take a look at JVM_Start) 1710 } 1711 1712 JavaThread::~JavaThread() { 1713 1714 // JSR166 -- return the parker to the free list 1715 Parker::Release(_parker); 1716 _parker = NULL; 1717 1718 // Free any remaining previous UnrollBlock 1719 vframeArray* old_array = vframe_array_last(); 1720 1721 if (old_array != NULL) { 1722 Deoptimization::UnrollBlock* old_info = old_array->unroll_block(); 1723 old_array->set_unroll_block(NULL); 1724 delete old_info; 1725 delete old_array; 1726 } 1727 1728 GrowableArray<jvmtiDeferredLocalVariableSet*>* deferred = deferred_locals(); 1729 if (deferred != NULL) { 1730 // This can only happen if thread is destroyed before deoptimization occurs. 1731 assert(deferred->length() != 0, "empty array!"); 1732 do { 1733 jvmtiDeferredLocalVariableSet* dlv = deferred->at(0); 1734 deferred->remove_at(0); 1735 // individual jvmtiDeferredLocalVariableSet are CHeapObj's 1736 delete dlv; 1737 } while (deferred->length() != 0); 1738 delete deferred; 1739 } 1740 1741 // All Java related clean up happens in exit 1742 ThreadSafepointState::destroy(this); 1743 if (_thread_stat != NULL) delete _thread_stat; 1744 1745 #if INCLUDE_JVMCI 1746 if (JVMCICounterSize > 0) { 1747 if (jvmci_counters_include(this)) { 1748 for (int i = 0; i < JVMCICounterSize; i++) { 1749 _jvmci_old_thread_counters[i] += _jvmci_counters[i]; 1750 } 1751 } 1752 FREE_C_HEAP_ARRAY(jlong, _jvmci_counters); 1753 } 1754 #endif // INCLUDE_JVMCI 1755 } 1756 1757 1758 // The first routine called by a new Java thread 1759 void JavaThread::run() { 1760 // initialize thread-local alloc buffer related fields 1761 this->initialize_tlab(); 1762 1763 // used to test validity of stack trace backs 1764 this->record_base_of_stack_pointer(); 1765 1766 this->create_stack_guard_pages(); 1767 1768 this->cache_global_variables(); 1769 1770 // Thread is now sufficient initialized to be handled by the safepoint code as being 1771 // in the VM. Change thread state from _thread_new to _thread_in_vm 1772 ThreadStateTransition::transition_and_fence(this, _thread_new, _thread_in_vm); 1773 1774 assert(JavaThread::current() == this, "sanity check"); 1775 assert(!Thread::current()->owns_locks(), "sanity check"); 1776 1777 DTRACE_THREAD_PROBE(start, this); 1778 1779 // This operation might block. We call that after all safepoint checks for a new thread has 1780 // been completed. 1781 this->set_active_handles(JNIHandleBlock::allocate_block()); 1782 1783 if (JvmtiExport::should_post_thread_life()) { 1784 JvmtiExport::post_thread_start(this); 1785 } 1786 1787 EventThreadStart event; 1788 if (event.should_commit()) { 1789 event.set_thread(JFR_THREAD_ID(this)); 1790 event.commit(); 1791 } 1792 1793 // We call another function to do the rest so we are sure that the stack addresses used 1794 // from there will be lower than the stack base just computed 1795 thread_main_inner(); 1796 1797 // Note, thread is no longer valid at this point! 1798 } 1799 1800 1801 void JavaThread::thread_main_inner() { 1802 assert(JavaThread::current() == this, "sanity check"); 1803 assert(this->threadObj() != NULL, "just checking"); 1804 1805 // Execute thread entry point unless this thread has a pending exception 1806 // or has been stopped before starting. 1807 // Note: Due to JVM_StopThread we can have pending exceptions already! 1808 if (!this->has_pending_exception() && 1809 !java_lang_Thread::is_stillborn(this->threadObj())) { 1810 { 1811 ResourceMark rm(this); 1812 this->set_native_thread_name(this->get_thread_name()); 1813 } 1814 HandleMark hm(this); 1815 this->entry_point()(this, this); 1816 } 1817 1818 DTRACE_THREAD_PROBE(stop, this); 1819 1820 this->exit(false); 1821 this->smr_delete(); 1822 } 1823 1824 1825 static void ensure_join(JavaThread* thread) { 1826 // We do not need to grab the Threads_lock, since we are operating on ourself. 1827 Handle threadObj(thread, thread->threadObj()); 1828 assert(threadObj.not_null(), "java thread object must exist"); 1829 ObjectLocker lock(threadObj, thread); 1830 // Ignore pending exception (ThreadDeath), since we are exiting anyway 1831 thread->clear_pending_exception(); 1832 // Thread is exiting. So set thread_status field in java.lang.Thread class to TERMINATED. 1833 java_lang_Thread::set_thread_status(threadObj(), java_lang_Thread::TERMINATED); 1834 // Clear the native thread instance - this makes isAlive return false and allows the join() 1835 // to complete once we've done the notify_all below 1836 java_lang_Thread::set_thread(threadObj(), NULL); 1837 lock.notify_all(thread); 1838 // Ignore pending exception (ThreadDeath), since we are exiting anyway 1839 thread->clear_pending_exception(); 1840 } 1841 1842 static bool is_daemon(oop threadObj) { 1843 return (threadObj != NULL && java_lang_Thread::is_daemon(threadObj)); 1844 } 1845 1846 // For any new cleanup additions, please check to see if they need to be applied to 1847 // cleanup_failed_attach_current_thread as well. 1848 void JavaThread::exit(bool destroy_vm, ExitType exit_type) { 1849 assert(this == JavaThread::current(), "thread consistency check"); 1850 1851 elapsedTimer _timer_exit_phase1; 1852 elapsedTimer _timer_exit_phase2; 1853 elapsedTimer _timer_exit_phase3; 1854 elapsedTimer _timer_exit_phase4; 1855 1856 if (log_is_enabled(Debug, os, thread, timer)) { 1857 _timer_exit_phase1.start(); 1858 } 1859 1860 HandleMark hm(this); 1861 Handle uncaught_exception(this, this->pending_exception()); 1862 this->clear_pending_exception(); 1863 Handle threadObj(this, this->threadObj()); 1864 assert(threadObj.not_null(), "Java thread object should be created"); 1865 1866 // FIXIT: This code should be moved into else part, when reliable 1.2/1.3 check is in place 1867 { 1868 EXCEPTION_MARK; 1869 1870 CLEAR_PENDING_EXCEPTION; 1871 } 1872 if (!destroy_vm) { 1873 if (uncaught_exception.not_null()) { 1874 EXCEPTION_MARK; 1875 // Call method Thread.dispatchUncaughtException(). 1876 Klass* thread_klass = SystemDictionary::Thread_klass(); 1877 JavaValue result(T_VOID); 1878 JavaCalls::call_virtual(&result, 1879 threadObj, thread_klass, 1880 vmSymbols::dispatchUncaughtException_name(), 1881 vmSymbols::throwable_void_signature(), 1882 uncaught_exception, 1883 THREAD); 1884 if (HAS_PENDING_EXCEPTION) { 1885 ResourceMark rm(this); 1886 jio_fprintf(defaultStream::error_stream(), 1887 "\nException: %s thrown from the UncaughtExceptionHandler" 1888 " in thread \"%s\"\n", 1889 pending_exception()->klass()->external_name(), 1890 get_thread_name()); 1891 CLEAR_PENDING_EXCEPTION; 1892 } 1893 } 1894 1895 // Called before the java thread exit since we want to read info 1896 // from java_lang_Thread object 1897 EventThreadEnd event; 1898 if (event.should_commit()) { 1899 event.set_thread(JFR_THREAD_ID(this)); 1900 event.commit(); 1901 } 1902 1903 // Call after last event on thread 1904 JFR_ONLY(Jfr::on_thread_exit(this);) 1905 1906 // Call Thread.exit(). We try 3 times in case we got another Thread.stop during 1907 // the execution of the method. If that is not enough, then we don't really care. Thread.stop 1908 // is deprecated anyhow. 1909 if (!is_Compiler_thread()) { 1910 int count = 3; 1911 while (java_lang_Thread::threadGroup(threadObj()) != NULL && (count-- > 0)) { 1912 EXCEPTION_MARK; 1913 JavaValue result(T_VOID); 1914 Klass* thread_klass = SystemDictionary::Thread_klass(); 1915 JavaCalls::call_virtual(&result, 1916 threadObj, thread_klass, 1917 vmSymbols::exit_method_name(), 1918 vmSymbols::void_method_signature(), 1919 THREAD); 1920 CLEAR_PENDING_EXCEPTION; 1921 } 1922 } 1923 // notify JVMTI 1924 if (JvmtiExport::should_post_thread_life()) { 1925 JvmtiExport::post_thread_end(this); 1926 } 1927 1928 // We have notified the agents that we are exiting, before we go on, 1929 // we must check for a pending external suspend request and honor it 1930 // in order to not surprise the thread that made the suspend request. 1931 while (true) { 1932 { 1933 MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag); 1934 if (!is_external_suspend()) { 1935 set_terminated(_thread_exiting); 1936 ThreadService::current_thread_exiting(this, is_daemon(threadObj())); 1937 break; 1938 } 1939 // Implied else: 1940 // Things get a little tricky here. We have a pending external 1941 // suspend request, but we are holding the SR_lock so we 1942 // can't just self-suspend. So we temporarily drop the lock 1943 // and then self-suspend. 1944 } 1945 1946 ThreadBlockInVM tbivm(this); 1947 java_suspend_self(); 1948 1949 // We're done with this suspend request, but we have to loop around 1950 // and check again. Eventually we will get SR_lock without a pending 1951 // external suspend request and will be able to mark ourselves as 1952 // exiting. 1953 } 1954 // no more external suspends are allowed at this point 1955 } else { 1956 assert(!is_terminated() && !is_exiting(), "must not be exiting"); 1957 // before_exit() has already posted JVMTI THREAD_END events 1958 } 1959 1960 if (log_is_enabled(Debug, os, thread, timer)) { 1961 _timer_exit_phase1.stop(); 1962 _timer_exit_phase2.start(); 1963 } 1964 // Notify waiters on thread object. This has to be done after exit() is called 1965 // on the thread (if the thread is the last thread in a daemon ThreadGroup the 1966 // group should have the destroyed bit set before waiters are notified). 1967 ensure_join(this); 1968 assert(!this->has_pending_exception(), "ensure_join should have cleared"); 1969 1970 if (log_is_enabled(Debug, os, thread, timer)) { 1971 _timer_exit_phase2.stop(); 1972 _timer_exit_phase3.start(); 1973 } 1974 // 6282335 JNI DetachCurrentThread spec states that all Java monitors 1975 // held by this thread must be released. The spec does not distinguish 1976 // between JNI-acquired and regular Java monitors. We can only see 1977 // regular Java monitors here if monitor enter-exit matching is broken. 1978 // 1979 // ensure_join() ignores IllegalThreadStateExceptions, and so does 1980 // ObjectSynchronizer::release_monitors_owned_by_thread(). 1981 if (exit_type == jni_detach) { 1982 // Sanity check even though JNI DetachCurrentThread() would have 1983 // returned JNI_ERR if there was a Java frame. JavaThread exit 1984 // should be done executing Java code by the time we get here. 1985 assert(!this->has_last_Java_frame(), 1986 "should not have a Java frame when detaching or exiting"); 1987 ObjectSynchronizer::release_monitors_owned_by_thread(this); 1988 assert(!this->has_pending_exception(), "release_monitors should have cleared"); 1989 } 1990 1991 // These things needs to be done while we are still a Java Thread. Make sure that thread 1992 // is in a consistent state, in case GC happens 1993 assert(_privileged_stack_top == NULL, "must be NULL when we get here"); 1994 1995 if (active_handles() != NULL) { 1996 JNIHandleBlock* block = active_handles(); 1997 set_active_handles(NULL); 1998 JNIHandleBlock::release_block(block); 1999 } 2000 2001 if (free_handle_block() != NULL) { 2002 JNIHandleBlock* block = free_handle_block(); 2003 set_free_handle_block(NULL); 2004 JNIHandleBlock::release_block(block); 2005 } 2006 2007 // These have to be removed while this is still a valid thread. 2008 remove_stack_guard_pages(); 2009 2010 if (UseTLAB) { 2011 tlab().retire(); 2012 } 2013 2014 if (JvmtiEnv::environments_might_exist()) { 2015 JvmtiExport::cleanup_thread(this); 2016 } 2017 2018 // We must flush any deferred card marks and other various GC barrier 2019 // related buffers (e.g. G1 SATB buffer and G1 dirty card queue buffer) 2020 // before removing a thread from the list of active threads. 2021 BarrierSet::barrier_set()->on_thread_detach(this); 2022 2023 log_info(os, thread)("JavaThread %s (tid: " UINTX_FORMAT ").", 2024 exit_type == JavaThread::normal_exit ? "exiting" : "detaching", 2025 os::current_thread_id()); 2026 2027 if (log_is_enabled(Debug, os, thread, timer)) { 2028 _timer_exit_phase3.stop(); 2029 _timer_exit_phase4.start(); 2030 } 2031 // Remove from list of active threads list, and notify VM thread if we are the last non-daemon thread 2032 Threads::remove(this); 2033 2034 if (log_is_enabled(Debug, os, thread, timer)) { 2035 _timer_exit_phase4.stop(); 2036 ResourceMark rm(this); 2037 log_debug(os, thread, timer)("name='%s'" 2038 ", exit-phase1=" JLONG_FORMAT 2039 ", exit-phase2=" JLONG_FORMAT 2040 ", exit-phase3=" JLONG_FORMAT 2041 ", exit-phase4=" JLONG_FORMAT, 2042 get_thread_name(), 2043 _timer_exit_phase1.milliseconds(), 2044 _timer_exit_phase2.milliseconds(), 2045 _timer_exit_phase3.milliseconds(), 2046 _timer_exit_phase4.milliseconds()); 2047 } 2048 } 2049 2050 void JavaThread::cleanup_failed_attach_current_thread() { 2051 if (active_handles() != NULL) { 2052 JNIHandleBlock* block = active_handles(); 2053 set_active_handles(NULL); 2054 JNIHandleBlock::release_block(block); 2055 } 2056 2057 if (free_handle_block() != NULL) { 2058 JNIHandleBlock* block = free_handle_block(); 2059 set_free_handle_block(NULL); 2060 JNIHandleBlock::release_block(block); 2061 } 2062 2063 // These have to be removed while this is still a valid thread. 2064 remove_stack_guard_pages(); 2065 2066 if (UseTLAB) { 2067 tlab().retire(); 2068 } 2069 2070 BarrierSet::barrier_set()->on_thread_detach(this); 2071 2072 Threads::remove(this); 2073 this->smr_delete(); 2074 } 2075 2076 JavaThread* JavaThread::active() { 2077 Thread* thread = Thread::current(); 2078 if (thread->is_Java_thread()) { 2079 return (JavaThread*) thread; 2080 } else { 2081 assert(thread->is_VM_thread(), "this must be a vm thread"); 2082 VM_Operation* op = ((VMThread*) thread)->vm_operation(); 2083 JavaThread *ret=op == NULL ? NULL : (JavaThread *)op->calling_thread(); 2084 assert(ret->is_Java_thread(), "must be a Java thread"); 2085 return ret; 2086 } 2087 } 2088 2089 bool JavaThread::is_lock_owned(address adr) const { 2090 if (Thread::is_lock_owned(adr)) return true; 2091 2092 for (MonitorChunk* chunk = monitor_chunks(); chunk != NULL; chunk = chunk->next()) { 2093 if (chunk->contains(adr)) return true; 2094 } 2095 2096 return false; 2097 } 2098 2099 2100 void JavaThread::add_monitor_chunk(MonitorChunk* chunk) { 2101 chunk->set_next(monitor_chunks()); 2102 set_monitor_chunks(chunk); 2103 } 2104 2105 void JavaThread::remove_monitor_chunk(MonitorChunk* chunk) { 2106 guarantee(monitor_chunks() != NULL, "must be non empty"); 2107 if (monitor_chunks() == chunk) { 2108 set_monitor_chunks(chunk->next()); 2109 } else { 2110 MonitorChunk* prev = monitor_chunks(); 2111 while (prev->next() != chunk) prev = prev->next(); 2112 prev->set_next(chunk->next()); 2113 } 2114 } 2115 2116 // JVM support. 2117 2118 // Note: this function shouldn't block if it's called in 2119 // _thread_in_native_trans state (such as from 2120 // check_special_condition_for_native_trans()). 2121 void JavaThread::check_and_handle_async_exceptions(bool check_unsafe_error) { 2122 2123 if (has_last_Java_frame() && has_async_condition()) { 2124 // If we are at a polling page safepoint (not a poll return) 2125 // then we must defer async exception because live registers 2126 // will be clobbered by the exception path. Poll return is 2127 // ok because the call we a returning from already collides 2128 // with exception handling registers and so there is no issue. 2129 // (The exception handling path kills call result registers but 2130 // this is ok since the exception kills the result anyway). 2131 2132 if (is_at_poll_safepoint()) { 2133 // if the code we are returning to has deoptimized we must defer 2134 // the exception otherwise live registers get clobbered on the 2135 // exception path before deoptimization is able to retrieve them. 2136 // 2137 RegisterMap map(this, false); 2138 frame caller_fr = last_frame().sender(&map); 2139 assert(caller_fr.is_compiled_frame(), "what?"); 2140 if (caller_fr.is_deoptimized_frame()) { 2141 log_info(exceptions)("deferred async exception at compiled safepoint"); 2142 return; 2143 } 2144 } 2145 } 2146 2147 JavaThread::AsyncRequests condition = clear_special_runtime_exit_condition(); 2148 if (condition == _no_async_condition) { 2149 // Conditions have changed since has_special_runtime_exit_condition() 2150 // was called: 2151 // - if we were here only because of an external suspend request, 2152 // then that was taken care of above (or cancelled) so we are done 2153 // - if we were here because of another async request, then it has 2154 // been cleared between the has_special_runtime_exit_condition() 2155 // and now so again we are done 2156 return; 2157 } 2158 2159 // Check for pending async. exception 2160 if (_pending_async_exception != NULL) { 2161 // Only overwrite an already pending exception, if it is not a threadDeath. 2162 if (!has_pending_exception() || !pending_exception()->is_a(SystemDictionary::ThreadDeath_klass())) { 2163 2164 // We cannot call Exceptions::_throw(...) here because we cannot block 2165 set_pending_exception(_pending_async_exception, __FILE__, __LINE__); 2166 2167 LogTarget(Info, exceptions) lt; 2168 if (lt.is_enabled()) { 2169 ResourceMark rm; 2170 LogStream ls(lt); 2171 ls.print("Async. exception installed at runtime exit (" INTPTR_FORMAT ")", p2i(this)); 2172 if (has_last_Java_frame()) { 2173 frame f = last_frame(); 2174 ls.print(" (pc: " INTPTR_FORMAT " sp: " INTPTR_FORMAT " )", p2i(f.pc()), p2i(f.sp())); 2175 } 2176 ls.print_cr(" of type: %s", _pending_async_exception->klass()->external_name()); 2177 } 2178 _pending_async_exception = NULL; 2179 clear_has_async_exception(); 2180 } 2181 } 2182 2183 if (check_unsafe_error && 2184 condition == _async_unsafe_access_error && !has_pending_exception()) { 2185 condition = _no_async_condition; // done 2186 switch (thread_state()) { 2187 case _thread_in_vm: { 2188 JavaThread* THREAD = this; 2189 THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in an unsafe memory access operation"); 2190 } 2191 case _thread_in_native: { 2192 ThreadInVMfromNative tiv(this); 2193 JavaThread* THREAD = this; 2194 THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in an unsafe memory access operation"); 2195 } 2196 case _thread_in_Java: { 2197 ThreadInVMfromJava tiv(this); 2198 JavaThread* THREAD = this; 2199 THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in a recent unsafe memory access operation in compiled Java code"); 2200 } 2201 default: 2202 ShouldNotReachHere(); 2203 } 2204 } 2205 2206 assert(condition == _no_async_condition || has_pending_exception() || 2207 (!check_unsafe_error && condition == _async_unsafe_access_error), 2208 "must have handled the async condition, if no exception"); 2209 } 2210 2211 void JavaThread::handle_special_runtime_exit_condition(bool check_asyncs) { 2212 // 2213 // Check for pending external suspend. Internal suspend requests do 2214 // not use handle_special_runtime_exit_condition(). 2215 // If JNIEnv proxies are allowed, don't self-suspend if the target 2216 // thread is not the current thread. In older versions of jdbx, jdbx 2217 // threads could call into the VM with another thread's JNIEnv so we 2218 // can be here operating on behalf of a suspended thread (4432884). 2219 bool do_self_suspend = is_external_suspend_with_lock(); 2220 if (do_self_suspend && (!AllowJNIEnvProxy || this == JavaThread::current())) { 2221 // 2222 // Because thread is external suspended the safepoint code will count 2223 // thread as at a safepoint. This can be odd because we can be here 2224 // as _thread_in_Java which would normally transition to _thread_blocked 2225 // at a safepoint. We would like to mark the thread as _thread_blocked 2226 // before calling java_suspend_self like all other callers of it but 2227 // we must then observe proper safepoint protocol. (We can't leave 2228 // _thread_blocked with a safepoint in progress). However we can be 2229 // here as _thread_in_native_trans so we can't use a normal transition 2230 // constructor/destructor pair because they assert on that type of 2231 // transition. We could do something like: 2232 // 2233 // JavaThreadState state = thread_state(); 2234 // set_thread_state(_thread_in_vm); 2235 // { 2236 // ThreadBlockInVM tbivm(this); 2237 // java_suspend_self() 2238 // } 2239 // set_thread_state(_thread_in_vm_trans); 2240 // if (safepoint) block; 2241 // set_thread_state(state); 2242 // 2243 // but that is pretty messy. Instead we just go with the way the 2244 // code has worked before and note that this is the only path to 2245 // java_suspend_self that doesn't put the thread in _thread_blocked 2246 // mode. 2247 2248 frame_anchor()->make_walkable(this); 2249 java_suspend_self(); 2250 2251 // We might be here for reasons in addition to the self-suspend request 2252 // so check for other async requests. 2253 } 2254 2255 if (check_asyncs) { 2256 check_and_handle_async_exceptions(); 2257 } 2258 2259 JFR_ONLY(SUSPEND_THREAD_CONDITIONAL(this);) 2260 } 2261 2262 void JavaThread::send_thread_stop(oop java_throwable) { 2263 assert(Thread::current()->is_VM_thread(), "should be in the vm thread"); 2264 assert(Threads_lock->is_locked(), "Threads_lock should be locked by safepoint code"); 2265 assert(SafepointSynchronize::is_at_safepoint(), "all threads are stopped"); 2266 2267 // Do not throw asynchronous exceptions against the compiler thread 2268 // (the compiler thread should not be a Java thread -- fix in 1.4.2) 2269 if (!can_call_java()) return; 2270 2271 { 2272 // Actually throw the Throwable against the target Thread - however 2273 // only if there is no thread death exception installed already. 2274 if (_pending_async_exception == NULL || !_pending_async_exception->is_a(SystemDictionary::ThreadDeath_klass())) { 2275 // If the topmost frame is a runtime stub, then we are calling into 2276 // OptoRuntime from compiled code. Some runtime stubs (new, monitor_exit..) 2277 // must deoptimize the caller before continuing, as the compiled exception handler table 2278 // may not be valid 2279 if (has_last_Java_frame()) { 2280 frame f = last_frame(); 2281 if (f.is_runtime_frame() || f.is_safepoint_blob_frame()) { 2282 // BiasedLocking needs an updated RegisterMap for the revoke monitors pass 2283 RegisterMap reg_map(this, UseBiasedLocking); 2284 frame compiled_frame = f.sender(®_map); 2285 if (!StressCompiledExceptionHandlers && compiled_frame.can_be_deoptimized()) { 2286 Deoptimization::deoptimize(this, compiled_frame, ®_map); 2287 } 2288 } 2289 } 2290 2291 // Set async. pending exception in thread. 2292 set_pending_async_exception(java_throwable); 2293 2294 if (log_is_enabled(Info, exceptions)) { 2295 ResourceMark rm; 2296 log_info(exceptions)("Pending Async. exception installed of type: %s", 2297 InstanceKlass::cast(_pending_async_exception->klass())->external_name()); 2298 } 2299 // for AbortVMOnException flag 2300 Exceptions::debug_check_abort(_pending_async_exception->klass()->external_name()); 2301 } 2302 } 2303 2304 2305 // Interrupt thread so it will wake up from a potential wait() 2306 Thread::interrupt(this); 2307 } 2308 2309 // External suspension mechanism. 2310 // 2311 // Tell the VM to suspend a thread when ever it knows that it does not hold on 2312 // to any VM_locks and it is at a transition 2313 // Self-suspension will happen on the transition out of the vm. 2314 // Catch "this" coming in from JNIEnv pointers when the thread has been freed 2315 // 2316 // Guarantees on return: 2317 // + Target thread will not execute any new bytecode (that's why we need to 2318 // force a safepoint) 2319 // + Target thread will not enter any new monitors 2320 // 2321 void JavaThread::java_suspend() { 2322 ThreadsListHandle tlh; 2323 if (!tlh.includes(this) || threadObj() == NULL || is_exiting()) { 2324 return; 2325 } 2326 2327 { MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag); 2328 if (!is_external_suspend()) { 2329 // a racing resume has cancelled us; bail out now 2330 return; 2331 } 2332 2333 // suspend is done 2334 uint32_t debug_bits = 0; 2335 // Warning: is_ext_suspend_completed() may temporarily drop the 2336 // SR_lock to allow the thread to reach a stable thread state if 2337 // it is currently in a transient thread state. 2338 if (is_ext_suspend_completed(false /* !called_by_wait */, 2339 SuspendRetryDelay, &debug_bits)) { 2340 return; 2341 } 2342 } 2343 2344 VM_ThreadSuspend vm_suspend; 2345 VMThread::execute(&vm_suspend); 2346 } 2347 2348 // Part II of external suspension. 2349 // A JavaThread self suspends when it detects a pending external suspend 2350 // request. This is usually on transitions. It is also done in places 2351 // where continuing to the next transition would surprise the caller, 2352 // e.g., monitor entry. 2353 // 2354 // Returns the number of times that the thread self-suspended. 2355 // 2356 // Note: DO NOT call java_suspend_self() when you just want to block current 2357 // thread. java_suspend_self() is the second stage of cooperative 2358 // suspension for external suspend requests and should only be used 2359 // to complete an external suspend request. 2360 // 2361 int JavaThread::java_suspend_self() { 2362 int ret = 0; 2363 2364 // we are in the process of exiting so don't suspend 2365 if (is_exiting()) { 2366 clear_external_suspend(); 2367 return ret; 2368 } 2369 2370 assert(_anchor.walkable() || 2371 (is_Java_thread() && !((JavaThread*)this)->has_last_Java_frame()), 2372 "must have walkable stack"); 2373 2374 MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag); 2375 2376 assert(!this->is_ext_suspended(), 2377 "a thread trying to self-suspend should not already be suspended"); 2378 2379 if (this->is_suspend_equivalent()) { 2380 // If we are self-suspending as a result of the lifting of a 2381 // suspend equivalent condition, then the suspend_equivalent 2382 // flag is not cleared until we set the ext_suspended flag so 2383 // that wait_for_ext_suspend_completion() returns consistent 2384 // results. 2385 this->clear_suspend_equivalent(); 2386 } 2387 2388 // A racing resume may have cancelled us before we grabbed SR_lock 2389 // above. Or another external suspend request could be waiting for us 2390 // by the time we return from SR_lock()->wait(). The thread 2391 // that requested the suspension may already be trying to walk our 2392 // stack and if we return now, we can change the stack out from under 2393 // it. This would be a "bad thing (TM)" and cause the stack walker 2394 // to crash. We stay self-suspended until there are no more pending 2395 // external suspend requests. 2396 while (is_external_suspend()) { 2397 ret++; 2398 this->set_ext_suspended(); 2399 2400 // _ext_suspended flag is cleared by java_resume() 2401 while (is_ext_suspended()) { 2402 this->SR_lock()->wait(Mutex::_no_safepoint_check_flag); 2403 } 2404 } 2405 2406 return ret; 2407 } 2408 2409 #ifdef ASSERT 2410 // Verify the JavaThread has not yet been published in the Threads::list, and 2411 // hence doesn't need protection from concurrent access at this stage. 2412 void JavaThread::verify_not_published() { 2413 // Cannot create a ThreadsListHandle here and check !tlh.includes(this) 2414 // since an unpublished JavaThread doesn't participate in the 2415 // Thread-SMR protocol for keeping a ThreadsList alive. 2416 assert(!on_thread_list(), "JavaThread shouldn't have been published yet!"); 2417 } 2418 #endif 2419 2420 // Slow path when the native==>VM/Java barriers detect a safepoint is in 2421 // progress or when _suspend_flags is non-zero. 2422 // Current thread needs to self-suspend if there is a suspend request and/or 2423 // block if a safepoint is in progress. 2424 // Async exception ISN'T checked. 2425 // Note only the ThreadInVMfromNative transition can call this function 2426 // directly and when thread state is _thread_in_native_trans 2427 void JavaThread::check_safepoint_and_suspend_for_native_trans(JavaThread *thread) { 2428 assert(thread->thread_state() == _thread_in_native_trans, "wrong state"); 2429 2430 JavaThread *curJT = JavaThread::current(); 2431 bool do_self_suspend = thread->is_external_suspend(); 2432 2433 assert(!curJT->has_last_Java_frame() || curJT->frame_anchor()->walkable(), "Unwalkable stack in native->vm transition"); 2434 2435 // If JNIEnv proxies are allowed, don't self-suspend if the target 2436 // thread is not the current thread. In older versions of jdbx, jdbx 2437 // threads could call into the VM with another thread's JNIEnv so we 2438 // can be here operating on behalf of a suspended thread (4432884). 2439 if (do_self_suspend && (!AllowJNIEnvProxy || curJT == thread)) { 2440 JavaThreadState state = thread->thread_state(); 2441 2442 // We mark this thread_blocked state as a suspend-equivalent so 2443 // that a caller to is_ext_suspend_completed() won't be confused. 2444 // The suspend-equivalent state is cleared by java_suspend_self(). 2445 thread->set_suspend_equivalent(); 2446 2447 // If the safepoint code sees the _thread_in_native_trans state, it will 2448 // wait until the thread changes to other thread state. There is no 2449 // guarantee on how soon we can obtain the SR_lock and complete the 2450 // self-suspend request. It would be a bad idea to let safepoint wait for 2451 // too long. Temporarily change the state to _thread_blocked to 2452 // let the VM thread know that this thread is ready for GC. The problem 2453 // of changing thread state is that safepoint could happen just after 2454 // java_suspend_self() returns after being resumed, and VM thread will 2455 // see the _thread_blocked state. We must check for safepoint 2456 // after restoring the state and make sure we won't leave while a safepoint 2457 // is in progress. 2458 thread->set_thread_state(_thread_blocked); 2459 thread->java_suspend_self(); 2460 thread->set_thread_state(state); 2461 2462 InterfaceSupport::serialize_thread_state_with_handler(thread); 2463 } 2464 2465 SafepointMechanism::block_if_requested(curJT); 2466 2467 if (thread->is_deopt_suspend()) { 2468 thread->clear_deopt_suspend(); 2469 RegisterMap map(thread, false); 2470 frame f = thread->last_frame(); 2471 while (f.id() != thread->must_deopt_id() && ! f.is_first_frame()) { 2472 f = f.sender(&map); 2473 } 2474 if (f.id() == thread->must_deopt_id()) { 2475 thread->clear_must_deopt_id(); 2476 f.deoptimize(thread); 2477 } else { 2478 fatal("missed deoptimization!"); 2479 } 2480 } 2481 2482 JFR_ONLY(SUSPEND_THREAD_CONDITIONAL(thread);) 2483 } 2484 2485 // Slow path when the native==>VM/Java barriers detect a safepoint is in 2486 // progress or when _suspend_flags is non-zero. 2487 // Current thread needs to self-suspend if there is a suspend request and/or 2488 // block if a safepoint is in progress. 2489 // Also check for pending async exception (not including unsafe access error). 2490 // Note only the native==>VM/Java barriers can call this function and when 2491 // thread state is _thread_in_native_trans. 2492 void JavaThread::check_special_condition_for_native_trans(JavaThread *thread) { 2493 check_safepoint_and_suspend_for_native_trans(thread); 2494 2495 if (thread->has_async_exception()) { 2496 // We are in _thread_in_native_trans state, don't handle unsafe 2497 // access error since that may block. 2498 thread->check_and_handle_async_exceptions(false); 2499 } 2500 } 2501 2502 // This is a variant of the normal 2503 // check_special_condition_for_native_trans with slightly different 2504 // semantics for use by critical native wrappers. It does all the 2505 // normal checks but also performs the transition back into 2506 // thread_in_Java state. This is required so that critical natives 2507 // can potentially block and perform a GC if they are the last thread 2508 // exiting the GCLocker. 2509 void JavaThread::check_special_condition_for_native_trans_and_transition(JavaThread *thread) { 2510 check_special_condition_for_native_trans(thread); 2511 2512 // Finish the transition 2513 thread->set_thread_state(_thread_in_Java); 2514 2515 if (thread->do_critical_native_unlock()) { 2516 ThreadInVMfromJavaNoAsyncException tiv(thread); 2517 GCLocker::unlock_critical(thread); 2518 thread->clear_critical_native_unlock(); 2519 } 2520 } 2521 2522 // We need to guarantee the Threads_lock here, since resumes are not 2523 // allowed during safepoint synchronization 2524 // Can only resume from an external suspension 2525 void JavaThread::java_resume() { 2526 assert_locked_or_safepoint(Threads_lock); 2527 2528 // Sanity check: thread is gone, has started exiting or the thread 2529 // was not externally suspended. 2530 ThreadsListHandle tlh; 2531 if (!tlh.includes(this) || is_exiting() || !is_external_suspend()) { 2532 return; 2533 } 2534 2535 MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag); 2536 2537 clear_external_suspend(); 2538 2539 if (is_ext_suspended()) { 2540 clear_ext_suspended(); 2541 SR_lock()->notify_all(); 2542 } 2543 } 2544 2545 size_t JavaThread::_stack_red_zone_size = 0; 2546 size_t JavaThread::_stack_yellow_zone_size = 0; 2547 size_t JavaThread::_stack_reserved_zone_size = 0; 2548 size_t JavaThread::_stack_shadow_zone_size = 0; 2549 2550 void JavaThread::create_stack_guard_pages() { 2551 if (!os::uses_stack_guard_pages() || 2552 _stack_guard_state != stack_guard_unused || 2553 (DisablePrimordialThreadGuardPages && os::is_primordial_thread())) { 2554 log_info(os, thread)("Stack guard page creation for thread " 2555 UINTX_FORMAT " disabled", os::current_thread_id()); 2556 return; 2557 } 2558 address low_addr = stack_end(); 2559 size_t len = stack_guard_zone_size(); 2560 2561 assert(is_aligned(low_addr, os::vm_page_size()), "Stack base should be the start of a page"); 2562 assert(is_aligned(len, os::vm_page_size()), "Stack size should be a multiple of page size"); 2563 2564 int must_commit = os::must_commit_stack_guard_pages(); 2565 // warning("Guarding at " PTR_FORMAT " for len " SIZE_FORMAT "\n", low_addr, len); 2566 2567 if (must_commit && !os::create_stack_guard_pages((char *) low_addr, len)) { 2568 log_warning(os, thread)("Attempt to allocate stack guard pages failed."); 2569 return; 2570 } 2571 2572 if (os::guard_memory((char *) low_addr, len)) { 2573 _stack_guard_state = stack_guard_enabled; 2574 } else { 2575 log_warning(os, thread)("Attempt to protect stack guard pages failed (" 2576 PTR_FORMAT "-" PTR_FORMAT ").", p2i(low_addr), p2i(low_addr + len)); 2577 if (os::uncommit_memory((char *) low_addr, len)) { 2578 log_warning(os, thread)("Attempt to deallocate stack guard pages failed."); 2579 } 2580 return; 2581 } 2582 2583 log_debug(os, thread)("Thread " UINTX_FORMAT " stack guard pages activated: " 2584 PTR_FORMAT "-" PTR_FORMAT ".", 2585 os::current_thread_id(), p2i(low_addr), p2i(low_addr + len)); 2586 } 2587 2588 void JavaThread::remove_stack_guard_pages() { 2589 assert(Thread::current() == this, "from different thread"); 2590 if (_stack_guard_state == stack_guard_unused) return; 2591 address low_addr = stack_end(); 2592 size_t len = stack_guard_zone_size(); 2593 2594 if (os::must_commit_stack_guard_pages()) { 2595 if (os::remove_stack_guard_pages((char *) low_addr, len)) { 2596 _stack_guard_state = stack_guard_unused; 2597 } else { 2598 log_warning(os, thread)("Attempt to deallocate stack guard pages failed (" 2599 PTR_FORMAT "-" PTR_FORMAT ").", p2i(low_addr), p2i(low_addr + len)); 2600 return; 2601 } 2602 } else { 2603 if (_stack_guard_state == stack_guard_unused) return; 2604 if (os::unguard_memory((char *) low_addr, len)) { 2605 _stack_guard_state = stack_guard_unused; 2606 } else { 2607 log_warning(os, thread)("Attempt to unprotect stack guard pages failed (" 2608 PTR_FORMAT "-" PTR_FORMAT ").", p2i(low_addr), p2i(low_addr + len)); 2609 return; 2610 } 2611 } 2612 2613 log_debug(os, thread)("Thread " UINTX_FORMAT " stack guard pages removed: " 2614 PTR_FORMAT "-" PTR_FORMAT ".", 2615 os::current_thread_id(), p2i(low_addr), p2i(low_addr + len)); 2616 } 2617 2618 void JavaThread::enable_stack_reserved_zone() { 2619 assert(_stack_guard_state != stack_guard_unused, "must be using guard pages."); 2620 assert(_stack_guard_state != stack_guard_enabled, "already enabled"); 2621 2622 // The base notation is from the stack's point of view, growing downward. 2623 // We need to adjust it to work correctly with guard_memory() 2624 address base = stack_reserved_zone_base() - stack_reserved_zone_size(); 2625 2626 guarantee(base < stack_base(),"Error calculating stack reserved zone"); 2627 guarantee(base < os::current_stack_pointer(),"Error calculating stack reserved zone"); 2628 2629 if (os::guard_memory((char *) base, stack_reserved_zone_size())) { 2630 _stack_guard_state = stack_guard_enabled; 2631 } else { 2632 warning("Attempt to guard stack reserved zone failed."); 2633 } 2634 enable_register_stack_guard(); 2635 } 2636 2637 void JavaThread::disable_stack_reserved_zone() { 2638 assert(_stack_guard_state != stack_guard_unused, "must be using guard pages."); 2639 assert(_stack_guard_state != stack_guard_reserved_disabled, "already disabled"); 2640 2641 // Simply return if called for a thread that does not use guard pages. 2642 if (_stack_guard_state == stack_guard_unused) return; 2643 2644 // The base notation is from the stack's point of view, growing downward. 2645 // We need to adjust it to work correctly with guard_memory() 2646 address base = stack_reserved_zone_base() - stack_reserved_zone_size(); 2647 2648 if (os::unguard_memory((char *)base, stack_reserved_zone_size())) { 2649 _stack_guard_state = stack_guard_reserved_disabled; 2650 } else { 2651 warning("Attempt to unguard stack reserved zone failed."); 2652 } 2653 disable_register_stack_guard(); 2654 } 2655 2656 void JavaThread::enable_stack_yellow_reserved_zone() { 2657 assert(_stack_guard_state != stack_guard_unused, "must be using guard pages."); 2658 assert(_stack_guard_state != stack_guard_enabled, "already enabled"); 2659 2660 // The base notation is from the stacks point of view, growing downward. 2661 // We need to adjust it to work correctly with guard_memory() 2662 address base = stack_red_zone_base(); 2663 2664 guarantee(base < stack_base(), "Error calculating stack yellow zone"); 2665 guarantee(base < os::current_stack_pointer(), "Error calculating stack yellow zone"); 2666 2667 if (os::guard_memory((char *) base, stack_yellow_reserved_zone_size())) { 2668 _stack_guard_state = stack_guard_enabled; 2669 } else { 2670 warning("Attempt to guard stack yellow zone failed."); 2671 } 2672 enable_register_stack_guard(); 2673 } 2674 2675 void JavaThread::disable_stack_yellow_reserved_zone() { 2676 assert(_stack_guard_state != stack_guard_unused, "must be using guard pages."); 2677 assert(_stack_guard_state != stack_guard_yellow_reserved_disabled, "already disabled"); 2678 2679 // Simply return if called for a thread that does not use guard pages. 2680 if (_stack_guard_state == stack_guard_unused) return; 2681 2682 // The base notation is from the stacks point of view, growing downward. 2683 // We need to adjust it to work correctly with guard_memory() 2684 address base = stack_red_zone_base(); 2685 2686 if (os::unguard_memory((char *)base, stack_yellow_reserved_zone_size())) { 2687 _stack_guard_state = stack_guard_yellow_reserved_disabled; 2688 } else { 2689 warning("Attempt to unguard stack yellow zone failed."); 2690 } 2691 disable_register_stack_guard(); 2692 } 2693 2694 void JavaThread::enable_stack_red_zone() { 2695 // The base notation is from the stacks point of view, growing downward. 2696 // We need to adjust it to work correctly with guard_memory() 2697 assert(_stack_guard_state != stack_guard_unused, "must be using guard pages."); 2698 address base = stack_red_zone_base() - stack_red_zone_size(); 2699 2700 guarantee(base < stack_base(), "Error calculating stack red zone"); 2701 guarantee(base < os::current_stack_pointer(), "Error calculating stack red zone"); 2702 2703 if (!os::guard_memory((char *) base, stack_red_zone_size())) { 2704 warning("Attempt to guard stack red zone failed."); 2705 } 2706 } 2707 2708 void JavaThread::disable_stack_red_zone() { 2709 // The base notation is from the stacks point of view, growing downward. 2710 // We need to adjust it to work correctly with guard_memory() 2711 assert(_stack_guard_state != stack_guard_unused, "must be using guard pages."); 2712 address base = stack_red_zone_base() - stack_red_zone_size(); 2713 if (!os::unguard_memory((char *)base, stack_red_zone_size())) { 2714 warning("Attempt to unguard stack red zone failed."); 2715 } 2716 } 2717 2718 void JavaThread::frames_do(void f(frame*, const RegisterMap* map)) { 2719 // ignore is there is no stack 2720 if (!has_last_Java_frame()) return; 2721 // traverse the stack frames. Starts from top frame. 2722 for (StackFrameStream fst(this); !fst.is_done(); fst.next()) { 2723 frame* fr = fst.current(); 2724 f(fr, fst.register_map()); 2725 } 2726 } 2727 2728 2729 #ifndef PRODUCT 2730 // Deoptimization 2731 // Function for testing deoptimization 2732 void JavaThread::deoptimize() { 2733 // BiasedLocking needs an updated RegisterMap for the revoke monitors pass 2734 StackFrameStream fst(this, UseBiasedLocking); 2735 bool deopt = false; // Dump stack only if a deopt actually happens. 2736 bool only_at = strlen(DeoptimizeOnlyAt) > 0; 2737 // Iterate over all frames in the thread and deoptimize 2738 for (; !fst.is_done(); fst.next()) { 2739 if (fst.current()->can_be_deoptimized()) { 2740 2741 if (only_at) { 2742 // Deoptimize only at particular bcis. DeoptimizeOnlyAt 2743 // consists of comma or carriage return separated numbers so 2744 // search for the current bci in that string. 2745 address pc = fst.current()->pc(); 2746 nmethod* nm = (nmethod*) fst.current()->cb(); 2747 ScopeDesc* sd = nm->scope_desc_at(pc); 2748 char buffer[8]; 2749 jio_snprintf(buffer, sizeof(buffer), "%d", sd->bci()); 2750 size_t len = strlen(buffer); 2751 const char * found = strstr(DeoptimizeOnlyAt, buffer); 2752 while (found != NULL) { 2753 if ((found[len] == ',' || found[len] == '\n' || found[len] == '\0') && 2754 (found == DeoptimizeOnlyAt || found[-1] == ',' || found[-1] == '\n')) { 2755 // Check that the bci found is bracketed by terminators. 2756 break; 2757 } 2758 found = strstr(found + 1, buffer); 2759 } 2760 if (!found) { 2761 continue; 2762 } 2763 } 2764 2765 if (DebugDeoptimization && !deopt) { 2766 deopt = true; // One-time only print before deopt 2767 tty->print_cr("[BEFORE Deoptimization]"); 2768 trace_frames(); 2769 trace_stack(); 2770 } 2771 Deoptimization::deoptimize(this, *fst.current(), fst.register_map()); 2772 } 2773 } 2774 2775 if (DebugDeoptimization && deopt) { 2776 tty->print_cr("[AFTER Deoptimization]"); 2777 trace_frames(); 2778 } 2779 } 2780 2781 2782 // Make zombies 2783 void JavaThread::make_zombies() { 2784 for (StackFrameStream fst(this); !fst.is_done(); fst.next()) { 2785 if (fst.current()->can_be_deoptimized()) { 2786 // it is a Java nmethod 2787 nmethod* nm = CodeCache::find_nmethod(fst.current()->pc()); 2788 nm->make_not_entrant(); 2789 } 2790 } 2791 } 2792 #endif // PRODUCT 2793 2794 2795 void JavaThread::deoptimized_wrt_marked_nmethods() { 2796 if (!has_last_Java_frame()) return; 2797 // BiasedLocking needs an updated RegisterMap for the revoke monitors pass 2798 StackFrameStream fst(this, UseBiasedLocking); 2799 for (; !fst.is_done(); fst.next()) { 2800 if (fst.current()->should_be_deoptimized()) { 2801 Deoptimization::deoptimize(this, *fst.current(), fst.register_map()); 2802 } 2803 } 2804 } 2805 2806 2807 // If the caller is a NamedThread, then remember, in the current scope, 2808 // the given JavaThread in its _processed_thread field. 2809 class RememberProcessedThread: public StackObj { 2810 NamedThread* _cur_thr; 2811 public: 2812 RememberProcessedThread(JavaThread* jthr) { 2813 Thread* thread = Thread::current(); 2814 if (thread->is_Named_thread()) { 2815 _cur_thr = (NamedThread *)thread; 2816 _cur_thr->set_processed_thread(jthr); 2817 } else { 2818 _cur_thr = NULL; 2819 } 2820 } 2821 2822 ~RememberProcessedThread() { 2823 if (_cur_thr) { 2824 _cur_thr->set_processed_thread(NULL); 2825 } 2826 } 2827 }; 2828 2829 void JavaThread::oops_do(OopClosure* f, CodeBlobClosure* cf) { 2830 // Verify that the deferred card marks have been flushed. 2831 assert(deferred_card_mark().is_empty(), "Should be empty during GC"); 2832 2833 // Traverse the GCHandles 2834 Thread::oops_do(f, cf); 2835 2836 assert((!has_last_Java_frame() && java_call_counter() == 0) || 2837 (has_last_Java_frame() && java_call_counter() > 0), "wrong java_sp info!"); 2838 2839 if (has_last_Java_frame()) { 2840 // Record JavaThread to GC thread 2841 RememberProcessedThread rpt(this); 2842 2843 // Traverse the privileged stack 2844 if (_privileged_stack_top != NULL) { 2845 _privileged_stack_top->oops_do(f); 2846 } 2847 2848 // traverse the registered growable array 2849 if (_array_for_gc != NULL) { 2850 for (int index = 0; index < _array_for_gc->length(); index++) { 2851 f->do_oop(_array_for_gc->adr_at(index)); 2852 } 2853 } 2854 2855 // Traverse the monitor chunks 2856 for (MonitorChunk* chunk = monitor_chunks(); chunk != NULL; chunk = chunk->next()) { 2857 chunk->oops_do(f); 2858 } 2859 2860 // Traverse the execution stack 2861 for (StackFrameStream fst(this); !fst.is_done(); fst.next()) { 2862 fst.current()->oops_do(f, cf, fst.register_map()); 2863 } 2864 } 2865 2866 // callee_target is never live across a gc point so NULL it here should 2867 // it still contain a methdOop. 2868 2869 set_callee_target(NULL); 2870 2871 assert(vframe_array_head() == NULL, "deopt in progress at a safepoint!"); 2872 // If we have deferred set_locals there might be oops waiting to be 2873 // written 2874 GrowableArray<jvmtiDeferredLocalVariableSet*>* list = deferred_locals(); 2875 if (list != NULL) { 2876 for (int i = 0; i < list->length(); i++) { 2877 list->at(i)->oops_do(f); 2878 } 2879 } 2880 2881 // Traverse instance variables at the end since the GC may be moving things 2882 // around using this function 2883 f->do_oop((oop*) &_threadObj); 2884 f->do_oop((oop*) &_vm_result); 2885 f->do_oop((oop*) &_exception_oop); 2886 f->do_oop((oop*) &_pending_async_exception); 2887 2888 if (jvmti_thread_state() != NULL) { 2889 jvmti_thread_state()->oops_do(f); 2890 } 2891 } 2892 2893 void JavaThread::nmethods_do(CodeBlobClosure* cf) { 2894 assert((!has_last_Java_frame() && java_call_counter() == 0) || 2895 (has_last_Java_frame() && java_call_counter() > 0), "wrong java_sp info!"); 2896 2897 if (has_last_Java_frame()) { 2898 // Traverse the execution stack 2899 for (StackFrameStream fst(this); !fst.is_done(); fst.next()) { 2900 fst.current()->nmethods_do(cf); 2901 } 2902 } 2903 } 2904 2905 void JavaThread::metadata_do(void f(Metadata*)) { 2906 if (has_last_Java_frame()) { 2907 // Traverse the execution stack to call f() on the methods in the stack 2908 for (StackFrameStream fst(this); !fst.is_done(); fst.next()) { 2909 fst.current()->metadata_do(f); 2910 } 2911 } else if (is_Compiler_thread()) { 2912 // need to walk ciMetadata in current compile tasks to keep alive. 2913 CompilerThread* ct = (CompilerThread*)this; 2914 if (ct->env() != NULL) { 2915 ct->env()->metadata_do(f); 2916 } 2917 CompileTask* task = ct->task(); 2918 if (task != NULL) { 2919 task->metadata_do(f); 2920 } 2921 } 2922 } 2923 2924 // Printing 2925 const char* _get_thread_state_name(JavaThreadState _thread_state) { 2926 switch (_thread_state) { 2927 case _thread_uninitialized: return "_thread_uninitialized"; 2928 case _thread_new: return "_thread_new"; 2929 case _thread_new_trans: return "_thread_new_trans"; 2930 case _thread_in_native: return "_thread_in_native"; 2931 case _thread_in_native_trans: return "_thread_in_native_trans"; 2932 case _thread_in_vm: return "_thread_in_vm"; 2933 case _thread_in_vm_trans: return "_thread_in_vm_trans"; 2934 case _thread_in_Java: return "_thread_in_Java"; 2935 case _thread_in_Java_trans: return "_thread_in_Java_trans"; 2936 case _thread_blocked: return "_thread_blocked"; 2937 case _thread_blocked_trans: return "_thread_blocked_trans"; 2938 default: return "unknown thread state"; 2939 } 2940 } 2941 2942 #ifndef PRODUCT 2943 void JavaThread::print_thread_state_on(outputStream *st) const { 2944 st->print_cr(" JavaThread state: %s", _get_thread_state_name(_thread_state)); 2945 }; 2946 void JavaThread::print_thread_state() const { 2947 print_thread_state_on(tty); 2948 } 2949 #endif // PRODUCT 2950 2951 // Called by Threads::print() for VM_PrintThreads operation 2952 void JavaThread::print_on(outputStream *st, bool print_extended_info) const { 2953 st->print_raw("\""); 2954 st->print_raw(get_thread_name()); 2955 st->print_raw("\" "); 2956 oop thread_oop = threadObj(); 2957 if (thread_oop != NULL) { 2958 st->print("#" INT64_FORMAT " ", (int64_t)java_lang_Thread::thread_id(thread_oop)); 2959 if (java_lang_Thread::is_daemon(thread_oop)) st->print("daemon "); 2960 st->print("prio=%d ", java_lang_Thread::priority(thread_oop)); 2961 } 2962 Thread::print_on(st, print_extended_info); 2963 // print guess for valid stack memory region (assume 4K pages); helps lock debugging 2964 st->print_cr("[" INTPTR_FORMAT "]", (intptr_t)last_Java_sp() & ~right_n_bits(12)); 2965 if (thread_oop != NULL) { 2966 st->print_cr(" java.lang.Thread.State: %s", java_lang_Thread::thread_status_name(thread_oop)); 2967 } 2968 #ifndef PRODUCT 2969 print_thread_state_on(st); 2970 _safepoint_state->print_on(st); 2971 #endif // PRODUCT 2972 if (is_Compiler_thread()) { 2973 CompileTask *task = ((CompilerThread*)this)->task(); 2974 if (task != NULL) { 2975 st->print(" Compiling: "); 2976 task->print(st, NULL, true, false); 2977 } else { 2978 st->print(" No compile task"); 2979 } 2980 st->cr(); 2981 } 2982 } 2983 2984 void JavaThread::print_name_on_error(outputStream* st, char *buf, int buflen) const { 2985 st->print("%s", get_thread_name_string(buf, buflen)); 2986 } 2987 2988 // Called by fatal error handler. The difference between this and 2989 // JavaThread::print() is that we can't grab lock or allocate memory. 2990 void JavaThread::print_on_error(outputStream* st, char *buf, int buflen) const { 2991 st->print("JavaThread \"%s\"", get_thread_name_string(buf, buflen)); 2992 oop thread_obj = threadObj(); 2993 if (thread_obj != NULL) { 2994 if (java_lang_Thread::is_daemon(thread_obj)) st->print(" daemon"); 2995 } 2996 st->print(" ["); 2997 st->print("%s", _get_thread_state_name(_thread_state)); 2998 if (osthread()) { 2999 st->print(", id=%d", osthread()->thread_id()); 3000 } 3001 st->print(", stack(" PTR_FORMAT "," PTR_FORMAT ")", 3002 p2i(stack_end()), p2i(stack_base())); 3003 st->print("]"); 3004 3005 ThreadsSMRSupport::print_info_on(this, st); 3006 return; 3007 } 3008 3009 // Verification 3010 3011 static void frame_verify(frame* f, const RegisterMap *map) { f->verify(map); } 3012 3013 void JavaThread::verify() { 3014 // Verify oops in the thread. 3015 oops_do(&VerifyOopClosure::verify_oop, NULL); 3016 3017 // Verify the stack frames. 3018 frames_do(frame_verify); 3019 } 3020 3021 // CR 6300358 (sub-CR 2137150) 3022 // Most callers of this method assume that it can't return NULL but a 3023 // thread may not have a name whilst it is in the process of attaching to 3024 // the VM - see CR 6412693, and there are places where a JavaThread can be 3025 // seen prior to having it's threadObj set (eg JNI attaching threads and 3026 // if vm exit occurs during initialization). These cases can all be accounted 3027 // for such that this method never returns NULL. 3028 const char* JavaThread::get_thread_name() const { 3029 #ifdef ASSERT 3030 // early safepoints can hit while current thread does not yet have TLS 3031 if (!SafepointSynchronize::is_at_safepoint()) { 3032 Thread *cur = Thread::current(); 3033 if (!(cur->is_Java_thread() && cur == this)) { 3034 // Current JavaThreads are allowed to get their own name without 3035 // the Threads_lock. 3036 assert_locked_or_safepoint(Threads_lock); 3037 } 3038 } 3039 #endif // ASSERT 3040 return get_thread_name_string(); 3041 } 3042 3043 // Returns a non-NULL representation of this thread's name, or a suitable 3044 // descriptive string if there is no set name 3045 const char* JavaThread::get_thread_name_string(char* buf, int buflen) const { 3046 const char* name_str; 3047 oop thread_obj = threadObj(); 3048 if (thread_obj != NULL) { 3049 oop name = java_lang_Thread::name(thread_obj); 3050 if (name != NULL) { 3051 if (buf == NULL) { 3052 name_str = java_lang_String::as_utf8_string(name); 3053 } else { 3054 name_str = java_lang_String::as_utf8_string(name, buf, buflen); 3055 } 3056 } else if (is_attaching_via_jni()) { // workaround for 6412693 - see 6404306 3057 name_str = "<no-name - thread is attaching>"; 3058 } else { 3059 name_str = Thread::name(); 3060 } 3061 } else { 3062 name_str = Thread::name(); 3063 } 3064 assert(name_str != NULL, "unexpected NULL thread name"); 3065 return name_str; 3066 } 3067 3068 3069 const char* JavaThread::get_threadgroup_name() const { 3070 debug_only(if (JavaThread::current() != this) assert_locked_or_safepoint(Threads_lock);) 3071 oop thread_obj = threadObj(); 3072 if (thread_obj != NULL) { 3073 oop thread_group = java_lang_Thread::threadGroup(thread_obj); 3074 if (thread_group != NULL) { 3075 // ThreadGroup.name can be null 3076 return java_lang_ThreadGroup::name(thread_group); 3077 } 3078 } 3079 return NULL; 3080 } 3081 3082 const char* JavaThread::get_parent_name() const { 3083 debug_only(if (JavaThread::current() != this) assert_locked_or_safepoint(Threads_lock);) 3084 oop thread_obj = threadObj(); 3085 if (thread_obj != NULL) { 3086 oop thread_group = java_lang_Thread::threadGroup(thread_obj); 3087 if (thread_group != NULL) { 3088 oop parent = java_lang_ThreadGroup::parent(thread_group); 3089 if (parent != NULL) { 3090 // ThreadGroup.name can be null 3091 return java_lang_ThreadGroup::name(parent); 3092 } 3093 } 3094 } 3095 return NULL; 3096 } 3097 3098 ThreadPriority JavaThread::java_priority() const { 3099 oop thr_oop = threadObj(); 3100 if (thr_oop == NULL) return NormPriority; // Bootstrapping 3101 ThreadPriority priority = java_lang_Thread::priority(thr_oop); 3102 assert(MinPriority <= priority && priority <= MaxPriority, "sanity check"); 3103 return priority; 3104 } 3105 3106 void JavaThread::prepare(jobject jni_thread, ThreadPriority prio) { 3107 3108 assert(Threads_lock->owner() == Thread::current(), "must have threads lock"); 3109 // Link Java Thread object <-> C++ Thread 3110 3111 // Get the C++ thread object (an oop) from the JNI handle (a jthread) 3112 // and put it into a new Handle. The Handle "thread_oop" can then 3113 // be used to pass the C++ thread object to other methods. 3114 3115 // Set the Java level thread object (jthread) field of the 3116 // new thread (a JavaThread *) to C++ thread object using the 3117 // "thread_oop" handle. 3118 3119 // Set the thread field (a JavaThread *) of the 3120 // oop representing the java_lang_Thread to the new thread (a JavaThread *). 3121 3122 Handle thread_oop(Thread::current(), 3123 JNIHandles::resolve_non_null(jni_thread)); 3124 assert(InstanceKlass::cast(thread_oop->klass())->is_linked(), 3125 "must be initialized"); 3126 set_threadObj(thread_oop()); 3127 java_lang_Thread::set_thread(thread_oop(), this); 3128 3129 if (prio == NoPriority) { 3130 prio = java_lang_Thread::priority(thread_oop()); 3131 assert(prio != NoPriority, "A valid priority should be present"); 3132 } 3133 3134 // Push the Java priority down to the native thread; needs Threads_lock 3135 Thread::set_priority(this, prio); 3136 3137 // Add the new thread to the Threads list and set it in motion. 3138 // We must have threads lock in order to call Threads::add. 3139 // It is crucial that we do not block before the thread is 3140 // added to the Threads list for if a GC happens, then the java_thread oop 3141 // will not be visited by GC. 3142 Threads::add(this); 3143 } 3144 3145 oop JavaThread::current_park_blocker() { 3146 // Support for JSR-166 locks 3147 oop thread_oop = threadObj(); 3148 if (thread_oop != NULL && 3149 JDK_Version::current().supports_thread_park_blocker()) { 3150 return java_lang_Thread::park_blocker(thread_oop); 3151 } 3152 return NULL; 3153 } 3154 3155 3156 void JavaThread::print_stack_on(outputStream* st) { 3157 if (!has_last_Java_frame()) return; 3158 ResourceMark rm; 3159 HandleMark hm; 3160 3161 RegisterMap reg_map(this); 3162 vframe* start_vf = last_java_vframe(®_map); 3163 int count = 0; 3164 for (vframe* f = start_vf; f != NULL; f = f->sender()) { 3165 if (f->is_java_frame()) { 3166 javaVFrame* jvf = javaVFrame::cast(f); 3167 java_lang_Throwable::print_stack_element(st, jvf->method(), jvf->bci()); 3168 3169 // Print out lock information 3170 if (JavaMonitorsInStackTrace) { 3171 jvf->print_lock_info_on(st, count); 3172 } 3173 } else { 3174 // Ignore non-Java frames 3175 } 3176 3177 // Bail-out case for too deep stacks if MaxJavaStackTraceDepth > 0 3178 count++; 3179 if (MaxJavaStackTraceDepth > 0 && MaxJavaStackTraceDepth == count) return; 3180 } 3181 } 3182 3183 3184 // JVMTI PopFrame support 3185 void JavaThread::popframe_preserve_args(ByteSize size_in_bytes, void* start) { 3186 assert(_popframe_preserved_args == NULL, "should not wipe out old PopFrame preserved arguments"); 3187 if (in_bytes(size_in_bytes) != 0) { 3188 _popframe_preserved_args = NEW_C_HEAP_ARRAY(char, in_bytes(size_in_bytes), mtThread); 3189 _popframe_preserved_args_size = in_bytes(size_in_bytes); 3190 Copy::conjoint_jbytes(start, _popframe_preserved_args, _popframe_preserved_args_size); 3191 } 3192 } 3193 3194 void* JavaThread::popframe_preserved_args() { 3195 return _popframe_preserved_args; 3196 } 3197 3198 ByteSize JavaThread::popframe_preserved_args_size() { 3199 return in_ByteSize(_popframe_preserved_args_size); 3200 } 3201 3202 WordSize JavaThread::popframe_preserved_args_size_in_words() { 3203 int sz = in_bytes(popframe_preserved_args_size()); 3204 assert(sz % wordSize == 0, "argument size must be multiple of wordSize"); 3205 return in_WordSize(sz / wordSize); 3206 } 3207 3208 void JavaThread::popframe_free_preserved_args() { 3209 assert(_popframe_preserved_args != NULL, "should not free PopFrame preserved arguments twice"); 3210 FREE_C_HEAP_ARRAY(char, (char*) _popframe_preserved_args); 3211 _popframe_preserved_args = NULL; 3212 _popframe_preserved_args_size = 0; 3213 } 3214 3215 #ifndef PRODUCT 3216 3217 void JavaThread::trace_frames() { 3218 tty->print_cr("[Describe stack]"); 3219 int frame_no = 1; 3220 for (StackFrameStream fst(this); !fst.is_done(); fst.next()) { 3221 tty->print(" %d. ", frame_no++); 3222 fst.current()->print_value_on(tty, this); 3223 tty->cr(); 3224 } 3225 } 3226 3227 class PrintAndVerifyOopClosure: public OopClosure { 3228 protected: 3229 template <class T> inline void do_oop_work(T* p) { 3230 oop obj = RawAccess<>::oop_load(p); 3231 if (obj == NULL) return; 3232 tty->print(INTPTR_FORMAT ": ", p2i(p)); 3233 if (oopDesc::is_oop_or_null(obj)) { 3234 if (obj->is_objArray()) { 3235 tty->print_cr("valid objArray: " INTPTR_FORMAT, p2i(obj)); 3236 } else { 3237 obj->print(); 3238 } 3239 } else { 3240 tty->print_cr("invalid oop: " INTPTR_FORMAT, p2i(obj)); 3241 } 3242 tty->cr(); 3243 } 3244 public: 3245 virtual void do_oop(oop* p) { do_oop_work(p); } 3246 virtual void do_oop(narrowOop* p) { do_oop_work(p); } 3247 }; 3248 3249 3250 static void oops_print(frame* f, const RegisterMap *map) { 3251 PrintAndVerifyOopClosure print; 3252 f->print_value(); 3253 f->oops_do(&print, NULL, (RegisterMap*)map); 3254 } 3255 3256 // Print our all the locations that contain oops and whether they are 3257 // valid or not. This useful when trying to find the oldest frame 3258 // where an oop has gone bad since the frame walk is from youngest to 3259 // oldest. 3260 void JavaThread::trace_oops() { 3261 tty->print_cr("[Trace oops]"); 3262 frames_do(oops_print); 3263 } 3264 3265 3266 #ifdef ASSERT 3267 // Print or validate the layout of stack frames 3268 void JavaThread::print_frame_layout(int depth, bool validate_only) { 3269 ResourceMark rm; 3270 PRESERVE_EXCEPTION_MARK; 3271 FrameValues values; 3272 int frame_no = 0; 3273 for (StackFrameStream fst(this, false); !fst.is_done(); fst.next()) { 3274 fst.current()->describe(values, ++frame_no); 3275 if (depth == frame_no) break; 3276 } 3277 if (validate_only) { 3278 values.validate(); 3279 } else { 3280 tty->print_cr("[Describe stack layout]"); 3281 values.print(this); 3282 } 3283 } 3284 #endif 3285 3286 void JavaThread::trace_stack_from(vframe* start_vf) { 3287 ResourceMark rm; 3288 int vframe_no = 1; 3289 for (vframe* f = start_vf; f; f = f->sender()) { 3290 if (f->is_java_frame()) { 3291 javaVFrame::cast(f)->print_activation(vframe_no++); 3292 } else { 3293 f->print(); 3294 } 3295 if (vframe_no > StackPrintLimit) { 3296 tty->print_cr("...<more frames>..."); 3297 return; 3298 } 3299 } 3300 } 3301 3302 3303 void JavaThread::trace_stack() { 3304 if (!has_last_Java_frame()) return; 3305 ResourceMark rm; 3306 HandleMark hm; 3307 RegisterMap reg_map(this); 3308 trace_stack_from(last_java_vframe(®_map)); 3309 } 3310 3311 3312 #endif // PRODUCT 3313 3314 3315 javaVFrame* JavaThread::last_java_vframe(RegisterMap *reg_map) { 3316 assert(reg_map != NULL, "a map must be given"); 3317 frame f = last_frame(); 3318 for (vframe* vf = vframe::new_vframe(&f, reg_map, this); vf; vf = vf->sender()) { 3319 if (vf->is_java_frame()) return javaVFrame::cast(vf); 3320 } 3321 return NULL; 3322 } 3323 3324 3325 Klass* JavaThread::security_get_caller_class(int depth) { 3326 vframeStream vfst(this); 3327 vfst.security_get_caller_frame(depth); 3328 if (!vfst.at_end()) { 3329 return vfst.method()->method_holder(); 3330 } 3331 return NULL; 3332 } 3333 3334 static void compiler_thread_entry(JavaThread* thread, TRAPS) { 3335 assert(thread->is_Compiler_thread(), "must be compiler thread"); 3336 CompileBroker::compiler_thread_loop(); 3337 } 3338 3339 static void sweeper_thread_entry(JavaThread* thread, TRAPS) { 3340 NMethodSweeper::sweeper_loop(); 3341 } 3342 3343 // Create a CompilerThread 3344 CompilerThread::CompilerThread(CompileQueue* queue, 3345 CompilerCounters* counters) 3346 : JavaThread(&compiler_thread_entry) { 3347 _env = NULL; 3348 _log = NULL; 3349 _task = NULL; 3350 _queue = queue; 3351 _counters = counters; 3352 _buffer_blob = NULL; 3353 _compiler = NULL; 3354 3355 // Compiler uses resource area for compilation, let's bias it to mtCompiler 3356 resource_area()->bias_to(mtCompiler); 3357 3358 #ifndef PRODUCT 3359 _ideal_graph_printer = NULL; 3360 #endif 3361 } 3362 3363 CompilerThread::~CompilerThread() { 3364 // Delete objects which were allocated on heap. 3365 delete _counters; 3366 } 3367 3368 bool CompilerThread::can_call_java() const { 3369 return _compiler != NULL && _compiler->is_jvmci(); 3370 } 3371 3372 // Create sweeper thread 3373 CodeCacheSweeperThread::CodeCacheSweeperThread() 3374 : JavaThread(&sweeper_thread_entry) { 3375 _scanned_compiled_method = NULL; 3376 } 3377 3378 void CodeCacheSweeperThread::oops_do(OopClosure* f, CodeBlobClosure* cf) { 3379 JavaThread::oops_do(f, cf); 3380 if (_scanned_compiled_method != NULL && cf != NULL) { 3381 // Safepoints can occur when the sweeper is scanning an nmethod so 3382 // process it here to make sure it isn't unloaded in the middle of 3383 // a scan. 3384 cf->do_code_blob(_scanned_compiled_method); 3385 } 3386 } 3387 3388 void CodeCacheSweeperThread::nmethods_do(CodeBlobClosure* cf) { 3389 JavaThread::nmethods_do(cf); 3390 if (_scanned_compiled_method != NULL && cf != NULL) { 3391 // Safepoints can occur when the sweeper is scanning an nmethod so 3392 // process it here to make sure it isn't unloaded in the middle of 3393 // a scan. 3394 cf->do_code_blob(_scanned_compiled_method); 3395 } 3396 } 3397 3398 3399 // ======= Threads ======== 3400 3401 // The Threads class links together all active threads, and provides 3402 // operations over all threads. It is protected by the Threads_lock, 3403 // which is also used in other global contexts like safepointing. 3404 // ThreadsListHandles are used to safely perform operations on one 3405 // or more threads without the risk of the thread exiting during the 3406 // operation. 3407 // 3408 // Note: The Threads_lock is currently more widely used than we 3409 // would like. We are actively migrating Threads_lock uses to other 3410 // mechanisms in order to reduce Threads_lock contention. 3411 3412 JavaThread* Threads::_thread_list = NULL; 3413 int Threads::_number_of_threads = 0; 3414 int Threads::_number_of_non_daemon_threads = 0; 3415 int Threads::_return_code = 0; 3416 int Threads::_thread_claim_parity = 0; 3417 size_t JavaThread::_stack_size_at_create = 0; 3418 3419 #ifdef ASSERT 3420 bool Threads::_vm_complete = false; 3421 size_t Threads::_threads_before_barrier_set = 0; 3422 #endif 3423 3424 static inline void *prefetch_and_load_ptr(void **addr, intx prefetch_interval) { 3425 Prefetch::read((void*)addr, prefetch_interval); 3426 return *addr; 3427 } 3428 3429 // Possibly the ugliest for loop the world has seen. C++ does not allow 3430 // multiple types in the declaration section of the for loop. In this case 3431 // we are only dealing with pointers and hence can cast them. It looks ugly 3432 // but macros are ugly and therefore it's fine to make things absurdly ugly. 3433 #define DO_JAVA_THREADS(LIST, X) \ 3434 for (JavaThread *MACRO_scan_interval = (JavaThread*)(uintptr_t)PrefetchScanIntervalInBytes, \ 3435 *MACRO_list = (JavaThread*)(LIST), \ 3436 **MACRO_end = ((JavaThread**)((ThreadsList*)MACRO_list)->threads()) + ((ThreadsList*)MACRO_list)->length(), \ 3437 **MACRO_current_p = (JavaThread**)((ThreadsList*)MACRO_list)->threads(), \ 3438 *X = (JavaThread*)prefetch_and_load_ptr((void**)MACRO_current_p, (intx)MACRO_scan_interval); \ 3439 MACRO_current_p != MACRO_end; \ 3440 MACRO_current_p++, \ 3441 X = (JavaThread*)prefetch_and_load_ptr((void**)MACRO_current_p, (intx)MACRO_scan_interval)) 3442 3443 // All JavaThreads 3444 #define ALL_JAVA_THREADS(X) DO_JAVA_THREADS(ThreadsSMRSupport::get_java_thread_list(), X) 3445 3446 // All NonJavaThreads (i.e., every non-JavaThread in the system). 3447 void Threads::non_java_threads_do(ThreadClosure* tc) { 3448 NoSafepointVerifier nsv(!SafepointSynchronize::is_at_safepoint(), false); 3449 for (NonJavaThread::Iterator njti; !njti.end(); njti.step()) { 3450 tc->do_thread(njti.current()); 3451 } 3452 } 3453 3454 // All JavaThreads 3455 void Threads::java_threads_do(ThreadClosure* tc) { 3456 assert_locked_or_safepoint(Threads_lock); 3457 // ALL_JAVA_THREADS iterates through all JavaThreads. 3458 ALL_JAVA_THREADS(p) { 3459 tc->do_thread(p); 3460 } 3461 } 3462 3463 void Threads::java_threads_and_vm_thread_do(ThreadClosure* tc) { 3464 assert_locked_or_safepoint(Threads_lock); 3465 java_threads_do(tc); 3466 tc->do_thread(VMThread::vm_thread()); 3467 } 3468 3469 // All JavaThreads + all non-JavaThreads (i.e., every thread in the system). 3470 void Threads::threads_do(ThreadClosure* tc) { 3471 assert_locked_or_safepoint(Threads_lock); 3472 java_threads_do(tc); 3473 non_java_threads_do(tc); 3474 } 3475 3476 void Threads::possibly_parallel_threads_do(bool is_par, ThreadClosure* tc) { 3477 int cp = Threads::thread_claim_parity(); 3478 ALL_JAVA_THREADS(p) { 3479 if (p->claim_oops_do(is_par, cp)) { 3480 tc->do_thread(p); 3481 } 3482 } 3483 VMThread* vmt = VMThread::vm_thread(); 3484 if (vmt->claim_oops_do(is_par, cp)) { 3485 tc->do_thread(vmt); 3486 } 3487 } 3488 3489 // The system initialization in the library has three phases. 3490 // 3491 // Phase 1: java.lang.System class initialization 3492 // java.lang.System is a primordial class loaded and initialized 3493 // by the VM early during startup. java.lang.System.<clinit> 3494 // only does registerNatives and keeps the rest of the class 3495 // initialization work later until thread initialization completes. 3496 // 3497 // System.initPhase1 initializes the system properties, the static 3498 // fields in, out, and err. Set up java signal handlers, OS-specific 3499 // system settings, and thread group of the main thread. 3500 static void call_initPhase1(TRAPS) { 3501 Klass* klass = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_System(), true, CHECK); 3502 JavaValue result(T_VOID); 3503 JavaCalls::call_static(&result, klass, vmSymbols::initPhase1_name(), 3504 vmSymbols::void_method_signature(), CHECK); 3505 } 3506 3507 // Phase 2. Module system initialization 3508 // This will initialize the module system. Only java.base classes 3509 // can be loaded until phase 2 completes. 3510 // 3511 // Call System.initPhase2 after the compiler initialization and jsr292 3512 // classes get initialized because module initialization runs a lot of java 3513 // code, that for performance reasons, should be compiled. Also, this will 3514 // enable the startup code to use lambda and other language features in this 3515 // phase and onward. 3516 // 3517 // After phase 2, The VM will begin search classes from -Xbootclasspath/a. 3518 static void call_initPhase2(TRAPS) { 3519 TraceTime timer("Initialize module system", TRACETIME_LOG(Info, startuptime)); 3520 3521 Klass* klass = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_System(), true, CHECK); 3522 3523 JavaValue result(T_INT); 3524 JavaCallArguments args; 3525 args.push_int(DisplayVMOutputToStderr); 3526 args.push_int(log_is_enabled(Debug, init)); // print stack trace if exception thrown 3527 JavaCalls::call_static(&result, klass, vmSymbols::initPhase2_name(), 3528 vmSymbols::boolean_boolean_int_signature(), &args, CHECK); 3529 if (result.get_jint() != JNI_OK) { 3530 vm_exit_during_initialization(); // no message or exception 3531 } 3532 3533 universe_post_module_init(); 3534 } 3535 3536 // Phase 3. final setup - set security manager, system class loader and TCCL 3537 // 3538 // This will instantiate and set the security manager, set the system class 3539 // loader as well as the thread context class loader. The security manager 3540 // and system class loader may be a custom class loaded from -Xbootclasspath/a, 3541 // other modules or the application's classpath. 3542 static void call_initPhase3(TRAPS) { 3543 Klass* klass = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_System(), true, CHECK); 3544 JavaValue result(T_VOID); 3545 JavaCalls::call_static(&result, klass, vmSymbols::initPhase3_name(), 3546 vmSymbols::void_method_signature(), CHECK); 3547 } 3548 3549 void Threads::initialize_java_lang_classes(JavaThread* main_thread, TRAPS) { 3550 TraceTime timer("Initialize java.lang classes", TRACETIME_LOG(Info, startuptime)); 3551 3552 if (EagerXrunInit && Arguments::init_libraries_at_startup()) { 3553 create_vm_init_libraries(); 3554 } 3555 3556 initialize_class(vmSymbols::java_lang_String(), CHECK); 3557 3558 // Inject CompactStrings value after the static initializers for String ran. 3559 java_lang_String::set_compact_strings(CompactStrings); 3560 3561 // Initialize java_lang.System (needed before creating the thread) 3562 initialize_class(vmSymbols::java_lang_System(), CHECK); 3563 // The VM creates & returns objects of this class. Make sure it's initialized. 3564 initialize_class(vmSymbols::java_lang_Class(), CHECK); 3565 initialize_class(vmSymbols::java_lang_ThreadGroup(), CHECK); 3566 Handle thread_group = create_initial_thread_group(CHECK); 3567 Universe::set_main_thread_group(thread_group()); 3568 initialize_class(vmSymbols::java_lang_Thread(), CHECK); 3569 oop thread_object = create_initial_thread(thread_group, main_thread, CHECK); 3570 main_thread->set_threadObj(thread_object); 3571 // Set thread status to running since main thread has 3572 // been started and running. 3573 java_lang_Thread::set_thread_status(thread_object, 3574 java_lang_Thread::RUNNABLE); 3575 3576 // The VM creates objects of this class. 3577 initialize_class(vmSymbols::java_lang_Module(), CHECK); 3578 3579 // The VM preresolves methods to these classes. Make sure that they get initialized 3580 initialize_class(vmSymbols::java_lang_reflect_Method(), CHECK); 3581 initialize_class(vmSymbols::java_lang_ref_Finalizer(), CHECK); 3582 3583 // Phase 1 of the system initialization in the library, java.lang.System class initialization 3584 call_initPhase1(CHECK); 3585 3586 // get the Java runtime name after java.lang.System is initialized 3587 JDK_Version::set_runtime_name(get_java_runtime_name(THREAD)); 3588 JDK_Version::set_runtime_version(get_java_runtime_version(THREAD)); 3589 3590 // an instance of OutOfMemory exception has been allocated earlier 3591 initialize_class(vmSymbols::java_lang_OutOfMemoryError(), CHECK); 3592 initialize_class(vmSymbols::java_lang_NullPointerException(), CHECK); 3593 initialize_class(vmSymbols::java_lang_ClassCastException(), CHECK); 3594 initialize_class(vmSymbols::java_lang_ArrayStoreException(), CHECK); 3595 initialize_class(vmSymbols::java_lang_ArithmeticException(), CHECK); 3596 initialize_class(vmSymbols::java_lang_StackOverflowError(), CHECK); 3597 initialize_class(vmSymbols::java_lang_IllegalMonitorStateException(), CHECK); 3598 initialize_class(vmSymbols::java_lang_IllegalArgumentException(), CHECK); 3599 } 3600 3601 void Threads::initialize_jsr292_core_classes(TRAPS) { 3602 TraceTime timer("Initialize java.lang.invoke classes", TRACETIME_LOG(Info, startuptime)); 3603 3604 initialize_class(vmSymbols::java_lang_invoke_MethodHandle(), CHECK); 3605 initialize_class(vmSymbols::java_lang_invoke_ResolvedMethodName(), CHECK); 3606 initialize_class(vmSymbols::java_lang_invoke_MemberName(), CHECK); 3607 initialize_class(vmSymbols::java_lang_invoke_MethodHandleNatives(), CHECK); 3608 } 3609 3610 jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) { 3611 extern void JDK_Version_init(); 3612 3613 // Preinitialize version info. 3614 VM_Version::early_initialize(); 3615 3616 // Check version 3617 if (!is_supported_jni_version(args->version)) return JNI_EVERSION; 3618 3619 // Initialize library-based TLS 3620 ThreadLocalStorage::init(); 3621 3622 // Initialize the output stream module 3623 ostream_init(); 3624 3625 // Process java launcher properties. 3626 Arguments::process_sun_java_launcher_properties(args); 3627 3628 // Initialize the os module 3629 os::init(); 3630 3631 // Record VM creation timing statistics 3632 TraceVmCreationTime create_vm_timer; 3633 create_vm_timer.start(); 3634 3635 // Initialize system properties. 3636 Arguments::init_system_properties(); 3637 3638 // So that JDK version can be used as a discriminator when parsing arguments 3639 JDK_Version_init(); 3640 3641 // Update/Initialize System properties after JDK version number is known 3642 Arguments::init_version_specific_system_properties(); 3643 3644 // Make sure to initialize log configuration *before* parsing arguments 3645 LogConfiguration::initialize(create_vm_timer.begin_time()); 3646 3647 // Parse arguments 3648 // Note: this internally calls os::init_container_support() 3649 jint parse_result = Arguments::parse(args); 3650 if (parse_result != JNI_OK) return parse_result; 3651 3652 os::init_before_ergo(); 3653 3654 jint ergo_result = Arguments::apply_ergo(); 3655 if (ergo_result != JNI_OK) return ergo_result; 3656 3657 // Final check of all ranges after ergonomics which may change values. 3658 if (!JVMFlagRangeList::check_ranges()) { 3659 return JNI_EINVAL; 3660 } 3661 3662 // Final check of all 'AfterErgo' constraints after ergonomics which may change values. 3663 bool constraint_result = JVMFlagConstraintList::check_constraints(JVMFlagConstraint::AfterErgo); 3664 if (!constraint_result) { 3665 return JNI_EINVAL; 3666 } 3667 3668 JVMFlagWriteableList::mark_startup(); 3669 3670 if (PauseAtStartup) { 3671 os::pause(); 3672 } 3673 3674 HOTSPOT_VM_INIT_BEGIN(); 3675 3676 // Timing (must come after argument parsing) 3677 TraceTime timer("Create VM", TRACETIME_LOG(Info, startuptime)); 3678 3679 #ifdef CAN_SHOW_REGISTERS_ON_ASSERT 3680 // Initialize assert poison page mechanism. 3681 if (ShowRegistersOnAssert) { 3682 initialize_assert_poison(); 3683 } 3684 #endif // CAN_SHOW_REGISTERS_ON_ASSERT 3685 3686 // Initialize the os module after parsing the args 3687 jint os_init_2_result = os::init_2(); 3688 if (os_init_2_result != JNI_OK) return os_init_2_result; 3689 3690 SafepointMechanism::initialize(); 3691 3692 jint adjust_after_os_result = Arguments::adjust_after_os(); 3693 if (adjust_after_os_result != JNI_OK) return adjust_after_os_result; 3694 3695 // Initialize output stream logging 3696 ostream_init_log(); 3697 3698 // Convert -Xrun to -agentlib: if there is no JVM_OnLoad 3699 // Must be before create_vm_init_agents() 3700 if (Arguments::init_libraries_at_startup()) { 3701 convert_vm_init_libraries_to_agents(); 3702 } 3703 3704 // Launch -agentlib/-agentpath and converted -Xrun agents 3705 if (Arguments::init_agents_at_startup()) { 3706 create_vm_init_agents(); 3707 } 3708 3709 // Initialize Threads state 3710 _thread_list = NULL; 3711 _number_of_threads = 0; 3712 _number_of_non_daemon_threads = 0; 3713 3714 // Initialize global data structures and create system classes in heap 3715 vm_init_globals(); 3716 3717 #if INCLUDE_JVMCI 3718 if (JVMCICounterSize > 0) { 3719 JavaThread::_jvmci_old_thread_counters = NEW_C_HEAP_ARRAY(jlong, JVMCICounterSize, mtInternal); 3720 memset(JavaThread::_jvmci_old_thread_counters, 0, sizeof(jlong) * JVMCICounterSize); 3721 } else { 3722 JavaThread::_jvmci_old_thread_counters = NULL; 3723 } 3724 #endif // INCLUDE_JVMCI 3725 3726 // Attach the main thread to this os thread 3727 JavaThread* main_thread = new JavaThread(); 3728 main_thread->set_thread_state(_thread_in_vm); 3729 main_thread->initialize_thread_current(); 3730 // must do this before set_active_handles 3731 main_thread->record_stack_base_and_size(); 3732 main_thread->register_thread_stack_with_NMT(); 3733 main_thread->set_active_handles(JNIHandleBlock::allocate_block()); 3734 3735 if (!main_thread->set_as_starting_thread()) { 3736 vm_shutdown_during_initialization( 3737 "Failed necessary internal allocation. Out of swap space"); 3738 main_thread->smr_delete(); 3739 *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again 3740 return JNI_ENOMEM; 3741 } 3742 3743 // Enable guard page *after* os::create_main_thread(), otherwise it would 3744 // crash Linux VM, see notes in os_linux.cpp. 3745 main_thread->create_stack_guard_pages(); 3746 3747 // Initialize Java-Level synchronization subsystem 3748 ObjectMonitor::Initialize(); 3749 3750 // Initialize global modules 3751 jint status = init_globals(); 3752 if (status != JNI_OK) { 3753 main_thread->smr_delete(); 3754 *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again 3755 return status; 3756 } 3757 3758 JFR_ONLY(Jfr::on_vm_init();) 3759 3760 // Should be done after the heap is fully created 3761 main_thread->cache_global_variables(); 3762 3763 HandleMark hm; 3764 3765 { MutexLocker mu(Threads_lock); 3766 Threads::add(main_thread); 3767 } 3768 3769 // Any JVMTI raw monitors entered in onload will transition into 3770 // real raw monitor. VM is setup enough here for raw monitor enter. 3771 JvmtiExport::transition_pending_onload_raw_monitors(); 3772 3773 // Create the VMThread 3774 { TraceTime timer("Start VMThread", TRACETIME_LOG(Info, startuptime)); 3775 3776 VMThread::create(); 3777 Thread* vmthread = VMThread::vm_thread(); 3778 3779 if (!os::create_thread(vmthread, os::vm_thread)) { 3780 vm_exit_during_initialization("Cannot create VM thread. " 3781 "Out of system resources."); 3782 } 3783 3784 // Wait for the VM thread to become ready, and VMThread::run to initialize 3785 // Monitors can have spurious returns, must always check another state flag 3786 { 3787 MutexLocker ml(Notify_lock); 3788 os::start_thread(vmthread); 3789 while (vmthread->active_handles() == NULL) { 3790 Notify_lock->wait(); 3791 } 3792 } 3793 } 3794 3795 assert(Universe::is_fully_initialized(), "not initialized"); 3796 if (VerifyDuringStartup) { 3797 // Make sure we're starting with a clean slate. 3798 VM_Verify verify_op; 3799 VMThread::execute(&verify_op); 3800 } 3801 3802 // We need this to update the java.vm.info property in case any flags used 3803 // to initially define it have been changed. This is needed for both CDS and 3804 // AOT, since UseSharedSpaces and UseAOT may be changed after java.vm.info 3805 // is initially computed. See Abstract_VM_Version::vm_info_string(). 3806 // This update must happen before we initialize the java classes, but 3807 // after any initialization logic that might modify the flags. 3808 Arguments::update_vm_info_property(VM_Version::vm_info_string()); 3809 3810 Thread* THREAD = Thread::current(); 3811 3812 // Always call even when there are not JVMTI environments yet, since environments 3813 // may be attached late and JVMTI must track phases of VM execution 3814 JvmtiExport::enter_early_start_phase(); 3815 3816 // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents. 3817 JvmtiExport::post_early_vm_start(); 3818 3819 initialize_java_lang_classes(main_thread, CHECK_JNI_ERR); 3820 3821 quicken_jni_functions(); 3822 3823 // No more stub generation allowed after that point. 3824 StubCodeDesc::freeze(); 3825 3826 // Set flag that basic initialization has completed. Used by exceptions and various 3827 // debug stuff, that does not work until all basic classes have been initialized. 3828 set_init_completed(); 3829 3830 LogConfiguration::post_initialize(); 3831 Metaspace::post_initialize(); 3832 3833 HOTSPOT_VM_INIT_END(); 3834 3835 // record VM initialization completion time 3836 #if INCLUDE_MANAGEMENT 3837 Management::record_vm_init_completed(); 3838 #endif // INCLUDE_MANAGEMENT 3839 3840 // Signal Dispatcher needs to be started before VMInit event is posted 3841 os::initialize_jdk_signal_support(CHECK_JNI_ERR); 3842 3843 // Start Attach Listener if +StartAttachListener or it can't be started lazily 3844 if (!DisableAttachMechanism) { 3845 AttachListener::vm_start(); 3846 if (StartAttachListener || AttachListener::init_at_startup()) { 3847 AttachListener::init(); 3848 } 3849 } 3850 3851 // Launch -Xrun agents 3852 // Must be done in the JVMTI live phase so that for backward compatibility the JDWP 3853 // back-end can launch with -Xdebug -Xrunjdwp. 3854 if (!EagerXrunInit && Arguments::init_libraries_at_startup()) { 3855 create_vm_init_libraries(); 3856 } 3857 3858 if (CleanChunkPoolAsync) { 3859 Chunk::start_chunk_pool_cleaner_task(); 3860 } 3861 3862 // initialize compiler(s) 3863 #if defined(COMPILER1) || COMPILER2_OR_JVMCI 3864 #if INCLUDE_JVMCI 3865 bool force_JVMCI_intialization = false; 3866 if (EnableJVMCI) { 3867 // Initialize JVMCI eagerly when it is explicitly requested. 3868 // Or when JVMCIPrintProperties is enabled. 3869 // The JVMCI Java initialization code will read this flag and 3870 // do the printing if it's set. 3871 force_JVMCI_intialization = EagerJVMCI || JVMCIPrintProperties; 3872 3873 if (!force_JVMCI_intialization) { 3874 // 8145270: Force initialization of JVMCI runtime otherwise requests for blocking 3875 // compilations via JVMCI will not actually block until JVMCI is initialized. 3876 force_JVMCI_intialization = UseJVMCICompiler && (!UseInterpreter || !BackgroundCompilation); 3877 } 3878 } 3879 #endif 3880 CompileBroker::compilation_init_phase1(CHECK_JNI_ERR); 3881 // Postpone completion of compiler initialization to after JVMCI 3882 // is initialized to avoid timeouts of blocking compilations. 3883 if (JVMCI_ONLY(!force_JVMCI_intialization) NOT_JVMCI(true)) { 3884 CompileBroker::compilation_init_phase2(); 3885 } 3886 #endif 3887 3888 // Pre-initialize some JSR292 core classes to avoid deadlock during class loading. 3889 // It is done after compilers are initialized, because otherwise compilations of 3890 // signature polymorphic MH intrinsics can be missed 3891 // (see SystemDictionary::find_method_handle_intrinsic). 3892 initialize_jsr292_core_classes(CHECK_JNI_ERR); 3893 3894 // This will initialize the module system. Only java.base classes can be 3895 // loaded until phase 2 completes 3896 call_initPhase2(CHECK_JNI_ERR); 3897 3898 // Always call even when there are not JVMTI environments yet, since environments 3899 // may be attached late and JVMTI must track phases of VM execution 3900 JvmtiExport::enter_start_phase(); 3901 3902 // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents. 3903 JvmtiExport::post_vm_start(); 3904 3905 // Final system initialization including security manager and system class loader 3906 call_initPhase3(CHECK_JNI_ERR); 3907 3908 // cache the system and platform class loaders 3909 SystemDictionary::compute_java_loaders(CHECK_JNI_ERR); 3910 3911 #if INCLUDE_CDS 3912 if (DumpSharedSpaces) { 3913 // capture the module path info from the ModuleEntryTable 3914 ClassLoader::initialize_module_path(THREAD); 3915 } 3916 #endif 3917 3918 #if INCLUDE_JVMCI 3919 if (force_JVMCI_intialization) { 3920 JVMCIRuntime::force_initialization(CHECK_JNI_ERR); 3921 CompileBroker::compilation_init_phase2(); 3922 } 3923 #endif 3924 3925 // Always call even when there are not JVMTI environments yet, since environments 3926 // may be attached late and JVMTI must track phases of VM execution 3927 JvmtiExport::enter_live_phase(); 3928 3929 // Notify JVMTI agents that VM initialization is complete - nop if no agents. 3930 JvmtiExport::post_vm_initialized(); 3931 3932 JFR_ONLY(Jfr::on_vm_start();) 3933 3934 #if INCLUDE_MANAGEMENT 3935 Management::initialize(THREAD); 3936 3937 if (HAS_PENDING_EXCEPTION) { 3938 // management agent fails to start possibly due to 3939 // configuration problem and is responsible for printing 3940 // stack trace if appropriate. Simply exit VM. 3941 vm_exit(1); 3942 } 3943 #endif // INCLUDE_MANAGEMENT 3944 3945 if (MemProfiling) MemProfiler::engage(); 3946 StatSampler::engage(); 3947 if (CheckJNICalls) JniPeriodicChecker::engage(); 3948 3949 BiasedLocking::init(); 3950 3951 #if INCLUDE_RTM_OPT 3952 RTMLockingCounters::init(); 3953 #endif 3954 3955 if (JDK_Version::current().post_vm_init_hook_enabled()) { 3956 call_postVMInitHook(THREAD); 3957 // The Java side of PostVMInitHook.run must deal with all 3958 // exceptions and provide means of diagnosis. 3959 if (HAS_PENDING_EXCEPTION) { 3960 CLEAR_PENDING_EXCEPTION; 3961 } 3962 } 3963 3964 { 3965 MutexLocker ml(PeriodicTask_lock); 3966 // Make sure the WatcherThread can be started by WatcherThread::start() 3967 // or by dynamic enrollment. 3968 WatcherThread::make_startable(); 3969 // Start up the WatcherThread if there are any periodic tasks 3970 // NOTE: All PeriodicTasks should be registered by now. If they 3971 // aren't, late joiners might appear to start slowly (we might 3972 // take a while to process their first tick). 3973 if (PeriodicTask::num_tasks() > 0) { 3974 WatcherThread::start(); 3975 } 3976 } 3977 3978 create_vm_timer.end(); 3979 #ifdef ASSERT 3980 _vm_complete = true; 3981 #endif 3982 3983 if (DumpSharedSpaces) { 3984 MetaspaceShared::preload_and_dump(CHECK_JNI_ERR); 3985 ShouldNotReachHere(); 3986 } 3987 3988 return JNI_OK; 3989 } 3990 3991 // type for the Agent_OnLoad and JVM_OnLoad entry points 3992 extern "C" { 3993 typedef jint (JNICALL *OnLoadEntry_t)(JavaVM *, char *, void *); 3994 } 3995 // Find a command line agent library and return its entry point for 3996 // -agentlib: -agentpath: -Xrun 3997 // num_symbol_entries must be passed-in since only the caller knows the number of symbols in the array. 3998 static OnLoadEntry_t lookup_on_load(AgentLibrary* agent, 3999 const char *on_load_symbols[], 4000 size_t num_symbol_entries) { 4001 OnLoadEntry_t on_load_entry = NULL; 4002 void *library = NULL; 4003 4004 if (!agent->valid()) { 4005 char buffer[JVM_MAXPATHLEN]; 4006 char ebuf[1024] = ""; 4007 const char *name = agent->name(); 4008 const char *msg = "Could not find agent library "; 4009 4010 // First check to see if agent is statically linked into executable 4011 if (os::find_builtin_agent(agent, on_load_symbols, num_symbol_entries)) { 4012 library = agent->os_lib(); 4013 } else if (agent->is_absolute_path()) { 4014 library = os::dll_load(name, ebuf, sizeof ebuf); 4015 if (library == NULL) { 4016 const char *sub_msg = " in absolute path, with error: "; 4017 size_t len = strlen(msg) + strlen(name) + strlen(sub_msg) + strlen(ebuf) + 1; 4018 char *buf = NEW_C_HEAP_ARRAY(char, len, mtThread); 4019 jio_snprintf(buf, len, "%s%s%s%s", msg, name, sub_msg, ebuf); 4020 // If we can't find the agent, exit. 4021 vm_exit_during_initialization(buf, NULL); 4022 FREE_C_HEAP_ARRAY(char, buf); 4023 } 4024 } else { 4025 // Try to load the agent from the standard dll directory 4026 if (os::dll_locate_lib(buffer, sizeof(buffer), Arguments::get_dll_dir(), 4027 name)) { 4028 library = os::dll_load(buffer, ebuf, sizeof ebuf); 4029 } 4030 if (library == NULL) { // Try the library path directory. 4031 if (os::dll_build_name(buffer, sizeof(buffer), name)) { 4032 library = os::dll_load(buffer, ebuf, sizeof ebuf); 4033 } 4034 if (library == NULL) { 4035 const char *sub_msg = " on the library path, with error: "; 4036 const char *sub_msg2 = "\nModule java.instrument may be missing from runtime image."; 4037 4038 size_t len = strlen(msg) + strlen(name) + strlen(sub_msg) + 4039 strlen(ebuf) + strlen(sub_msg2) + 1; 4040 char *buf = NEW_C_HEAP_ARRAY(char, len, mtThread); 4041 if (!agent->is_instrument_lib()) { 4042 jio_snprintf(buf, len, "%s%s%s%s", msg, name, sub_msg, ebuf); 4043 } else { 4044 jio_snprintf(buf, len, "%s%s%s%s%s", msg, name, sub_msg, ebuf, sub_msg2); 4045 } 4046 // If we can't find the agent, exit. 4047 vm_exit_during_initialization(buf, NULL); 4048 FREE_C_HEAP_ARRAY(char, buf); 4049 } 4050 } 4051 } 4052 agent->set_os_lib(library); 4053 agent->set_valid(); 4054 } 4055 4056 // Find the OnLoad function. 4057 on_load_entry = 4058 CAST_TO_FN_PTR(OnLoadEntry_t, os::find_agent_function(agent, 4059 false, 4060 on_load_symbols, 4061 num_symbol_entries)); 4062 return on_load_entry; 4063 } 4064 4065 // Find the JVM_OnLoad entry point 4066 static OnLoadEntry_t lookup_jvm_on_load(AgentLibrary* agent) { 4067 const char *on_load_symbols[] = JVM_ONLOAD_SYMBOLS; 4068 return lookup_on_load(agent, on_load_symbols, sizeof(on_load_symbols) / sizeof(char*)); 4069 } 4070 4071 // Find the Agent_OnLoad entry point 4072 static OnLoadEntry_t lookup_agent_on_load(AgentLibrary* agent) { 4073 const char *on_load_symbols[] = AGENT_ONLOAD_SYMBOLS; 4074 return lookup_on_load(agent, on_load_symbols, sizeof(on_load_symbols) / sizeof(char*)); 4075 } 4076 4077 // For backwards compatibility with -Xrun 4078 // Convert libraries with no JVM_OnLoad, but which have Agent_OnLoad to be 4079 // treated like -agentpath: 4080 // Must be called before agent libraries are created 4081 void Threads::convert_vm_init_libraries_to_agents() { 4082 AgentLibrary* agent; 4083 AgentLibrary* next; 4084 4085 for (agent = Arguments::libraries(); agent != NULL; agent = next) { 4086 next = agent->next(); // cache the next agent now as this agent may get moved off this list 4087 OnLoadEntry_t on_load_entry = lookup_jvm_on_load(agent); 4088 4089 // If there is an JVM_OnLoad function it will get called later, 4090 // otherwise see if there is an Agent_OnLoad 4091 if (on_load_entry == NULL) { 4092 on_load_entry = lookup_agent_on_load(agent); 4093 if (on_load_entry != NULL) { 4094 // switch it to the agent list -- so that Agent_OnLoad will be called, 4095 // JVM_OnLoad won't be attempted and Agent_OnUnload will 4096 Arguments::convert_library_to_agent(agent); 4097 } else { 4098 vm_exit_during_initialization("Could not find JVM_OnLoad or Agent_OnLoad function in the library", agent->name()); 4099 } 4100 } 4101 } 4102 } 4103 4104 // Create agents for -agentlib: -agentpath: and converted -Xrun 4105 // Invokes Agent_OnLoad 4106 // Called very early -- before JavaThreads exist 4107 void Threads::create_vm_init_agents() { 4108 extern struct JavaVM_ main_vm; 4109 AgentLibrary* agent; 4110 4111 JvmtiExport::enter_onload_phase(); 4112 4113 for (agent = Arguments::agents(); agent != NULL; agent = agent->next()) { 4114 OnLoadEntry_t on_load_entry = lookup_agent_on_load(agent); 4115 4116 if (on_load_entry != NULL) { 4117 // Invoke the Agent_OnLoad function 4118 jint err = (*on_load_entry)(&main_vm, agent->options(), NULL); 4119 if (err != JNI_OK) { 4120 vm_exit_during_initialization("agent library failed to init", agent->name()); 4121 } 4122 } else { 4123 vm_exit_during_initialization("Could not find Agent_OnLoad function in the agent library", agent->name()); 4124 } 4125 } 4126 JvmtiExport::enter_primordial_phase(); 4127 } 4128 4129 extern "C" { 4130 typedef void (JNICALL *Agent_OnUnload_t)(JavaVM *); 4131 } 4132 4133 void Threads::shutdown_vm_agents() { 4134 // Send any Agent_OnUnload notifications 4135 const char *on_unload_symbols[] = AGENT_ONUNLOAD_SYMBOLS; 4136 size_t num_symbol_entries = ARRAY_SIZE(on_unload_symbols); 4137 extern struct JavaVM_ main_vm; 4138 for (AgentLibrary* agent = Arguments::agents(); agent != NULL; agent = agent->next()) { 4139 4140 // Find the Agent_OnUnload function. 4141 Agent_OnUnload_t unload_entry = CAST_TO_FN_PTR(Agent_OnUnload_t, 4142 os::find_agent_function(agent, 4143 false, 4144 on_unload_symbols, 4145 num_symbol_entries)); 4146 4147 // Invoke the Agent_OnUnload function 4148 if (unload_entry != NULL) { 4149 JavaThread* thread = JavaThread::current(); 4150 ThreadToNativeFromVM ttn(thread); 4151 HandleMark hm(thread); 4152 (*unload_entry)(&main_vm); 4153 } 4154 } 4155 } 4156 4157 // Called for after the VM is initialized for -Xrun libraries which have not been converted to agent libraries 4158 // Invokes JVM_OnLoad 4159 void Threads::create_vm_init_libraries() { 4160 extern struct JavaVM_ main_vm; 4161 AgentLibrary* agent; 4162 4163 for (agent = Arguments::libraries(); agent != NULL; agent = agent->next()) { 4164 OnLoadEntry_t on_load_entry = lookup_jvm_on_load(agent); 4165 4166 if (on_load_entry != NULL) { 4167 // Invoke the JVM_OnLoad function 4168 JavaThread* thread = JavaThread::current(); 4169 ThreadToNativeFromVM ttn(thread); 4170 HandleMark hm(thread); 4171 jint err = (*on_load_entry)(&main_vm, agent->options(), NULL); 4172 if (err != JNI_OK) { 4173 vm_exit_during_initialization("-Xrun library failed to init", agent->name()); 4174 } 4175 } else { 4176 vm_exit_during_initialization("Could not find JVM_OnLoad function in -Xrun library", agent->name()); 4177 } 4178 } 4179 } 4180 4181 4182 // Last thread running calls java.lang.Shutdown.shutdown() 4183 void JavaThread::invoke_shutdown_hooks() { 4184 HandleMark hm(this); 4185 4186 // We could get here with a pending exception, if so clear it now. 4187 if (this->has_pending_exception()) { 4188 this->clear_pending_exception(); 4189 } 4190 4191 EXCEPTION_MARK; 4192 Klass* shutdown_klass = 4193 SystemDictionary::resolve_or_null(vmSymbols::java_lang_Shutdown(), 4194 THREAD); 4195 if (shutdown_klass != NULL) { 4196 // SystemDictionary::resolve_or_null will return null if there was 4197 // an exception. If we cannot load the Shutdown class, just don't 4198 // call Shutdown.shutdown() at all. This will mean the shutdown hooks 4199 // won't be run. Note that if a shutdown hook was registered, 4200 // the Shutdown class would have already been loaded 4201 // (Runtime.addShutdownHook will load it). 4202 JavaValue result(T_VOID); 4203 JavaCalls::call_static(&result, 4204 shutdown_klass, 4205 vmSymbols::shutdown_method_name(), 4206 vmSymbols::void_method_signature(), 4207 THREAD); 4208 } 4209 CLEAR_PENDING_EXCEPTION; 4210 } 4211 4212 // Threads::destroy_vm() is normally called from jni_DestroyJavaVM() when 4213 // the program falls off the end of main(). Another VM exit path is through 4214 // vm_exit() when the program calls System.exit() to return a value or when 4215 // there is a serious error in VM. The two shutdown paths are not exactly 4216 // the same, but they share Shutdown.shutdown() at Java level and before_exit() 4217 // and VM_Exit op at VM level. 4218 // 4219 // Shutdown sequence: 4220 // + Shutdown native memory tracking if it is on 4221 // + Wait until we are the last non-daemon thread to execute 4222 // <-- every thing is still working at this moment --> 4223 // + Call java.lang.Shutdown.shutdown(), which will invoke Java level 4224 // shutdown hooks 4225 // + Call before_exit(), prepare for VM exit 4226 // > run VM level shutdown hooks (they are registered through JVM_OnExit(), 4227 // currently the only user of this mechanism is File.deleteOnExit()) 4228 // > stop StatSampler, watcher thread, CMS threads, 4229 // post thread end and vm death events to JVMTI, 4230 // stop signal thread 4231 // + Call JavaThread::exit(), it will: 4232 // > release JNI handle blocks, remove stack guard pages 4233 // > remove this thread from Threads list 4234 // <-- no more Java code from this thread after this point --> 4235 // + Stop VM thread, it will bring the remaining VM to a safepoint and stop 4236 // the compiler threads at safepoint 4237 // <-- do not use anything that could get blocked by Safepoint --> 4238 // + Disable tracing at JNI/JVM barriers 4239 // + Set _vm_exited flag for threads that are still running native code 4240 // + Call exit_globals() 4241 // > deletes tty 4242 // > deletes PerfMemory resources 4243 // + Delete this thread 4244 // + Return to caller 4245 4246 bool Threads::destroy_vm() { 4247 JavaThread* thread = JavaThread::current(); 4248 4249 #ifdef ASSERT 4250 _vm_complete = false; 4251 #endif 4252 // Wait until we are the last non-daemon thread to execute 4253 { MutexLocker nu(Threads_lock); 4254 while (Threads::number_of_non_daemon_threads() > 1) 4255 // This wait should make safepoint checks, wait without a timeout, 4256 // and wait as a suspend-equivalent condition. 4257 Threads_lock->wait(!Mutex::_no_safepoint_check_flag, 0, 4258 Mutex::_as_suspend_equivalent_flag); 4259 } 4260 4261 EventShutdown e; 4262 if (e.should_commit()) { 4263 e.set_reason("No remaining non-daemon Java threads"); 4264 e.commit(); 4265 } 4266 4267 // Hang forever on exit if we are reporting an error. 4268 if (ShowMessageBoxOnError && VMError::is_error_reported()) { 4269 os::infinite_sleep(); 4270 } 4271 os::wait_for_keypress_at_exit(); 4272 4273 // run Java level shutdown hooks 4274 thread->invoke_shutdown_hooks(); 4275 4276 before_exit(thread); 4277 4278 thread->exit(true); 4279 4280 // Stop VM thread. 4281 { 4282 // 4945125 The vm thread comes to a safepoint during exit. 4283 // GC vm_operations can get caught at the safepoint, and the 4284 // heap is unparseable if they are caught. Grab the Heap_lock 4285 // to prevent this. The GC vm_operations will not be able to 4286 // queue until after the vm thread is dead. After this point, 4287 // we'll never emerge out of the safepoint before the VM exits. 4288 4289 MutexLocker ml(Heap_lock); 4290 4291 VMThread::wait_for_vm_thread_exit(); 4292 assert(SafepointSynchronize::is_at_safepoint(), "VM thread should exit at Safepoint"); 4293 VMThread::destroy(); 4294 } 4295 4296 // Now, all Java threads are gone except daemon threads. Daemon threads 4297 // running Java code or in VM are stopped by the Safepoint. However, 4298 // daemon threads executing native code are still running. But they 4299 // will be stopped at native=>Java/VM barriers. Note that we can't 4300 // simply kill or suspend them, as it is inherently deadlock-prone. 4301 4302 VM_Exit::set_vm_exited(); 4303 4304 // Clean up ideal graph printers after the VMThread has started 4305 // the final safepoint which will block all the Compiler threads. 4306 // Note that this Thread has already logically exited so the 4307 // clean_up() function's use of a JavaThreadIteratorWithHandle 4308 // would be a problem except set_vm_exited() has remembered the 4309 // shutdown thread which is granted a policy exception. 4310 #if defined(COMPILER2) && !defined(PRODUCT) 4311 IdealGraphPrinter::clean_up(); 4312 #endif 4313 4314 notify_vm_shutdown(); 4315 4316 // exit_globals() will delete tty 4317 exit_globals(); 4318 4319 // We are after VM_Exit::set_vm_exited() so we can't call 4320 // thread->smr_delete() or we will block on the Threads_lock. 4321 // Deleting the shutdown thread here is safe because another 4322 // JavaThread cannot have an active ThreadsListHandle for 4323 // this JavaThread. 4324 delete thread; 4325 4326 #if INCLUDE_JVMCI 4327 if (JVMCICounterSize > 0) { 4328 FREE_C_HEAP_ARRAY(jlong, JavaThread::_jvmci_old_thread_counters); 4329 } 4330 #endif 4331 4332 LogConfiguration::finalize(); 4333 4334 return true; 4335 } 4336 4337 4338 jboolean Threads::is_supported_jni_version_including_1_1(jint version) { 4339 if (version == JNI_VERSION_1_1) return JNI_TRUE; 4340 return is_supported_jni_version(version); 4341 } 4342 4343 4344 jboolean Threads::is_supported_jni_version(jint version) { 4345 if (version == JNI_VERSION_1_2) return JNI_TRUE; 4346 if (version == JNI_VERSION_1_4) return JNI_TRUE; 4347 if (version == JNI_VERSION_1_6) return JNI_TRUE; 4348 if (version == JNI_VERSION_1_8) return JNI_TRUE; 4349 if (version == JNI_VERSION_9) return JNI_TRUE; 4350 if (version == JNI_VERSION_10) return JNI_TRUE; 4351 return JNI_FALSE; 4352 } 4353 4354 4355 void Threads::add(JavaThread* p, bool force_daemon) { 4356 // The threads lock must be owned at this point 4357 assert(Threads_lock->owned_by_self(), "must have threads lock"); 4358 4359 BarrierSet::barrier_set()->on_thread_attach(p); 4360 4361 p->set_next(_thread_list); 4362 _thread_list = p; 4363 4364 // Once a JavaThread is added to the Threads list, smr_delete() has 4365 // to be used to delete it. Otherwise we can just delete it directly. 4366 p->set_on_thread_list(); 4367 4368 _number_of_threads++; 4369 oop threadObj = p->threadObj(); 4370 bool daemon = true; 4371 // Bootstrapping problem: threadObj can be null for initial 4372 // JavaThread (or for threads attached via JNI) 4373 if ((!force_daemon) && !is_daemon((threadObj))) { 4374 _number_of_non_daemon_threads++; 4375 daemon = false; 4376 } 4377 4378 ThreadService::add_thread(p, daemon); 4379 4380 // Maintain fast thread list 4381 ThreadsSMRSupport::add_thread(p); 4382 4383 // Possible GC point. 4384 Events::log(p, "Thread added: " INTPTR_FORMAT, p2i(p)); 4385 } 4386 4387 void Threads::remove(JavaThread* p) { 4388 4389 // Reclaim the objectmonitors from the omInUseList and omFreeList of the moribund thread. 4390 ObjectSynchronizer::omFlush(p); 4391 4392 // Extra scope needed for Thread_lock, so we can check 4393 // that we do not remove thread without safepoint code notice 4394 { MutexLocker ml(Threads_lock); 4395 4396 assert(ThreadsSMRSupport::get_java_thread_list()->includes(p), "p must be present"); 4397 4398 // Maintain fast thread list 4399 ThreadsSMRSupport::remove_thread(p); 4400 4401 JavaThread* current = _thread_list; 4402 JavaThread* prev = NULL; 4403 4404 while (current != p) { 4405 prev = current; 4406 current = current->next(); 4407 } 4408 4409 if (prev) { 4410 prev->set_next(current->next()); 4411 } else { 4412 _thread_list = p->next(); 4413 } 4414 4415 _number_of_threads--; 4416 oop threadObj = p->threadObj(); 4417 bool daemon = true; 4418 if (!is_daemon(threadObj)) { 4419 _number_of_non_daemon_threads--; 4420 daemon = false; 4421 4422 // Only one thread left, do a notify on the Threads_lock so a thread waiting 4423 // on destroy_vm will wake up. 4424 if (number_of_non_daemon_threads() == 1) { 4425 Threads_lock->notify_all(); 4426 } 4427 } 4428 ThreadService::remove_thread(p, daemon); 4429 4430 // Make sure that safepoint code disregard this thread. This is needed since 4431 // the thread might mess around with locks after this point. This can cause it 4432 // to do callbacks into the safepoint code. However, the safepoint code is not aware 4433 // of this thread since it is removed from the queue. 4434 p->set_terminated_value(); 4435 } // unlock Threads_lock 4436 4437 // Since Events::log uses a lock, we grab it outside the Threads_lock 4438 Events::log(p, "Thread exited: " INTPTR_FORMAT, p2i(p)); 4439 } 4440 4441 // Operations on the Threads list for GC. These are not explicitly locked, 4442 // but the garbage collector must provide a safe context for them to run. 4443 // In particular, these things should never be called when the Threads_lock 4444 // is held by some other thread. (Note: the Safepoint abstraction also 4445 // uses the Threads_lock to guarantee this property. It also makes sure that 4446 // all threads gets blocked when exiting or starting). 4447 4448 void Threads::oops_do(OopClosure* f, CodeBlobClosure* cf) { 4449 ALL_JAVA_THREADS(p) { 4450 p->oops_do(f, cf); 4451 } 4452 VMThread::vm_thread()->oops_do(f, cf); 4453 } 4454 4455 void Threads::change_thread_claim_parity() { 4456 // Set the new claim parity. 4457 assert(_thread_claim_parity >= 0 && _thread_claim_parity <= 2, 4458 "Not in range."); 4459 _thread_claim_parity++; 4460 if (_thread_claim_parity == 3) _thread_claim_parity = 1; 4461 assert(_thread_claim_parity >= 1 && _thread_claim_parity <= 2, 4462 "Not in range."); 4463 } 4464 4465 #ifdef ASSERT 4466 void Threads::assert_all_threads_claimed() { 4467 ALL_JAVA_THREADS(p) { 4468 const int thread_parity = p->oops_do_parity(); 4469 assert((thread_parity == _thread_claim_parity), 4470 "Thread " PTR_FORMAT " has incorrect parity %d != %d", p2i(p), thread_parity, _thread_claim_parity); 4471 } 4472 VMThread* vmt = VMThread::vm_thread(); 4473 const int thread_parity = vmt->oops_do_parity(); 4474 assert((thread_parity == _thread_claim_parity), 4475 "VMThread " PTR_FORMAT " has incorrect parity %d != %d", p2i(vmt), thread_parity, _thread_claim_parity); 4476 } 4477 #endif // ASSERT 4478 4479 class ParallelOopsDoThreadClosure : public ThreadClosure { 4480 private: 4481 OopClosure* _f; 4482 CodeBlobClosure* _cf; 4483 public: 4484 ParallelOopsDoThreadClosure(OopClosure* f, CodeBlobClosure* cf) : _f(f), _cf(cf) {} 4485 void do_thread(Thread* t) { 4486 t->oops_do(_f, _cf); 4487 } 4488 }; 4489 4490 void Threads::possibly_parallel_oops_do(bool is_par, OopClosure* f, CodeBlobClosure* cf) { 4491 ParallelOopsDoThreadClosure tc(f, cf); 4492 possibly_parallel_threads_do(is_par, &tc); 4493 } 4494 4495 void Threads::nmethods_do(CodeBlobClosure* cf) { 4496 ALL_JAVA_THREADS(p) { 4497 // This is used by the code cache sweeper to mark nmethods that are active 4498 // on the stack of a Java thread. Ignore the sweeper thread itself to avoid 4499 // marking CodeCacheSweeperThread::_scanned_compiled_method as active. 4500 if(!p->is_Code_cache_sweeper_thread()) { 4501 p->nmethods_do(cf); 4502 } 4503 } 4504 } 4505 4506 void Threads::metadata_do(void f(Metadata*)) { 4507 ALL_JAVA_THREADS(p) { 4508 p->metadata_do(f); 4509 } 4510 } 4511 4512 class ThreadHandlesClosure : public ThreadClosure { 4513 void (*_f)(Metadata*); 4514 public: 4515 ThreadHandlesClosure(void f(Metadata*)) : _f(f) {} 4516 virtual void do_thread(Thread* thread) { 4517 thread->metadata_handles_do(_f); 4518 } 4519 }; 4520 4521 void Threads::metadata_handles_do(void f(Metadata*)) { 4522 // Only walk the Handles in Thread. 4523 ThreadHandlesClosure handles_closure(f); 4524 threads_do(&handles_closure); 4525 } 4526 4527 void Threads::deoptimized_wrt_marked_nmethods() { 4528 ALL_JAVA_THREADS(p) { 4529 p->deoptimized_wrt_marked_nmethods(); 4530 } 4531 } 4532 4533 4534 // Get count Java threads that are waiting to enter the specified monitor. 4535 GrowableArray<JavaThread*>* Threads::get_pending_threads(ThreadsList * t_list, 4536 int count, 4537 address monitor) { 4538 GrowableArray<JavaThread*>* result = new GrowableArray<JavaThread*>(count); 4539 4540 int i = 0; 4541 DO_JAVA_THREADS(t_list, p) { 4542 if (!p->can_call_java()) continue; 4543 4544 address pending = (address)p->current_pending_monitor(); 4545 if (pending == monitor) { // found a match 4546 if (i < count) result->append(p); // save the first count matches 4547 i++; 4548 } 4549 } 4550 4551 return result; 4552 } 4553 4554 4555 JavaThread *Threads::owning_thread_from_monitor_owner(ThreadsList * t_list, 4556 address owner) { 4557 // NULL owner means not locked so we can skip the search 4558 if (owner == NULL) return NULL; 4559 4560 DO_JAVA_THREADS(t_list, p) { 4561 // first, see if owner is the address of a Java thread 4562 if (owner == (address)p) return p; 4563 } 4564 4565 // Cannot assert on lack of success here since this function may be 4566 // used by code that is trying to report useful problem information 4567 // like deadlock detection. 4568 if (UseHeavyMonitors) return NULL; 4569 4570 // If we didn't find a matching Java thread and we didn't force use of 4571 // heavyweight monitors, then the owner is the stack address of the 4572 // Lock Word in the owning Java thread's stack. 4573 // 4574 JavaThread* the_owner = NULL; 4575 DO_JAVA_THREADS(t_list, q) { 4576 if (q->is_lock_owned(owner)) { 4577 the_owner = q; 4578 break; 4579 } 4580 } 4581 4582 // cannot assert on lack of success here; see above comment 4583 return the_owner; 4584 } 4585 4586 // Threads::print_on() is called at safepoint by VM_PrintThreads operation. 4587 void Threads::print_on(outputStream* st, bool print_stacks, 4588 bool internal_format, bool print_concurrent_locks, 4589 bool print_extended_info) { 4590 char buf[32]; 4591 st->print_raw_cr(os::local_time_string(buf, sizeof(buf))); 4592 4593 st->print_cr("Full thread dump %s (%s %s):", 4594 VM_Version::vm_name(), 4595 VM_Version::vm_release(), 4596 VM_Version::vm_info_string()); 4597 st->cr(); 4598 4599 #if INCLUDE_SERVICES 4600 // Dump concurrent locks 4601 ConcurrentLocksDump concurrent_locks; 4602 if (print_concurrent_locks) { 4603 concurrent_locks.dump_at_safepoint(); 4604 } 4605 #endif // INCLUDE_SERVICES 4606 4607 ThreadsSMRSupport::print_info_on(st); 4608 st->cr(); 4609 4610 ALL_JAVA_THREADS(p) { 4611 ResourceMark rm; 4612 p->print_on(st, print_extended_info); 4613 if (print_stacks) { 4614 if (internal_format) { 4615 p->trace_stack(); 4616 } else { 4617 p->print_stack_on(st); 4618 } 4619 } 4620 st->cr(); 4621 #if INCLUDE_SERVICES 4622 if (print_concurrent_locks) { 4623 concurrent_locks.print_locks_on(p, st); 4624 } 4625 #endif // INCLUDE_SERVICES 4626 } 4627 4628 VMThread::vm_thread()->print_on(st); 4629 st->cr(); 4630 Universe::heap()->print_gc_threads_on(st); 4631 WatcherThread* wt = WatcherThread::watcher_thread(); 4632 if (wt != NULL) { 4633 wt->print_on(st); 4634 st->cr(); 4635 } 4636 4637 st->flush(); 4638 } 4639 4640 void Threads::print_on_error(Thread* this_thread, outputStream* st, Thread* current, char* buf, 4641 int buflen, bool* found_current) { 4642 if (this_thread != NULL) { 4643 bool is_current = (current == this_thread); 4644 *found_current = *found_current || is_current; 4645 st->print("%s", is_current ? "=>" : " "); 4646 4647 st->print(PTR_FORMAT, p2i(this_thread)); 4648 st->print(" "); 4649 this_thread->print_on_error(st, buf, buflen); 4650 st->cr(); 4651 } 4652 } 4653 4654 class PrintOnErrorClosure : public ThreadClosure { 4655 outputStream* _st; 4656 Thread* _current; 4657 char* _buf; 4658 int _buflen; 4659 bool* _found_current; 4660 public: 4661 PrintOnErrorClosure(outputStream* st, Thread* current, char* buf, 4662 int buflen, bool* found_current) : 4663 _st(st), _current(current), _buf(buf), _buflen(buflen), _found_current(found_current) {} 4664 4665 virtual void do_thread(Thread* thread) { 4666 Threads::print_on_error(thread, _st, _current, _buf, _buflen, _found_current); 4667 } 4668 }; 4669 4670 // Threads::print_on_error() is called by fatal error handler. It's possible 4671 // that VM is not at safepoint and/or current thread is inside signal handler. 4672 // Don't print stack trace, as the stack may not be walkable. Don't allocate 4673 // memory (even in resource area), it might deadlock the error handler. 4674 void Threads::print_on_error(outputStream* st, Thread* current, char* buf, 4675 int buflen) { 4676 ThreadsSMRSupport::print_info_on(st); 4677 st->cr(); 4678 4679 bool found_current = false; 4680 st->print_cr("Java Threads: ( => current thread )"); 4681 ALL_JAVA_THREADS(thread) { 4682 print_on_error(thread, st, current, buf, buflen, &found_current); 4683 } 4684 st->cr(); 4685 4686 st->print_cr("Other Threads:"); 4687 print_on_error(VMThread::vm_thread(), st, current, buf, buflen, &found_current); 4688 print_on_error(WatcherThread::watcher_thread(), st, current, buf, buflen, &found_current); 4689 4690 PrintOnErrorClosure print_closure(st, current, buf, buflen, &found_current); 4691 Universe::heap()->gc_threads_do(&print_closure); 4692 4693 if (!found_current) { 4694 st->cr(); 4695 st->print("=>" PTR_FORMAT " (exited) ", p2i(current)); 4696 current->print_on_error(st, buf, buflen); 4697 st->cr(); 4698 } 4699 st->cr(); 4700 4701 st->print_cr("Threads with active compile tasks:"); 4702 print_threads_compiling(st, buf, buflen); 4703 } 4704 4705 void Threads::print_threads_compiling(outputStream* st, char* buf, int buflen) { 4706 ALL_JAVA_THREADS(thread) { 4707 if (thread->is_Compiler_thread()) { 4708 CompilerThread* ct = (CompilerThread*) thread; 4709 4710 // Keep task in local variable for NULL check. 4711 // ct->_task might be set to NULL by concurring compiler thread 4712 // because it completed the compilation. The task is never freed, 4713 // though, just returned to a free list. 4714 CompileTask* task = ct->task(); 4715 if (task != NULL) { 4716 thread->print_name_on_error(st, buf, buflen); 4717 task->print(st, NULL, true, true); 4718 } 4719 } 4720 } 4721 } 4722 4723 4724 // Internal SpinLock and Mutex 4725 // Based on ParkEvent 4726 4727 // Ad-hoc mutual exclusion primitives: SpinLock and Mux 4728 // 4729 // We employ SpinLocks _only for low-contention, fixed-length 4730 // short-duration critical sections where we're concerned 4731 // about native mutex_t or HotSpot Mutex:: latency. 4732 // The mux construct provides a spin-then-block mutual exclusion 4733 // mechanism. 4734 // 4735 // Testing has shown that contention on the ListLock guarding gFreeList 4736 // is common. If we implement ListLock as a simple SpinLock it's common 4737 // for the JVM to devolve to yielding with little progress. This is true 4738 // despite the fact that the critical sections protected by ListLock are 4739 // extremely short. 4740 // 4741 // TODO-FIXME: ListLock should be of type SpinLock. 4742 // We should make this a 1st-class type, integrated into the lock 4743 // hierarchy as leaf-locks. Critically, the SpinLock structure 4744 // should have sufficient padding to avoid false-sharing and excessive 4745 // cache-coherency traffic. 4746 4747 4748 typedef volatile int SpinLockT; 4749 4750 void Thread::SpinAcquire(volatile int * adr, const char * LockName) { 4751 if (Atomic::cmpxchg (1, adr, 0) == 0) { 4752 return; // normal fast-path return 4753 } 4754 4755 // Slow-path : We've encountered contention -- Spin/Yield/Block strategy. 4756 int ctr = 0; 4757 int Yields = 0; 4758 for (;;) { 4759 while (*adr != 0) { 4760 ++ctr; 4761 if ((ctr & 0xFFF) == 0 || !os::is_MP()) { 4762 if (Yields > 5) { 4763 os::naked_short_sleep(1); 4764 } else { 4765 os::naked_yield(); 4766 ++Yields; 4767 } 4768 } else { 4769 SpinPause(); 4770 } 4771 } 4772 if (Atomic::cmpxchg(1, adr, 0) == 0) return; 4773 } 4774 } 4775 4776 void Thread::SpinRelease(volatile int * adr) { 4777 assert(*adr != 0, "invariant"); 4778 OrderAccess::fence(); // guarantee at least release consistency. 4779 // Roach-motel semantics. 4780 // It's safe if subsequent LDs and STs float "up" into the critical section, 4781 // but prior LDs and STs within the critical section can't be allowed 4782 // to reorder or float past the ST that releases the lock. 4783 // Loads and stores in the critical section - which appear in program 4784 // order before the store that releases the lock - must also appear 4785 // before the store that releases the lock in memory visibility order. 4786 // Conceptually we need a #loadstore|#storestore "release" MEMBAR before 4787 // the ST of 0 into the lock-word which releases the lock, so fence 4788 // more than covers this on all platforms. 4789 *adr = 0; 4790 } 4791 4792 // muxAcquire and muxRelease: 4793 // 4794 // * muxAcquire and muxRelease support a single-word lock-word construct. 4795 // The LSB of the word is set IFF the lock is held. 4796 // The remainder of the word points to the head of a singly-linked list 4797 // of threads blocked on the lock. 4798 // 4799 // * The current implementation of muxAcquire-muxRelease uses its own 4800 // dedicated Thread._MuxEvent instance. If we're interested in 4801 // minimizing the peak number of extant ParkEvent instances then 4802 // we could eliminate _MuxEvent and "borrow" _ParkEvent as long 4803 // as certain invariants were satisfied. Specifically, care would need 4804 // to be taken with regards to consuming unpark() "permits". 4805 // A safe rule of thumb is that a thread would never call muxAcquire() 4806 // if it's enqueued (cxq, EntryList, WaitList, etc) and will subsequently 4807 // park(). Otherwise the _ParkEvent park() operation in muxAcquire() could 4808 // consume an unpark() permit intended for monitorenter, for instance. 4809 // One way around this would be to widen the restricted-range semaphore 4810 // implemented in park(). Another alternative would be to provide 4811 // multiple instances of the PlatformEvent() for each thread. One 4812 // instance would be dedicated to muxAcquire-muxRelease, for instance. 4813 // 4814 // * Usage: 4815 // -- Only as leaf locks 4816 // -- for short-term locking only as muxAcquire does not perform 4817 // thread state transitions. 4818 // 4819 // Alternatives: 4820 // * We could implement muxAcquire and muxRelease with MCS or CLH locks 4821 // but with parking or spin-then-park instead of pure spinning. 4822 // * Use Taura-Oyama-Yonenzawa locks. 4823 // * It's possible to construct a 1-0 lock if we encode the lockword as 4824 // (List,LockByte). Acquire will CAS the full lockword while Release 4825 // will STB 0 into the LockByte. The 1-0 scheme admits stranding, so 4826 // acquiring threads use timers (ParkTimed) to detect and recover from 4827 // the stranding window. Thread/Node structures must be aligned on 256-byte 4828 // boundaries by using placement-new. 4829 // * Augment MCS with advisory back-link fields maintained with CAS(). 4830 // Pictorially: LockWord -> T1 <-> T2 <-> T3 <-> ... <-> Tn <-> Owner. 4831 // The validity of the backlinks must be ratified before we trust the value. 4832 // If the backlinks are invalid the exiting thread must back-track through the 4833 // the forward links, which are always trustworthy. 4834 // * Add a successor indication. The LockWord is currently encoded as 4835 // (List, LOCKBIT:1). We could also add a SUCCBIT or an explicit _succ variable 4836 // to provide the usual futile-wakeup optimization. 4837 // See RTStt for details. 4838 // 4839 4840 4841 const intptr_t LOCKBIT = 1; 4842 4843 void Thread::muxAcquire(volatile intptr_t * Lock, const char * LockName) { 4844 intptr_t w = Atomic::cmpxchg(LOCKBIT, Lock, (intptr_t)0); 4845 if (w == 0) return; 4846 if ((w & LOCKBIT) == 0 && Atomic::cmpxchg(w|LOCKBIT, Lock, w) == w) { 4847 return; 4848 } 4849 4850 ParkEvent * const Self = Thread::current()->_MuxEvent; 4851 assert((intptr_t(Self) & LOCKBIT) == 0, "invariant"); 4852 for (;;) { 4853 int its = (os::is_MP() ? 100 : 0) + 1; 4854 4855 // Optional spin phase: spin-then-park strategy 4856 while (--its >= 0) { 4857 w = *Lock; 4858 if ((w & LOCKBIT) == 0 && Atomic::cmpxchg(w|LOCKBIT, Lock, w) == w) { 4859 return; 4860 } 4861 } 4862 4863 Self->reset(); 4864 Self->OnList = intptr_t(Lock); 4865 // The following fence() isn't _strictly necessary as the subsequent 4866 // CAS() both serializes execution and ratifies the fetched *Lock value. 4867 OrderAccess::fence(); 4868 for (;;) { 4869 w = *Lock; 4870 if ((w & LOCKBIT) == 0) { 4871 if (Atomic::cmpxchg(w|LOCKBIT, Lock, w) == w) { 4872 Self->OnList = 0; // hygiene - allows stronger asserts 4873 return; 4874 } 4875 continue; // Interference -- *Lock changed -- Just retry 4876 } 4877 assert(w & LOCKBIT, "invariant"); 4878 Self->ListNext = (ParkEvent *) (w & ~LOCKBIT); 4879 if (Atomic::cmpxchg(intptr_t(Self)|LOCKBIT, Lock, w) == w) break; 4880 } 4881 4882 while (Self->OnList != 0) { 4883 Self->park(); 4884 } 4885 } 4886 } 4887 4888 void Thread::muxAcquireW(volatile intptr_t * Lock, ParkEvent * ev) { 4889 intptr_t w = Atomic::cmpxchg(LOCKBIT, Lock, (intptr_t)0); 4890 if (w == 0) return; 4891 if ((w & LOCKBIT) == 0 && Atomic::cmpxchg(w|LOCKBIT, Lock, w) == w) { 4892 return; 4893 } 4894 4895 ParkEvent * ReleaseAfter = NULL; 4896 if (ev == NULL) { 4897 ev = ReleaseAfter = ParkEvent::Allocate(NULL); 4898 } 4899 assert((intptr_t(ev) & LOCKBIT) == 0, "invariant"); 4900 for (;;) { 4901 guarantee(ev->OnList == 0, "invariant"); 4902 int its = (os::is_MP() ? 100 : 0) + 1; 4903 4904 // Optional spin phase: spin-then-park strategy 4905 while (--its >= 0) { 4906 w = *Lock; 4907 if ((w & LOCKBIT) == 0 && Atomic::cmpxchg(w|LOCKBIT, Lock, w) == w) { 4908 if (ReleaseAfter != NULL) { 4909 ParkEvent::Release(ReleaseAfter); 4910 } 4911 return; 4912 } 4913 } 4914 4915 ev->reset(); 4916 ev->OnList = intptr_t(Lock); 4917 // The following fence() isn't _strictly necessary as the subsequent 4918 // CAS() both serializes execution and ratifies the fetched *Lock value. 4919 OrderAccess::fence(); 4920 for (;;) { 4921 w = *Lock; 4922 if ((w & LOCKBIT) == 0) { 4923 if (Atomic::cmpxchg(w|LOCKBIT, Lock, w) == w) { 4924 ev->OnList = 0; 4925 // We call ::Release while holding the outer lock, thus 4926 // artificially lengthening the critical section. 4927 // Consider deferring the ::Release() until the subsequent unlock(), 4928 // after we've dropped the outer lock. 4929 if (ReleaseAfter != NULL) { 4930 ParkEvent::Release(ReleaseAfter); 4931 } 4932 return; 4933 } 4934 continue; // Interference -- *Lock changed -- Just retry 4935 } 4936 assert(w & LOCKBIT, "invariant"); 4937 ev->ListNext = (ParkEvent *) (w & ~LOCKBIT); 4938 if (Atomic::cmpxchg(intptr_t(ev)|LOCKBIT, Lock, w) == w) break; 4939 } 4940 4941 while (ev->OnList != 0) { 4942 ev->park(); 4943 } 4944 } 4945 } 4946 4947 // Release() must extract a successor from the list and then wake that thread. 4948 // It can "pop" the front of the list or use a detach-modify-reattach (DMR) scheme 4949 // similar to that used by ParkEvent::Allocate() and ::Release(). DMR-based 4950 // Release() would : 4951 // (A) CAS() or swap() null to *Lock, releasing the lock and detaching the list. 4952 // (B) Extract a successor from the private list "in-hand" 4953 // (C) attempt to CAS() the residual back into *Lock over null. 4954 // If there were any newly arrived threads and the CAS() would fail. 4955 // In that case Release() would detach the RATs, re-merge the list in-hand 4956 // with the RATs and repeat as needed. Alternately, Release() might 4957 // detach and extract a successor, but then pass the residual list to the wakee. 4958 // The wakee would be responsible for reattaching and remerging before it 4959 // competed for the lock. 4960 // 4961 // Both "pop" and DMR are immune from ABA corruption -- there can be 4962 // multiple concurrent pushers, but only one popper or detacher. 4963 // This implementation pops from the head of the list. This is unfair, 4964 // but tends to provide excellent throughput as hot threads remain hot. 4965 // (We wake recently run threads first). 4966 // 4967 // All paths through muxRelease() will execute a CAS. 4968 // Release consistency -- We depend on the CAS in muxRelease() to provide full 4969 // bidirectional fence/MEMBAR semantics, ensuring that all prior memory operations 4970 // executed within the critical section are complete and globally visible before the 4971 // store (CAS) to the lock-word that releases the lock becomes globally visible. 4972 void Thread::muxRelease(volatile intptr_t * Lock) { 4973 for (;;) { 4974 const intptr_t w = Atomic::cmpxchg((intptr_t)0, Lock, LOCKBIT); 4975 assert(w & LOCKBIT, "invariant"); 4976 if (w == LOCKBIT) return; 4977 ParkEvent * const List = (ParkEvent *) (w & ~LOCKBIT); 4978 assert(List != NULL, "invariant"); 4979 assert(List->OnList == intptr_t(Lock), "invariant"); 4980 ParkEvent * const nxt = List->ListNext; 4981 guarantee((intptr_t(nxt) & LOCKBIT) == 0, "invariant"); 4982 4983 // The following CAS() releases the lock and pops the head element. 4984 // The CAS() also ratifies the previously fetched lock-word value. 4985 if (Atomic::cmpxchg(intptr_t(nxt), Lock, w) != w) { 4986 continue; 4987 } 4988 List->OnList = 0; 4989 OrderAccess::fence(); 4990 List->unpark(); 4991 return; 4992 } 4993 } 4994 4995 4996 void Threads::verify() { 4997 ALL_JAVA_THREADS(p) { 4998 p->verify(); 4999 } 5000 VMThread* thread = VMThread::vm_thread(); 5001 if (thread != NULL) thread->verify(); 5002 }