1 /* 2 * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 * 23 */ 24 25 #include "precompiled.hpp" 26 #include "classfile/systemDictionary.hpp" 27 #include "memory/allocation.hpp" 28 #include "memory/heapInspection.hpp" 29 #include "memory/oopFactory.hpp" 30 #include "memory/resourceArea.hpp" 31 #include "oops/instanceKlass.hpp" 32 #include "oops/objArrayOop.inline.hpp" 33 #include "oops/oop.inline.hpp" 34 #include "runtime/atomic.hpp" 35 #include "runtime/handles.inline.hpp" 36 #include "runtime/init.hpp" 37 #include "runtime/objectMonitor.inline.hpp" 38 #include "runtime/thread.inline.hpp" 39 #include "runtime/threadSMR.inline.hpp" 40 #include "runtime/vframe.hpp" 41 #include "runtime/vmThread.hpp" 42 #include "runtime/vm_operations.hpp" 43 #include "services/threadService.hpp" 44 45 // TODO: we need to define a naming convention for perf counters 46 // to distinguish counters for: 47 // - standard JSR174 use 48 // - Hotspot extension (public and committed) 49 // - Hotspot extension (private/internal and uncommitted) 50 51 // Default is disabled. 52 bool ThreadService::_thread_monitoring_contention_enabled = false; 53 bool ThreadService::_thread_cpu_time_enabled = false; 54 bool ThreadService::_thread_allocated_memory_enabled = false; 55 56 PerfCounter* ThreadService::_total_threads_count = NULL; 57 PerfVariable* ThreadService::_live_threads_count = NULL; 58 PerfVariable* ThreadService::_peak_threads_count = NULL; 59 PerfVariable* ThreadService::_daemon_threads_count = NULL; 60 volatile int ThreadService::_atomic_threads_count = 0; 61 volatile int ThreadService::_atomic_daemon_threads_count = 0; 62 63 ThreadDumpResult* ThreadService::_threaddump_list = NULL; 64 65 static const int INITIAL_ARRAY_SIZE = 10; 66 67 void ThreadService::init() { 68 EXCEPTION_MARK; 69 70 // These counters are for java.lang.management API support. 71 // They are created even if -XX:-UsePerfData is set and in 72 // that case, they will be allocated on C heap. 73 74 _total_threads_count = 75 PerfDataManager::create_counter(JAVA_THREADS, "started", 76 PerfData::U_Events, CHECK); 77 78 _live_threads_count = 79 PerfDataManager::create_variable(JAVA_THREADS, "live", 80 PerfData::U_None, CHECK); 81 82 _peak_threads_count = 83 PerfDataManager::create_variable(JAVA_THREADS, "livePeak", 84 PerfData::U_None, CHECK); 85 86 _daemon_threads_count = 87 PerfDataManager::create_variable(JAVA_THREADS, "daemon", 88 PerfData::U_None, CHECK); 89 90 if (os::is_thread_cpu_time_supported()) { 91 _thread_cpu_time_enabled = true; 92 } 93 94 _thread_allocated_memory_enabled = true; // Always on, so enable it 95 } 96 97 void ThreadService::reset_peak_thread_count() { 98 // Acquire the lock to update the peak thread count 99 // to synchronize with thread addition and removal. 100 MutexLockerEx mu(Threads_lock); 101 _peak_threads_count->set_value(get_live_thread_count()); 102 } 103 104 void ThreadService::add_thread(JavaThread* thread, bool daemon) { 105 assert(Threads_lock->owned_by_self(), "must have threads lock"); 106 107 // Do not count VM internal or JVMTI agent threads 108 if (thread->is_hidden_from_external_view() || 109 thread->is_jvmti_agent_thread()) { 110 return; 111 } 112 113 _total_threads_count->inc(); 114 _live_threads_count->inc(); 115 Atomic::inc(&_atomic_threads_count); 116 117 if (_atomic_threads_count > _peak_threads_count->get_value()) { 118 _peak_threads_count->set_value(_atomic_threads_count); 119 } 120 121 if (daemon) { 122 _daemon_threads_count->inc(); 123 Atomic::inc(&_atomic_daemon_threads_count); 124 } 125 } 126 127 void ThreadService::decrement_thread_counts(JavaThread* jt) { 128 Atomic::dec(&_atomic_threads_count); 129 130 oop threadObj = jt->threadObj(); 131 if (threadObj != NULL && java_lang_Thread::is_daemon(threadObj)) { 132 Atomic::dec(&_atomic_daemon_threads_count); 133 } 134 } 135 136 void ThreadService::remove_thread(JavaThread* thread, bool daemon) { 137 assert(Threads_lock->owned_by_self(), "must have threads lock"); 138 if (thread->is_hidden_from_external_view() || 139 thread->is_jvmti_agent_thread()) { 140 return; 141 } 142 143 assert(!thread->is_terminated(), "must not be terminated"); 144 if (!thread->is_exiting()) { 145 // JavaThread::exit() skipped calling current_thread_exiting() 146 decrement_thread_counts(thread); 147 } 148 149 int daemon_count = _atomic_daemon_threads_count; 150 int count = _atomic_threads_count; 151 152 // Counts are incremented at the same time, but atomic counts are 153 // decremented earlier than perf counts. 154 assert(_live_threads_count->get_value() > count, 155 "thread count mismatch %d : %d", 156 (int)_live_threads_count->get_value(), count); 157 158 _live_threads_count->dec(1); 159 if (daemon) { 160 assert(_daemon_threads_count->get_value() > daemon_count, 161 "thread count mismatch %d : %d", 162 (int)_daemon_threads_count->get_value(), daemon_count); 163 164 _daemon_threads_count->dec(1); 165 } 166 167 // Counts are incremented at the same time, but atomic counts are 168 // decremented earlier than perf counts. 169 assert(_daemon_threads_count->get_value() >= daemon_count, 170 "thread count mismatch %d : %d", 171 (int)_daemon_threads_count->get_value(), daemon_count); 172 assert(_live_threads_count->get_value() >= count, 173 "thread count mismatch %d : %d", 174 (int)_live_threads_count->get_value(), count); 175 assert(_live_threads_count->get_value() > 0 || 176 (_live_threads_count->get_value() == 0 && count == 0 && 177 _daemon_threads_count->get_value() == 0 && daemon_count == 0), 178 "thread counts should reach 0 at the same time, live %d,%d daemon %d,%d", 179 (int)_live_threads_count->get_value(), count, 180 (int)_daemon_threads_count->get_value(), daemon_count); 181 assert(_daemon_threads_count->get_value() > 0 || 182 (_daemon_threads_count->get_value() == 0 && daemon_count == 0), 183 "thread counts should reach 0 at the same time, daemon %d,%d", 184 (int)_daemon_threads_count->get_value(), daemon_count); 185 } 186 187 void ThreadService::current_thread_exiting(JavaThread* jt) { 188 if (jt->is_hidden_from_external_view() || 189 jt->is_jvmti_agent_thread()) { 190 return; 191 } 192 193 assert(jt == JavaThread::current(), "Called by current thread"); 194 assert(!jt->is_terminated() && jt->is_exiting(), "must be exiting"); 195 196 decrement_thread_counts(jt); 197 } 198 199 // FIXME: JVMTI should call this function 200 Handle ThreadService::get_current_contended_monitor(JavaThread* thread) { 201 assert(thread != NULL, "should be non-NULL"); 202 debug_only(Thread::check_for_dangling_thread_pointer(thread);) 203 204 ObjectMonitor *wait_obj = thread->current_waiting_monitor(); 205 206 oop obj = NULL; 207 if (wait_obj != NULL) { 208 // thread is doing an Object.wait() call 209 obj = (oop) wait_obj->object(); 210 assert(obj != NULL, "Object.wait() should have an object"); 211 } else { 212 ObjectMonitor *enter_obj = thread->current_pending_monitor(); 213 if (enter_obj != NULL) { 214 // thread is trying to enter() or raw_enter() an ObjectMonitor. 215 obj = (oop) enter_obj->object(); 216 } 217 // If obj == NULL, then ObjectMonitor is raw which doesn't count. 218 } 219 220 Handle h(Thread::current(), obj); 221 return h; 222 } 223 224 bool ThreadService::set_thread_monitoring_contention(bool flag) { 225 MutexLocker m(Management_lock); 226 227 bool prev = _thread_monitoring_contention_enabled; 228 _thread_monitoring_contention_enabled = flag; 229 230 return prev; 231 } 232 233 bool ThreadService::set_thread_cpu_time_enabled(bool flag) { 234 MutexLocker m(Management_lock); 235 236 bool prev = _thread_cpu_time_enabled; 237 _thread_cpu_time_enabled = flag; 238 239 return prev; 240 } 241 242 bool ThreadService::set_thread_allocated_memory_enabled(bool flag) { 243 MutexLocker m(Management_lock); 244 245 bool prev = _thread_allocated_memory_enabled; 246 _thread_allocated_memory_enabled = flag; 247 248 return prev; 249 } 250 251 // GC support 252 void ThreadService::oops_do(OopClosure* f) { 253 for (ThreadDumpResult* dump = _threaddump_list; dump != NULL; dump = dump->next()) { 254 dump->oops_do(f); 255 } 256 } 257 258 void ThreadService::metadata_do(void f(Metadata*)) { 259 for (ThreadDumpResult* dump = _threaddump_list; dump != NULL; dump = dump->next()) { 260 dump->metadata_do(f); 261 } 262 } 263 264 void ThreadService::add_thread_dump(ThreadDumpResult* dump) { 265 MutexLocker ml(Management_lock); 266 if (_threaddump_list == NULL) { 267 _threaddump_list = dump; 268 } else { 269 dump->set_next(_threaddump_list); 270 _threaddump_list = dump; 271 } 272 } 273 274 void ThreadService::remove_thread_dump(ThreadDumpResult* dump) { 275 MutexLocker ml(Management_lock); 276 277 ThreadDumpResult* prev = NULL; 278 bool found = false; 279 for (ThreadDumpResult* d = _threaddump_list; d != NULL; prev = d, d = d->next()) { 280 if (d == dump) { 281 if (prev == NULL) { 282 _threaddump_list = dump->next(); 283 } else { 284 prev->set_next(dump->next()); 285 } 286 found = true; 287 break; 288 } 289 } 290 assert(found, "The threaddump result to be removed must exist."); 291 } 292 293 // Dump stack trace of threads specified in the given threads array. 294 // Returns StackTraceElement[][] each element is the stack trace of a thread in 295 // the corresponding entry in the given threads array 296 Handle ThreadService::dump_stack_traces(GrowableArray<instanceHandle>* threads, 297 int num_threads, 298 TRAPS) { 299 assert(num_threads > 0, "just checking"); 300 301 ThreadDumpResult dump_result; 302 VM_ThreadDump op(&dump_result, 303 threads, 304 num_threads, 305 -1, /* entire stack */ 306 false, /* with locked monitors */ 307 false /* with locked synchronizers */); 308 VMThread::execute(&op); 309 310 // Allocate the resulting StackTraceElement[][] object 311 312 ResourceMark rm(THREAD); 313 Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_StackTraceElement_array(), true, CHECK_NH); 314 ObjArrayKlass* ik = ObjArrayKlass::cast(k); 315 objArrayOop r = oopFactory::new_objArray(ik, num_threads, CHECK_NH); 316 objArrayHandle result_obj(THREAD, r); 317 318 int num_snapshots = dump_result.num_snapshots(); 319 assert(num_snapshots == num_threads, "Must have num_threads thread snapshots"); 320 assert(num_snapshots == 0 || dump_result.t_list_has_been_set(), "ThreadsList must have been set if we have a snapshot"); 321 int i = 0; 322 for (ThreadSnapshot* ts = dump_result.snapshots(); ts != NULL; i++, ts = ts->next()) { 323 ThreadStackTrace* stacktrace = ts->get_stack_trace(); 324 if (stacktrace == NULL) { 325 // No stack trace 326 result_obj->obj_at_put(i, NULL); 327 } else { 328 // Construct an array of java/lang/StackTraceElement object 329 Handle backtrace_h = stacktrace->allocate_fill_stack_trace_element_array(CHECK_NH); 330 result_obj->obj_at_put(i, backtrace_h()); 331 } 332 } 333 334 return result_obj; 335 } 336 337 void ThreadService::reset_contention_count_stat(JavaThread* thread) { 338 ThreadStatistics* stat = thread->get_thread_stat(); 339 if (stat != NULL) { 340 stat->reset_count_stat(); 341 } 342 } 343 344 void ThreadService::reset_contention_time_stat(JavaThread* thread) { 345 ThreadStatistics* stat = thread->get_thread_stat(); 346 if (stat != NULL) { 347 stat->reset_time_stat(); 348 } 349 } 350 351 // Find deadlocks involving object monitors and concurrent locks if concurrent_locks is true 352 DeadlockCycle* ThreadService::find_deadlocks_at_safepoint(ThreadsList * t_list, bool concurrent_locks) { 353 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint"); 354 355 // This code was modified from the original Threads::find_deadlocks code. 356 int globalDfn = 0, thisDfn; 357 ObjectMonitor* waitingToLockMonitor = NULL; 358 oop waitingToLockBlocker = NULL; 359 bool blocked_on_monitor = false; 360 JavaThread *currentThread, *previousThread; 361 int num_deadlocks = 0; 362 363 // Initialize the depth-first-number for each JavaThread. 364 JavaThreadIterator jti(t_list); 365 for (JavaThread* jt = jti.first(); jt != NULL; jt = jti.next()) { 366 jt->set_depth_first_number(-1); 367 } 368 369 DeadlockCycle* deadlocks = NULL; 370 DeadlockCycle* last = NULL; 371 DeadlockCycle* cycle = new DeadlockCycle(); 372 for (JavaThread* jt = jti.first(); jt != NULL; jt = jti.next()) { 373 if (jt->depth_first_number() >= 0) { 374 // this thread was already visited 375 continue; 376 } 377 378 thisDfn = globalDfn; 379 jt->set_depth_first_number(globalDfn++); 380 previousThread = jt; 381 currentThread = jt; 382 383 cycle->reset(); 384 385 // When there is a deadlock, all the monitors involved in the dependency 386 // cycle must be contended and heavyweight. So we only care about the 387 // heavyweight monitor a thread is waiting to lock. 388 waitingToLockMonitor = (ObjectMonitor*)jt->current_pending_monitor(); 389 if (concurrent_locks) { 390 waitingToLockBlocker = jt->current_park_blocker(); 391 } 392 while (waitingToLockMonitor != NULL || waitingToLockBlocker != NULL) { 393 cycle->add_thread(currentThread); 394 if (waitingToLockMonitor != NULL) { 395 address currentOwner = (address)waitingToLockMonitor->owner(); 396 if (currentOwner != NULL) { 397 currentThread = Threads::owning_thread_from_monitor_owner(t_list, 398 currentOwner); 399 if (currentThread == NULL) { 400 // This function is called at a safepoint so the JavaThread 401 // that owns waitingToLockMonitor should be findable, but 402 // if it is not findable, then the previous currentThread is 403 // blocked permanently. We record this as a deadlock. 404 num_deadlocks++; 405 406 cycle->set_deadlock(true); 407 408 // add this cycle to the deadlocks list 409 if (deadlocks == NULL) { 410 deadlocks = cycle; 411 } else { 412 last->set_next(cycle); 413 } 414 last = cycle; 415 cycle = new DeadlockCycle(); 416 break; 417 } 418 } 419 } else { 420 if (concurrent_locks) { 421 if (waitingToLockBlocker->is_a(SystemDictionary::java_util_concurrent_locks_AbstractOwnableSynchronizer_klass())) { 422 oop threadObj = java_util_concurrent_locks_AbstractOwnableSynchronizer::get_owner_threadObj(waitingToLockBlocker); 423 // This JavaThread (if there is one) is protected by the 424 // ThreadsListSetter in VM_FindDeadlocks::doit(). 425 currentThread = threadObj != NULL ? java_lang_Thread::thread(threadObj) : NULL; 426 } else { 427 currentThread = NULL; 428 } 429 } 430 } 431 432 if (currentThread == NULL) { 433 // No dependency on another thread 434 break; 435 } 436 if (currentThread->depth_first_number() < 0) { 437 // First visit to this thread 438 currentThread->set_depth_first_number(globalDfn++); 439 } else if (currentThread->depth_first_number() < thisDfn) { 440 // Thread already visited, and not on a (new) cycle 441 break; 442 } else if (currentThread == previousThread) { 443 // Self-loop, ignore 444 break; 445 } else { 446 // We have a (new) cycle 447 num_deadlocks++; 448 449 cycle->set_deadlock(true); 450 451 // add this cycle to the deadlocks list 452 if (deadlocks == NULL) { 453 deadlocks = cycle; 454 } else { 455 last->set_next(cycle); 456 } 457 last = cycle; 458 cycle = new DeadlockCycle(); 459 break; 460 } 461 previousThread = currentThread; 462 waitingToLockMonitor = (ObjectMonitor*)currentThread->current_pending_monitor(); 463 if (concurrent_locks) { 464 waitingToLockBlocker = currentThread->current_park_blocker(); 465 } 466 } 467 468 } 469 delete cycle; 470 return deadlocks; 471 } 472 473 ThreadDumpResult::ThreadDumpResult() : _num_threads(0), _num_snapshots(0), _snapshots(NULL), _last(NULL), _next(NULL), _setter() { 474 475 // Create a new ThreadDumpResult object and append to the list. 476 // If GC happens before this function returns, Method* 477 // in the stack trace will be visited. 478 ThreadService::add_thread_dump(this); 479 } 480 481 ThreadDumpResult::ThreadDumpResult(int num_threads) : _num_threads(num_threads), _num_snapshots(0), _snapshots(NULL), _last(NULL), _next(NULL), _setter() { 482 // Create a new ThreadDumpResult object and append to the list. 483 // If GC happens before this function returns, oops 484 // will be visited. 485 ThreadService::add_thread_dump(this); 486 } 487 488 ThreadDumpResult::~ThreadDumpResult() { 489 ThreadService::remove_thread_dump(this); 490 491 // free all the ThreadSnapshot objects created during 492 // the VM_ThreadDump operation 493 ThreadSnapshot* ts = _snapshots; 494 while (ts != NULL) { 495 ThreadSnapshot* p = ts; 496 ts = ts->next(); 497 delete p; 498 } 499 } 500 501 502 void ThreadDumpResult::add_thread_snapshot(ThreadSnapshot* ts) { 503 assert(_num_threads == 0 || _num_snapshots < _num_threads, 504 "_num_snapshots must be less than _num_threads"); 505 _num_snapshots++; 506 if (_snapshots == NULL) { 507 _snapshots = ts; 508 } else { 509 _last->set_next(ts); 510 } 511 _last = ts; 512 } 513 514 void ThreadDumpResult::oops_do(OopClosure* f) { 515 for (ThreadSnapshot* ts = _snapshots; ts != NULL; ts = ts->next()) { 516 ts->oops_do(f); 517 } 518 } 519 520 void ThreadDumpResult::metadata_do(void f(Metadata*)) { 521 for (ThreadSnapshot* ts = _snapshots; ts != NULL; ts = ts->next()) { 522 ts->metadata_do(f); 523 } 524 } 525 526 ThreadsList* ThreadDumpResult::t_list() { 527 return _setter.list(); 528 } 529 530 StackFrameInfo::StackFrameInfo(javaVFrame* jvf, bool with_lock_info) { 531 _method = jvf->method(); 532 _bci = jvf->bci(); 533 _class_holder = _method->method_holder()->klass_holder(); 534 _locked_monitors = NULL; 535 if (with_lock_info) { 536 ResourceMark rm; 537 GrowableArray<MonitorInfo*>* list = jvf->locked_monitors(); 538 int length = list->length(); 539 if (length > 0) { 540 _locked_monitors = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<oop>(length, true); 541 for (int i = 0; i < length; i++) { 542 MonitorInfo* monitor = list->at(i); 543 assert(monitor->owner() != NULL, "This monitor must have an owning object"); 544 _locked_monitors->append(monitor->owner()); 545 } 546 } 547 } 548 } 549 550 void StackFrameInfo::oops_do(OopClosure* f) { 551 if (_locked_monitors != NULL) { 552 int length = _locked_monitors->length(); 553 for (int i = 0; i < length; i++) { 554 f->do_oop((oop*) _locked_monitors->adr_at(i)); 555 } 556 } 557 f->do_oop(&_class_holder); 558 } 559 560 void StackFrameInfo::metadata_do(void f(Metadata*)) { 561 f(_method); 562 } 563 564 void StackFrameInfo::print_on(outputStream* st) const { 565 ResourceMark rm; 566 java_lang_Throwable::print_stack_element(st, method(), bci()); 567 int len = (_locked_monitors != NULL ? _locked_monitors->length() : 0); 568 for (int i = 0; i < len; i++) { 569 oop o = _locked_monitors->at(i); 570 st->print_cr("\t- locked <" INTPTR_FORMAT "> (a %s)", p2i(o), o->klass()->external_name()); 571 } 572 573 } 574 575 // Iterate through monitor cache to find JNI locked monitors 576 class InflatedMonitorsClosure: public MonitorClosure { 577 private: 578 ThreadStackTrace* _stack_trace; 579 Thread* _thread; 580 public: 581 InflatedMonitorsClosure(Thread* t, ThreadStackTrace* st) { 582 _thread = t; 583 _stack_trace = st; 584 } 585 void do_monitor(ObjectMonitor* mid) { 586 if (mid->owner() == _thread) { 587 oop object = (oop) mid->object(); 588 if (!_stack_trace->is_owned_monitor_on_stack(object)) { 589 _stack_trace->add_jni_locked_monitor(object); 590 } 591 } 592 } 593 }; 594 595 ThreadStackTrace::ThreadStackTrace(JavaThread* t, bool with_locked_monitors) { 596 _thread = t; 597 _frames = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<StackFrameInfo*>(INITIAL_ARRAY_SIZE, true); 598 _depth = 0; 599 _with_locked_monitors = with_locked_monitors; 600 if (_with_locked_monitors) { 601 _jni_locked_monitors = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<oop>(INITIAL_ARRAY_SIZE, true); 602 } else { 603 _jni_locked_monitors = NULL; 604 } 605 } 606 607 ThreadStackTrace::~ThreadStackTrace() { 608 for (int i = 0; i < _frames->length(); i++) { 609 delete _frames->at(i); 610 } 611 delete _frames; 612 if (_jni_locked_monitors != NULL) { 613 delete _jni_locked_monitors; 614 } 615 } 616 617 void ThreadStackTrace::dump_stack_at_safepoint(int maxDepth) { 618 assert(SafepointSynchronize::is_at_safepoint(), "all threads are stopped"); 619 620 if (_thread->has_last_Java_frame()) { 621 RegisterMap reg_map(_thread); 622 vframe* start_vf = _thread->last_java_vframe(®_map); 623 int count = 0; 624 for (vframe* f = start_vf; f; f = f->sender() ) { 625 if (maxDepth >= 0 && count == maxDepth) { 626 // Skip frames if more than maxDepth 627 break; 628 } 629 if (f->is_java_frame()) { 630 javaVFrame* jvf = javaVFrame::cast(f); 631 add_stack_frame(jvf); 632 count++; 633 } else { 634 // Ignore non-Java frames 635 } 636 } 637 } 638 639 if (_with_locked_monitors) { 640 // Iterate inflated monitors and find monitors locked by this thread 641 // not found in the stack 642 InflatedMonitorsClosure imc(_thread, this); 643 ObjectSynchronizer::monitors_iterate(&imc); 644 } 645 } 646 647 648 bool ThreadStackTrace::is_owned_monitor_on_stack(oop object) { 649 assert(SafepointSynchronize::is_at_safepoint(), "all threads are stopped"); 650 651 bool found = false; 652 int num_frames = get_stack_depth(); 653 for (int depth = 0; depth < num_frames; depth++) { 654 StackFrameInfo* frame = stack_frame_at(depth); 655 int len = frame->num_locked_monitors(); 656 GrowableArray<oop>* locked_monitors = frame->locked_monitors(); 657 for (int j = 0; j < len; j++) { 658 oop monitor = locked_monitors->at(j); 659 assert(monitor != NULL, "must be a Java object"); 660 if (oopDesc::equals(monitor, object)) { 661 found = true; 662 break; 663 } 664 } 665 } 666 return found; 667 } 668 669 Handle ThreadStackTrace::allocate_fill_stack_trace_element_array(TRAPS) { 670 InstanceKlass* ik = SystemDictionary::StackTraceElement_klass(); 671 assert(ik != NULL, "must be loaded in 1.4+"); 672 673 // Allocate an array of java/lang/StackTraceElement object 674 objArrayOop ste = oopFactory::new_objArray(ik, _depth, CHECK_NH); 675 objArrayHandle backtrace(THREAD, ste); 676 for (int j = 0; j < _depth; j++) { 677 StackFrameInfo* frame = _frames->at(j); 678 methodHandle mh(THREAD, frame->method()); 679 oop element = java_lang_StackTraceElement::create(mh, frame->bci(), CHECK_NH); 680 backtrace->obj_at_put(j, element); 681 } 682 return backtrace; 683 } 684 685 void ThreadStackTrace::add_stack_frame(javaVFrame* jvf) { 686 StackFrameInfo* frame = new StackFrameInfo(jvf, _with_locked_monitors); 687 _frames->append(frame); 688 _depth++; 689 } 690 691 void ThreadStackTrace::oops_do(OopClosure* f) { 692 int length = _frames->length(); 693 for (int i = 0; i < length; i++) { 694 _frames->at(i)->oops_do(f); 695 } 696 697 length = (_jni_locked_monitors != NULL ? _jni_locked_monitors->length() : 0); 698 for (int j = 0; j < length; j++) { 699 f->do_oop((oop*) _jni_locked_monitors->adr_at(j)); 700 } 701 } 702 703 void ThreadStackTrace::metadata_do(void f(Metadata*)) { 704 int length = _frames->length(); 705 for (int i = 0; i < length; i++) { 706 _frames->at(i)->metadata_do(f); 707 } 708 } 709 710 711 ConcurrentLocksDump::~ConcurrentLocksDump() { 712 if (_retain_map_on_free) { 713 return; 714 } 715 716 for (ThreadConcurrentLocks* t = _map; t != NULL;) { 717 ThreadConcurrentLocks* tcl = t; 718 t = t->next(); 719 delete tcl; 720 } 721 } 722 723 void ConcurrentLocksDump::dump_at_safepoint() { 724 // dump all locked concurrent locks 725 assert(SafepointSynchronize::is_at_safepoint(), "all threads are stopped"); 726 727 GrowableArray<oop>* aos_objects = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<oop>(INITIAL_ARRAY_SIZE, true /* C_heap */); 728 729 // Find all instances of AbstractOwnableSynchronizer 730 HeapInspection::find_instances_at_safepoint(SystemDictionary::java_util_concurrent_locks_AbstractOwnableSynchronizer_klass(), 731 aos_objects); 732 // Build a map of thread to its owned AQS locks 733 build_map(aos_objects); 734 735 delete aos_objects; 736 } 737 738 739 // build a map of JavaThread to all its owned AbstractOwnableSynchronizer 740 void ConcurrentLocksDump::build_map(GrowableArray<oop>* aos_objects) { 741 int length = aos_objects->length(); 742 for (int i = 0; i < length; i++) { 743 oop o = aos_objects->at(i); 744 oop owner_thread_obj = java_util_concurrent_locks_AbstractOwnableSynchronizer::get_owner_threadObj(o); 745 if (owner_thread_obj != NULL) { 746 // See comments in ThreadConcurrentLocks to see how this 747 // JavaThread* is protected. 748 JavaThread* thread = java_lang_Thread::thread(owner_thread_obj); 749 assert(o->is_instance(), "Must be an instanceOop"); 750 add_lock(thread, (instanceOop) o); 751 } 752 } 753 } 754 755 void ConcurrentLocksDump::add_lock(JavaThread* thread, instanceOop o) { 756 ThreadConcurrentLocks* tcl = thread_concurrent_locks(thread); 757 if (tcl != NULL) { 758 tcl->add_lock(o); 759 return; 760 } 761 762 // First owned lock found for this thread 763 tcl = new ThreadConcurrentLocks(thread); 764 tcl->add_lock(o); 765 if (_map == NULL) { 766 _map = tcl; 767 } else { 768 _last->set_next(tcl); 769 } 770 _last = tcl; 771 } 772 773 ThreadConcurrentLocks* ConcurrentLocksDump::thread_concurrent_locks(JavaThread* thread) { 774 for (ThreadConcurrentLocks* tcl = _map; tcl != NULL; tcl = tcl->next()) { 775 if (tcl->java_thread() == thread) { 776 return tcl; 777 } 778 } 779 return NULL; 780 } 781 782 void ConcurrentLocksDump::print_locks_on(JavaThread* t, outputStream* st) { 783 st->print_cr(" Locked ownable synchronizers:"); 784 ThreadConcurrentLocks* tcl = thread_concurrent_locks(t); 785 GrowableArray<instanceOop>* locks = (tcl != NULL ? tcl->owned_locks() : NULL); 786 if (locks == NULL || locks->is_empty()) { 787 st->print_cr("\t- None"); 788 st->cr(); 789 return; 790 } 791 792 for (int i = 0; i < locks->length(); i++) { 793 instanceOop obj = locks->at(i); 794 st->print_cr("\t- <" INTPTR_FORMAT "> (a %s)", p2i(obj), obj->klass()->external_name()); 795 } 796 st->cr(); 797 } 798 799 ThreadConcurrentLocks::ThreadConcurrentLocks(JavaThread* thread) { 800 _thread = thread; 801 _owned_locks = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<instanceOop>(INITIAL_ARRAY_SIZE, true); 802 _next = NULL; 803 } 804 805 ThreadConcurrentLocks::~ThreadConcurrentLocks() { 806 delete _owned_locks; 807 } 808 809 void ThreadConcurrentLocks::add_lock(instanceOop o) { 810 _owned_locks->append(o); 811 } 812 813 void ThreadConcurrentLocks::oops_do(OopClosure* f) { 814 int length = _owned_locks->length(); 815 for (int i = 0; i < length; i++) { 816 f->do_oop((oop*) _owned_locks->adr_at(i)); 817 } 818 } 819 820 ThreadStatistics::ThreadStatistics() { 821 _contended_enter_count = 0; 822 _monitor_wait_count = 0; 823 _sleep_count = 0; 824 _count_pending_reset = false; 825 _timer_pending_reset = false; 826 memset((void*) _perf_recursion_counts, 0, sizeof(_perf_recursion_counts)); 827 } 828 829 ThreadSnapshot::ThreadSnapshot(ThreadsList * t_list, JavaThread* thread) { 830 _thread = thread; 831 _threadObj = thread->threadObj(); 832 _stack_trace = NULL; 833 _concurrent_locks = NULL; 834 _next = NULL; 835 836 ThreadStatistics* stat = thread->get_thread_stat(); 837 _contended_enter_ticks = stat->contended_enter_ticks(); 838 _contended_enter_count = stat->contended_enter_count(); 839 _monitor_wait_ticks = stat->monitor_wait_ticks(); 840 _monitor_wait_count = stat->monitor_wait_count(); 841 _sleep_ticks = stat->sleep_ticks(); 842 _sleep_count = stat->sleep_count(); 843 844 _blocker_object = NULL; 845 _blocker_object_owner = NULL; 846 847 _thread_status = java_lang_Thread::get_thread_status(_threadObj); 848 _is_ext_suspended = thread->is_being_ext_suspended(); 849 _is_in_native = (thread->thread_state() == _thread_in_native); 850 851 if (_thread_status == java_lang_Thread::BLOCKED_ON_MONITOR_ENTER || 852 _thread_status == java_lang_Thread::IN_OBJECT_WAIT || 853 _thread_status == java_lang_Thread::IN_OBJECT_WAIT_TIMED) { 854 855 Handle obj = ThreadService::get_current_contended_monitor(thread); 856 if (obj() == NULL) { 857 // monitor no longer exists; thread is not blocked 858 _thread_status = java_lang_Thread::RUNNABLE; 859 } else { 860 _blocker_object = obj(); 861 JavaThread* owner = ObjectSynchronizer::get_lock_owner(t_list, obj); 862 if ((owner == NULL && _thread_status == java_lang_Thread::BLOCKED_ON_MONITOR_ENTER) 863 || (owner != NULL && owner->is_attaching_via_jni())) { 864 // ownership information of the monitor is not available 865 // (may no longer be owned or releasing to some other thread) 866 // make this thread in RUNNABLE state. 867 // And when the owner thread is in attaching state, the java thread 868 // is not completely initialized. For example thread name and id 869 // and may not be set, so hide the attaching thread. 870 _thread_status = java_lang_Thread::RUNNABLE; 871 _blocker_object = NULL; 872 } else if (owner != NULL) { 873 _blocker_object_owner = owner->threadObj(); 874 } 875 } 876 } 877 878 // Support for JSR-166 locks 879 if (JDK_Version::current().supports_thread_park_blocker() && 880 (_thread_status == java_lang_Thread::PARKED || 881 _thread_status == java_lang_Thread::PARKED_TIMED)) { 882 883 _blocker_object = thread->current_park_blocker(); 884 if (_blocker_object != NULL && _blocker_object->is_a(SystemDictionary::java_util_concurrent_locks_AbstractOwnableSynchronizer_klass())) { 885 _blocker_object_owner = java_util_concurrent_locks_AbstractOwnableSynchronizer::get_owner_threadObj(_blocker_object); 886 } 887 } 888 } 889 890 ThreadSnapshot::~ThreadSnapshot() { 891 delete _stack_trace; 892 delete _concurrent_locks; 893 } 894 895 void ThreadSnapshot::dump_stack_at_safepoint(int max_depth, bool with_locked_monitors) { 896 _stack_trace = new ThreadStackTrace(_thread, with_locked_monitors); 897 _stack_trace->dump_stack_at_safepoint(max_depth); 898 } 899 900 901 void ThreadSnapshot::oops_do(OopClosure* f) { 902 f->do_oop(&_threadObj); 903 f->do_oop(&_blocker_object); 904 f->do_oop(&_blocker_object_owner); 905 if (_stack_trace != NULL) { 906 _stack_trace->oops_do(f); 907 } 908 if (_concurrent_locks != NULL) { 909 _concurrent_locks->oops_do(f); 910 } 911 } 912 913 void ThreadSnapshot::metadata_do(void f(Metadata*)) { 914 if (_stack_trace != NULL) { 915 _stack_trace->metadata_do(f); 916 } 917 } 918 919 920 DeadlockCycle::DeadlockCycle() { 921 _is_deadlock = false; 922 _threads = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<JavaThread*>(INITIAL_ARRAY_SIZE, true); 923 _next = NULL; 924 } 925 926 DeadlockCycle::~DeadlockCycle() { 927 delete _threads; 928 } 929 930 void DeadlockCycle::print_on_with(ThreadsList * t_list, outputStream* st) const { 931 st->cr(); 932 st->print_cr("Found one Java-level deadlock:"); 933 st->print("============================="); 934 935 JavaThread* currentThread; 936 ObjectMonitor* waitingToLockMonitor; 937 oop waitingToLockBlocker; 938 int len = _threads->length(); 939 for (int i = 0; i < len; i++) { 940 currentThread = _threads->at(i); 941 waitingToLockMonitor = (ObjectMonitor*)currentThread->current_pending_monitor(); 942 waitingToLockBlocker = currentThread->current_park_blocker(); 943 st->cr(); 944 st->print_cr("\"%s\":", currentThread->get_thread_name()); 945 const char* owner_desc = ",\n which is held by"; 946 if (waitingToLockMonitor != NULL) { 947 st->print(" waiting to lock monitor " INTPTR_FORMAT, p2i(waitingToLockMonitor)); 948 oop obj = (oop)waitingToLockMonitor->object(); 949 if (obj != NULL) { 950 st->print(" (object " INTPTR_FORMAT ", a %s)", p2i(obj), 951 obj->klass()->external_name()); 952 953 if (!currentThread->current_pending_monitor_is_from_java()) { 954 owner_desc = "\n in JNI, which is held by"; 955 } 956 } else { 957 // No Java object associated - a JVMTI raw monitor 958 owner_desc = " (JVMTI raw monitor),\n which is held by"; 959 } 960 currentThread = Threads::owning_thread_from_monitor_owner(t_list, 961 (address)waitingToLockMonitor->owner()); 962 if (currentThread == NULL) { 963 // The deadlock was detected at a safepoint so the JavaThread 964 // that owns waitingToLockMonitor should be findable, but 965 // if it is not findable, then the previous currentThread is 966 // blocked permanently. 967 st->print("%s UNKNOWN_owner_addr=" PTR_FORMAT, owner_desc, 968 p2i(waitingToLockMonitor->owner())); 969 continue; 970 } 971 } else { 972 st->print(" waiting for ownable synchronizer " INTPTR_FORMAT ", (a %s)", 973 p2i(waitingToLockBlocker), 974 waitingToLockBlocker->klass()->external_name()); 975 assert(waitingToLockBlocker->is_a(SystemDictionary::java_util_concurrent_locks_AbstractOwnableSynchronizer_klass()), 976 "Must be an AbstractOwnableSynchronizer"); 977 oop ownerObj = java_util_concurrent_locks_AbstractOwnableSynchronizer::get_owner_threadObj(waitingToLockBlocker); 978 currentThread = java_lang_Thread::thread(ownerObj); 979 assert(currentThread != NULL, "AbstractOwnableSynchronizer owning thread is unexpectedly NULL"); 980 } 981 st->print("%s \"%s\"", owner_desc, currentThread->get_thread_name()); 982 } 983 984 st->cr(); 985 st->cr(); 986 987 // Print stack traces 988 bool oldJavaMonitorsInStackTrace = JavaMonitorsInStackTrace; 989 JavaMonitorsInStackTrace = true; 990 st->print_cr("Java stack information for the threads listed above:"); 991 st->print_cr("==================================================="); 992 for (int j = 0; j < len; j++) { 993 currentThread = _threads->at(j); 994 st->print_cr("\"%s\":", currentThread->get_thread_name()); 995 currentThread->print_stack_on(st); 996 } 997 JavaMonitorsInStackTrace = oldJavaMonitorsInStackTrace; 998 } 999 1000 ThreadsListEnumerator::ThreadsListEnumerator(Thread* cur_thread, 1001 bool include_jvmti_agent_threads, 1002 bool include_jni_attaching_threads) { 1003 assert(cur_thread == Thread::current(), "Check current thread"); 1004 1005 int init_size = ThreadService::get_live_thread_count(); 1006 _threads_array = new GrowableArray<instanceHandle>(init_size); 1007 1008 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *jt = jtiwh.next(); ) { 1009 // skips JavaThreads in the process of exiting 1010 // and also skips VM internal JavaThreads 1011 // Threads in _thread_new or _thread_new_trans state are included. 1012 // i.e. threads have been started but not yet running. 1013 if (jt->threadObj() == NULL || 1014 jt->is_exiting() || 1015 !java_lang_Thread::is_alive(jt->threadObj()) || 1016 jt->is_hidden_from_external_view()) { 1017 continue; 1018 } 1019 1020 // skip agent threads 1021 if (!include_jvmti_agent_threads && jt->is_jvmti_agent_thread()) { 1022 continue; 1023 } 1024 1025 // skip jni threads in the process of attaching 1026 if (!include_jni_attaching_threads && jt->is_attaching_via_jni()) { 1027 continue; 1028 } 1029 1030 instanceHandle h(cur_thread, (instanceOop) jt->threadObj()); 1031 _threads_array->append(h); 1032 } 1033 }