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