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