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