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