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