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