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