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