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