1 /*
   2  * Copyright (c) 2003, 2014, 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 "oops/instanceKlass.hpp"
  31 #include "oops/oop.inline.hpp"
  32 #include "runtime/atomic.inline.hpp"
  33 #include "runtime/handles.inline.hpp"
  34 #include "runtime/init.hpp"
  35 #include "runtime/thread.hpp"
  36 #include "runtime/vframe.hpp"
  37 #include "runtime/thread.inline.hpp"
  38 #include "runtime/vmThread.hpp"
  39 #include "runtime/vm_operations.hpp"
  40 #include "services/threadService.hpp"
  41 
  42 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
  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((jint*) &_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((jint*) &_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((jint*) &_exiting_threads_count);
 141 
 142   oop threadObj = jt->threadObj();
 143   if (threadObj != NULL && java_lang_Thread::is_daemon(threadObj)) {
 144     Atomic::inc((jint*) &_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   assert(Threads_lock->owned_by_self(), "must grab Threads_lock or be at safepoint");
 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(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   int i = 0;
 270   for (ThreadSnapshot* ts = dump_result.snapshots(); ts != NULL; i++, ts = ts->next()) {
 271     ThreadStackTrace* stacktrace = ts->get_stack_trace();
 272     if (stacktrace == NULL) {
 273       // No stack trace
 274       result_obj->obj_at_put(i, NULL);
 275     } else {
 276       // Construct an array of java/lang/StackTraceElement object
 277       Handle backtrace_h = stacktrace->allocate_fill_stack_trace_element_array(CHECK_NH);
 278       result_obj->obj_at_put(i, backtrace_h());
 279     }
 280   }
 281 
 282   return result_obj;
 283 }
 284 
 285 void ThreadService::reset_contention_count_stat(JavaThread* thread) {
 286   ThreadStatistics* stat = thread->get_thread_stat();
 287   if (stat != NULL) {
 288     stat->reset_count_stat();
 289   }
 290 }
 291 
 292 void ThreadService::reset_contention_time_stat(JavaThread* thread) {
 293   ThreadStatistics* stat = thread->get_thread_stat();
 294   if (stat != NULL) {
 295     stat->reset_time_stat();
 296   }
 297 }
 298 
 299 // Find deadlocks involving object monitors and concurrent locks if concurrent_locks is true
 300 DeadlockCycle* ThreadService::find_deadlocks_at_safepoint(bool concurrent_locks) {
 301   // This code was modified from the original Threads::find_deadlocks code.
 302   int globalDfn = 0, thisDfn;
 303   ObjectMonitor* waitingToLockMonitor = NULL;
 304   oop waitingToLockBlocker = NULL;
 305   bool blocked_on_monitor = false;
 306   JavaThread *currentThread, *previousThread;
 307   int num_deadlocks = 0;
 308 
 309   for (JavaThread* p = Threads::first(); p != NULL; p = p->next()) {
 310     // Initialize the depth-first-number
 311     p->set_depth_first_number(-1);
 312   }
 313 
 314   DeadlockCycle* deadlocks = NULL;
 315   DeadlockCycle* last = NULL;
 316   DeadlockCycle* cycle = new DeadlockCycle();
 317   for (JavaThread* jt = Threads::first(); jt != NULL; jt = jt->next()) {
 318     if (jt->depth_first_number() >= 0) {
 319       // this thread was already visited
 320       continue;
 321     }
 322 
 323     thisDfn = globalDfn;
 324     jt->set_depth_first_number(globalDfn++);
 325     previousThread = jt;
 326     currentThread = jt;
 327 
 328     cycle->reset();
 329 
 330     // When there is a deadlock, all the monitors involved in the dependency
 331     // cycle must be contended and heavyweight. So we only care about the
 332     // heavyweight monitor a thread is waiting to lock.
 333     waitingToLockMonitor = (ObjectMonitor*)jt->current_pending_monitor();
 334     if (concurrent_locks) {
 335       waitingToLockBlocker = jt->current_park_blocker();
 336     }
 337     while (waitingToLockMonitor != NULL || waitingToLockBlocker != NULL) {
 338       cycle->add_thread(currentThread);
 339       if (waitingToLockMonitor != NULL) {
 340         address currentOwner = (address)waitingToLockMonitor->owner();
 341         if (currentOwner != NULL) {
 342           currentThread = Threads::owning_thread_from_monitor_owner(
 343                             currentOwner,
 344                             false /* no locking needed */);
 345           if (currentThread == NULL) {
 346             // This function is called at a safepoint so the JavaThread
 347             // that owns waitingToLockMonitor should be findable, but
 348             // if it is not findable, then the previous currentThread is
 349             // blocked permanently. We record this as a deadlock.
 350             num_deadlocks++;
 351 
 352             cycle->set_deadlock(true);
 353 
 354             // add this cycle to the deadlocks list
 355             if (deadlocks == NULL) {
 356               deadlocks = cycle;
 357             } else {
 358               last->set_next(cycle);
 359             }
 360             last = cycle;
 361             cycle = new DeadlockCycle();
 362             break;
 363           }
 364         }
 365       } else {
 366         if (concurrent_locks) {
 367           if (waitingToLockBlocker->is_a(SystemDictionary::abstract_ownable_synchronizer_klass())) {
 368             oop threadObj = java_util_concurrent_locks_AbstractOwnableSynchronizer::get_owner_threadObj(waitingToLockBlocker);
 369             currentThread = threadObj != NULL ? java_lang_Thread::thread(threadObj) : NULL;
 370           } else {
 371             currentThread = NULL;
 372           }
 373         }
 374       }
 375 
 376       if (currentThread == NULL) {
 377         // No dependency on another thread
 378         break;
 379       }
 380       if (currentThread->depth_first_number() < 0) {
 381         // First visit to this thread
 382         currentThread->set_depth_first_number(globalDfn++);
 383       } else if (currentThread->depth_first_number() < thisDfn) {
 384         // Thread already visited, and not on a (new) cycle
 385         break;
 386       } else if (currentThread == previousThread) {
 387         // Self-loop, ignore
 388         break;
 389       } else {
 390         // We have a (new) cycle
 391         num_deadlocks++;
 392 
 393         cycle->set_deadlock(true);
 394 
 395         // add this cycle to the deadlocks list
 396         if (deadlocks == NULL) {
 397           deadlocks = cycle;
 398         } else {
 399           last->set_next(cycle);
 400         }
 401         last = cycle;
 402         cycle = new DeadlockCycle();
 403         break;
 404       }
 405       previousThread = currentThread;
 406       waitingToLockMonitor = (ObjectMonitor*)currentThread->current_pending_monitor();
 407       if (concurrent_locks) {
 408         waitingToLockBlocker = currentThread->current_park_blocker();
 409       }
 410     }
 411 
 412   }
 413   delete cycle;
 414   return deadlocks;
 415 }
 416 
 417 ThreadDumpResult::ThreadDumpResult() : _num_threads(0), _num_snapshots(0), _snapshots(NULL), _next(NULL), _last(NULL) {
 418 
 419   // Create a new ThreadDumpResult object and append to the list.
 420   // If GC happens before this function returns, Method*
 421   // in the stack trace will be visited.
 422   ThreadService::add_thread_dump(this);
 423 }
 424 
 425 ThreadDumpResult::ThreadDumpResult(int num_threads) : _num_threads(num_threads), _num_snapshots(0), _snapshots(NULL), _next(NULL), _last(NULL) {
 426   // Create a new ThreadDumpResult object and append to the list.
 427   // If GC happens before this function returns, oops
 428   // will be visited.
 429   ThreadService::add_thread_dump(this);
 430 }
 431 
 432 ThreadDumpResult::~ThreadDumpResult() {
 433   ThreadService::remove_thread_dump(this);
 434 
 435   // free all the ThreadSnapshot objects created during
 436   // the VM_ThreadDump operation
 437   ThreadSnapshot* ts = _snapshots;
 438   while (ts != NULL) {
 439     ThreadSnapshot* p = ts;
 440     ts = ts->next();
 441     delete p;
 442   }
 443 }
 444 
 445 
 446 void ThreadDumpResult::add_thread_snapshot(ThreadSnapshot* ts) {
 447   assert(_num_threads == 0 || _num_snapshots < _num_threads,
 448          "_num_snapshots must be less than _num_threads");
 449   _num_snapshots++;
 450   if (_snapshots == NULL) {
 451     _snapshots = ts;
 452   } else {
 453     _last->set_next(ts);
 454   }
 455   _last = ts;
 456 }
 457 
 458 void ThreadDumpResult::oops_do(OopClosure* f) {
 459   for (ThreadSnapshot* ts = _snapshots; ts != NULL; ts = ts->next()) {
 460     ts->oops_do(f);
 461   }
 462 }
 463 
 464 void ThreadDumpResult::metadata_do(void f(Metadata*)) {
 465   for (ThreadSnapshot* ts = _snapshots; ts != NULL; ts = ts->next()) {
 466     ts->metadata_do(f);
 467   }
 468 }
 469 
 470 StackFrameInfo::StackFrameInfo(javaVFrame* jvf, bool with_lock_info) {
 471   _method = jvf->method();
 472   _bci = jvf->bci();
 473   _class_holder = _method->method_holder()->klass_holder();
 474   _locked_monitors = NULL;
 475   if (with_lock_info) {
 476     ResourceMark rm;
 477     GrowableArray<MonitorInfo*>* list = jvf->locked_monitors();
 478     int length = list->length();
 479     if (length > 0) {
 480       _locked_monitors = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<oop>(length, true);
 481       for (int i = 0; i < length; i++) {
 482         MonitorInfo* monitor = list->at(i);
 483         assert(monitor->owner(), "This monitor must have an owning object");
 484         _locked_monitors->append(monitor->owner());
 485       }
 486     }
 487   }
 488 }
 489 
 490 void StackFrameInfo::oops_do(OopClosure* f) {
 491   if (_locked_monitors != NULL) {
 492     int length = _locked_monitors->length();
 493     for (int i = 0; i < length; i++) {
 494       f->do_oop((oop*) _locked_monitors->adr_at(i));
 495     }
 496   }
 497   f->do_oop(&_class_holder);
 498 }
 499 
 500 void StackFrameInfo::metadata_do(void f(Metadata*)) {
 501   f(_method);
 502 }
 503 
 504 void StackFrameInfo::print_on(outputStream* st) const {
 505   ResourceMark rm;
 506   java_lang_Throwable::print_stack_element(st, method(), bci());
 507   int len = (_locked_monitors != NULL ? _locked_monitors->length() : 0);
 508   for (int i = 0; i < len; i++) {
 509     oop o = _locked_monitors->at(i);
 510     InstanceKlass* ik = InstanceKlass::cast(o->klass());
 511     st->print_cr("\t- locked <" INTPTR_FORMAT "> (a %s)", (address)o, ik->external_name());
 512   }
 513 
 514 }
 515 
 516 // Iterate through monitor cache to find JNI locked monitors
 517 class InflatedMonitorsClosure: public MonitorClosure {
 518 private:
 519   ThreadStackTrace* _stack_trace;
 520   Thread* _thread;
 521 public:
 522   InflatedMonitorsClosure(Thread* t, ThreadStackTrace* st) {
 523     _thread = t;
 524     _stack_trace = st;
 525   }
 526   void do_monitor(ObjectMonitor* mid) {
 527     if (mid->owner() == _thread) {
 528       oop object = (oop) mid->object();
 529       if (!_stack_trace->is_owned_monitor_on_stack(object)) {
 530         _stack_trace->add_jni_locked_monitor(object);
 531       }
 532     }
 533   }
 534 };
 535 
 536 ThreadStackTrace::ThreadStackTrace(JavaThread* t, bool with_locked_monitors) {
 537   _thread = t;
 538   _frames = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<StackFrameInfo*>(INITIAL_ARRAY_SIZE, true);
 539   _depth = 0;
 540   _with_locked_monitors = with_locked_monitors;
 541   if (_with_locked_monitors) {
 542     _jni_locked_monitors = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<oop>(INITIAL_ARRAY_SIZE, true);
 543   } else {
 544     _jni_locked_monitors = NULL;
 545   }
 546 }
 547 
 548 ThreadStackTrace::~ThreadStackTrace() {
 549   for (int i = 0; i < _frames->length(); i++) {
 550     delete _frames->at(i);
 551   }
 552   delete _frames;
 553   if (_jni_locked_monitors != NULL) {
 554     delete _jni_locked_monitors;
 555   }
 556 }
 557 
 558 void ThreadStackTrace::dump_stack_at_safepoint(int maxDepth) {
 559   assert(SafepointSynchronize::is_at_safepoint(), "all threads are stopped");
 560 
 561   if (_thread->has_last_Java_frame()) {
 562     RegisterMap reg_map(_thread);
 563     vframe* start_vf = _thread->last_java_vframe(&reg_map);
 564     int count = 0;
 565     for (vframe* f = start_vf; f; f = f->sender() ) {
 566       if (f->is_java_frame()) {
 567         javaVFrame* jvf = javaVFrame::cast(f);
 568         add_stack_frame(jvf);
 569         count++;
 570       } else {
 571         // Ignore non-Java frames
 572       }
 573       if (maxDepth > 0 && count == maxDepth) {
 574         // Skip frames if more than maxDepth
 575         break;
 576       }
 577     }
 578   }
 579 
 580   if (_with_locked_monitors) {
 581     // Iterate inflated monitors and find monitors locked by this thread
 582     // not found in the stack
 583     InflatedMonitorsClosure imc(_thread, this);
 584     ObjectSynchronizer::monitors_iterate(&imc);
 585   }
 586 }
 587 
 588 
 589 bool ThreadStackTrace::is_owned_monitor_on_stack(oop object) {
 590   assert(SafepointSynchronize::is_at_safepoint(), "all threads are stopped");
 591 
 592   bool found = false;
 593   int num_frames = get_stack_depth();
 594   for (int depth = 0; depth < num_frames; depth++) {
 595     StackFrameInfo* frame = stack_frame_at(depth);
 596     int len = frame->num_locked_monitors();
 597     GrowableArray<oop>* locked_monitors = frame->locked_monitors();
 598     for (int j = 0; j < len; j++) {
 599       oop monitor = locked_monitors->at(j);
 600       assert(monitor != NULL && monitor->is_instance(), "must be a Java object");
 601       if (monitor == object) {
 602         found = true;
 603         break;
 604       }
 605     }
 606   }
 607   return found;
 608 }
 609 
 610 Handle ThreadStackTrace::allocate_fill_stack_trace_element_array(TRAPS) {
 611   Klass* k = SystemDictionary::StackTraceElement_klass();
 612   assert(k != NULL, "must be loaded in 1.4+");
 613   instanceKlassHandle ik(THREAD, k);
 614 
 615   // Allocate an array of java/lang/StackTraceElement object
 616   objArrayOop ste = oopFactory::new_objArray(ik(), _depth, CHECK_NH);
 617   objArrayHandle backtrace(THREAD, ste);
 618   for (int j = 0; j < _depth; j++) {
 619     StackFrameInfo* frame = _frames->at(j);
 620     methodHandle mh(THREAD, frame->method());
 621     oop element = java_lang_StackTraceElement::create(mh, frame->bci(), CHECK_NH);
 622     backtrace->obj_at_put(j, element);
 623   }
 624   return backtrace;
 625 }
 626 
 627 void ThreadStackTrace::add_stack_frame(javaVFrame* jvf) {
 628   StackFrameInfo* frame = new StackFrameInfo(jvf, _with_locked_monitors);
 629   _frames->append(frame);
 630   _depth++;
 631 }
 632 
 633 void ThreadStackTrace::oops_do(OopClosure* f) {
 634   int length = _frames->length();
 635   for (int i = 0; i < length; i++) {
 636     _frames->at(i)->oops_do(f);
 637   }
 638 
 639   length = (_jni_locked_monitors != NULL ? _jni_locked_monitors->length() : 0);
 640   for (int j = 0; j < length; j++) {
 641     f->do_oop((oop*) _jni_locked_monitors->adr_at(j));
 642   }
 643 }
 644 
 645 void ThreadStackTrace::metadata_do(void f(Metadata*)) {
 646   int length = _frames->length();
 647   for (int i = 0; i < length; i++) {
 648     _frames->at(i)->metadata_do(f);
 649   }
 650 }
 651 
 652 
 653 ConcurrentLocksDump::~ConcurrentLocksDump() {
 654   if (_retain_map_on_free) {
 655     return;
 656   }
 657 
 658   for (ThreadConcurrentLocks* t = _map; t != NULL;)  {
 659     ThreadConcurrentLocks* tcl = t;
 660     t = t->next();
 661     delete tcl;
 662   }
 663 }
 664 
 665 void ConcurrentLocksDump::dump_at_safepoint() {
 666   // dump all locked concurrent locks
 667   assert(SafepointSynchronize::is_at_safepoint(), "all threads are stopped");
 668 
 669   if (JDK_Version::is_gte_jdk16x_version()) {
 670     ResourceMark rm;
 671 
 672     GrowableArray<oop>* aos_objects = new GrowableArray<oop>(INITIAL_ARRAY_SIZE);
 673 
 674     // Find all instances of AbstractOwnableSynchronizer
 675     HeapInspection::find_instances_at_safepoint(SystemDictionary::abstract_ownable_synchronizer_klass(),
 676                                                 aos_objects);
 677     // Build a map of thread to its owned AQS locks
 678     build_map(aos_objects);
 679   }
 680 }
 681 
 682 
 683 // build a map of JavaThread to all its owned AbstractOwnableSynchronizer
 684 void ConcurrentLocksDump::build_map(GrowableArray<oop>* aos_objects) {
 685   int length = aos_objects->length();
 686   for (int i = 0; i < length; i++) {
 687     oop o = aos_objects->at(i);
 688     oop owner_thread_obj = java_util_concurrent_locks_AbstractOwnableSynchronizer::get_owner_threadObj(o);
 689     if (owner_thread_obj != NULL) {
 690       JavaThread* thread = java_lang_Thread::thread(owner_thread_obj);
 691       assert(o->is_instance(), "Must be an instanceOop");
 692       add_lock(thread, (instanceOop) o);
 693     }
 694   }
 695 }
 696 
 697 void ConcurrentLocksDump::add_lock(JavaThread* thread, instanceOop o) {
 698   ThreadConcurrentLocks* tcl = thread_concurrent_locks(thread);
 699   if (tcl != NULL) {
 700     tcl->add_lock(o);
 701     return;
 702   }
 703 
 704   // First owned lock found for this thread
 705   tcl = new ThreadConcurrentLocks(thread);
 706   tcl->add_lock(o);
 707   if (_map == NULL) {
 708     _map = tcl;
 709   } else {
 710     _last->set_next(tcl);
 711   }
 712   _last = tcl;
 713 }
 714 
 715 ThreadConcurrentLocks* ConcurrentLocksDump::thread_concurrent_locks(JavaThread* thread) {
 716   for (ThreadConcurrentLocks* tcl = _map; tcl != NULL; tcl = tcl->next()) {
 717     if (tcl->java_thread() == thread) {
 718       return tcl;
 719     }
 720   }
 721   return NULL;
 722 }
 723 
 724 void ConcurrentLocksDump::print_locks_on(JavaThread* t, outputStream* st) {
 725   st->print_cr("   Locked ownable synchronizers:");
 726   ThreadConcurrentLocks* tcl = thread_concurrent_locks(t);
 727   GrowableArray<instanceOop>* locks = (tcl != NULL ? tcl->owned_locks() : NULL);
 728   if (locks == NULL || locks->is_empty()) {
 729     st->print_cr("\t- None");
 730     st->cr();
 731     return;
 732   }
 733 
 734   for (int i = 0; i < locks->length(); i++) {
 735     instanceOop obj = locks->at(i);
 736     InstanceKlass* ik = InstanceKlass::cast(obj->klass());
 737     st->print_cr("\t- <" INTPTR_FORMAT "> (a %s)", (address)obj, ik->external_name());
 738   }
 739   st->cr();
 740 }
 741 
 742 ThreadConcurrentLocks::ThreadConcurrentLocks(JavaThread* thread) {
 743   _thread = thread;
 744   _owned_locks = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<instanceOop>(INITIAL_ARRAY_SIZE, true);
 745   _next = NULL;
 746 }
 747 
 748 ThreadConcurrentLocks::~ThreadConcurrentLocks() {
 749   delete _owned_locks;
 750 }
 751 
 752 void ThreadConcurrentLocks::add_lock(instanceOop o) {
 753   _owned_locks->append(o);
 754 }
 755 
 756 void ThreadConcurrentLocks::oops_do(OopClosure* f) {
 757   int length = _owned_locks->length();
 758   for (int i = 0; i < length; i++) {
 759     f->do_oop((oop*) _owned_locks->adr_at(i));
 760   }
 761 }
 762 
 763 ThreadStatistics::ThreadStatistics() {
 764   _contended_enter_count = 0;
 765   _monitor_wait_count = 0;
 766   _sleep_count = 0;
 767   _count_pending_reset = false;
 768   _timer_pending_reset = false;
 769   memset((void*) _perf_recursion_counts, 0, sizeof(_perf_recursion_counts));
 770 }
 771 
 772 ThreadSnapshot::ThreadSnapshot(JavaThread* thread) {
 773   _thread = thread;
 774   _threadObj = thread->threadObj();
 775   _stack_trace = NULL;
 776   _concurrent_locks = NULL;
 777   _next = NULL;
 778 
 779   ThreadStatistics* stat = thread->get_thread_stat();
 780   _contended_enter_ticks = stat->contended_enter_ticks();
 781   _contended_enter_count = stat->contended_enter_count();
 782   _monitor_wait_ticks = stat->monitor_wait_ticks();
 783   _monitor_wait_count = stat->monitor_wait_count();
 784   _sleep_ticks = stat->sleep_ticks();
 785   _sleep_count = stat->sleep_count();
 786 
 787   _blocker_object = NULL;
 788   _blocker_object_owner = NULL;
 789 
 790   _thread_status = java_lang_Thread::get_thread_status(_threadObj);
 791   _is_ext_suspended = thread->is_being_ext_suspended();
 792   _is_in_native = (thread->thread_state() == _thread_in_native);
 793 
 794   if (_thread_status == java_lang_Thread::BLOCKED_ON_MONITOR_ENTER ||
 795       _thread_status == java_lang_Thread::IN_OBJECT_WAIT ||
 796       _thread_status == java_lang_Thread::IN_OBJECT_WAIT_TIMED) {
 797 
 798     Handle obj = ThreadService::get_current_contended_monitor(thread);
 799     if (obj() == NULL) {
 800       // monitor no longer exists; thread is not blocked
 801       _thread_status = java_lang_Thread::RUNNABLE;
 802     } else {
 803       _blocker_object = obj();
 804       JavaThread* owner = ObjectSynchronizer::get_lock_owner(obj, false);
 805       if ((owner == NULL && _thread_status == java_lang_Thread::BLOCKED_ON_MONITOR_ENTER)
 806           || (owner != NULL && owner->is_attaching_via_jni())) {
 807         // ownership information of the monitor is not available
 808         // (may no longer be owned or releasing to some other thread)
 809         // make this thread in RUNNABLE state.
 810         // And when the owner thread is in attaching state, the java thread
 811         // is not completely initialized. For example thread name and id
 812         // and may not be set, so hide the attaching thread.
 813         _thread_status = java_lang_Thread::RUNNABLE;
 814         _blocker_object = NULL;
 815       } else if (owner != NULL) {
 816         _blocker_object_owner = owner->threadObj();
 817       }
 818     }
 819   }
 820 
 821   // Support for JSR-166 locks
 822   if (JDK_Version::current().supports_thread_park_blocker() &&
 823         (_thread_status == java_lang_Thread::PARKED ||
 824          _thread_status == java_lang_Thread::PARKED_TIMED)) {
 825 
 826     _blocker_object = thread->current_park_blocker();
 827     if (_blocker_object != NULL && _blocker_object->is_a(SystemDictionary::abstract_ownable_synchronizer_klass())) {
 828       _blocker_object_owner = java_util_concurrent_locks_AbstractOwnableSynchronizer::get_owner_threadObj(_blocker_object);
 829     }
 830   }
 831 }
 832 
 833 ThreadSnapshot::~ThreadSnapshot() {
 834   delete _stack_trace;
 835   delete _concurrent_locks;
 836 }
 837 
 838 void ThreadSnapshot::dump_stack_at_safepoint(int max_depth, bool with_locked_monitors) {
 839   _stack_trace = new ThreadStackTrace(_thread, with_locked_monitors);
 840   _stack_trace->dump_stack_at_safepoint(max_depth);
 841 }
 842 
 843 
 844 void ThreadSnapshot::oops_do(OopClosure* f) {
 845   f->do_oop(&_threadObj);
 846   f->do_oop(&_blocker_object);
 847   f->do_oop(&_blocker_object_owner);
 848   if (_stack_trace != NULL) {
 849     _stack_trace->oops_do(f);
 850   }
 851   if (_concurrent_locks != NULL) {
 852     _concurrent_locks->oops_do(f);
 853   }
 854 }
 855 
 856 void ThreadSnapshot::metadata_do(void f(Metadata*)) {
 857   if (_stack_trace != NULL) {
 858     _stack_trace->metadata_do(f);
 859   }
 860 }
 861 
 862 
 863 DeadlockCycle::DeadlockCycle() {
 864   _is_deadlock = false;
 865   _threads = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<JavaThread*>(INITIAL_ARRAY_SIZE, true);
 866   _next = NULL;
 867 }
 868 
 869 DeadlockCycle::~DeadlockCycle() {
 870   delete _threads;
 871 }
 872 
 873 void DeadlockCycle::print_on(outputStream* st) const {
 874   st->cr();
 875   st->print_cr("Found one Java-level deadlock:");
 876   st->print("=============================");
 877 
 878   JavaThread* currentThread;
 879   ObjectMonitor* waitingToLockMonitor;
 880   oop waitingToLockBlocker;
 881   int len = _threads->length();
 882   for (int i = 0; i < len; i++) {
 883     currentThread = _threads->at(i);
 884     waitingToLockMonitor = (ObjectMonitor*)currentThread->current_pending_monitor();
 885     waitingToLockBlocker = currentThread->current_park_blocker();
 886     st->cr();
 887     st->print_cr("\"%s\":", currentThread->get_thread_name());
 888     const char* owner_desc = ",\n  which is held by";
 889     if (waitingToLockMonitor != NULL) {
 890       st->print("  waiting to lock monitor " INTPTR_FORMAT, waitingToLockMonitor);
 891       oop obj = (oop)waitingToLockMonitor->object();
 892       if (obj != NULL) {
 893         st->print(" (object "INTPTR_FORMAT ", a %s)", (address)obj,
 894                    (InstanceKlass::cast(obj->klass()))->external_name());
 895 
 896         if (!currentThread->current_pending_monitor_is_from_java()) {
 897           owner_desc = "\n  in JNI, which is held by";
 898         }
 899       } else {
 900         // No Java object associated - a JVMTI raw monitor
 901         owner_desc = " (JVMTI raw monitor),\n  which is held by";
 902       }
 903       currentThread = Threads::owning_thread_from_monitor_owner(
 904                         (address)waitingToLockMonitor->owner(),
 905                         false /* no locking needed */);
 906       if (currentThread == NULL) {
 907         // The deadlock was detected at a safepoint so the JavaThread
 908         // that owns waitingToLockMonitor should be findable, but
 909         // if it is not findable, then the previous currentThread is
 910         // blocked permanently.
 911         st->print("%s UNKNOWN_owner_addr=" PTR_FORMAT, owner_desc,
 912                   (address)waitingToLockMonitor->owner());
 913         continue;
 914       }
 915     } else {
 916       st->print("  waiting for ownable synchronizer " INTPTR_FORMAT ", (a %s)",
 917                 (address)waitingToLockBlocker,
 918                 (InstanceKlass::cast(waitingToLockBlocker->klass()))->external_name());
 919       assert(waitingToLockBlocker->is_a(SystemDictionary::abstract_ownable_synchronizer_klass()),
 920              "Must be an AbstractOwnableSynchronizer");
 921       oop ownerObj = java_util_concurrent_locks_AbstractOwnableSynchronizer::get_owner_threadObj(waitingToLockBlocker);
 922       currentThread = java_lang_Thread::thread(ownerObj);
 923     }
 924     st->print("%s \"%s\"", owner_desc, currentThread->get_thread_name());
 925   }
 926 
 927   st->cr();
 928   st->cr();
 929 
 930   // Print stack traces
 931   bool oldJavaMonitorsInStackTrace = JavaMonitorsInStackTrace;
 932   JavaMonitorsInStackTrace = true;
 933   st->print_cr("Java stack information for the threads listed above:");
 934   st->print_cr("===================================================");
 935   for (int j = 0; j < len; j++) {
 936     currentThread = _threads->at(j);
 937     st->print_cr("\"%s\":", currentThread->get_thread_name());
 938     currentThread->print_stack_on(st);
 939   }
 940   JavaMonitorsInStackTrace = oldJavaMonitorsInStackTrace;
 941 }
 942 
 943 ThreadsListEnumerator::ThreadsListEnumerator(Thread* cur_thread,
 944                                              bool include_jvmti_agent_threads,
 945                                              bool include_jni_attaching_threads) {
 946   assert(cur_thread == Thread::current(), "Check current thread");
 947 
 948   int init_size = ThreadService::get_live_thread_count();
 949   _threads_array = new GrowableArray<instanceHandle>(init_size);
 950 
 951   MutexLockerEx ml(Threads_lock);
 952 
 953   for (JavaThread* jt = Threads::first(); jt != NULL; jt = jt->next()) {
 954     // skips JavaThreads in the process of exiting
 955     // and also skips VM internal JavaThreads
 956     // Threads in _thread_new or _thread_new_trans state are included.
 957     // i.e. threads have been started but not yet running.
 958     if (jt->threadObj() == NULL   ||
 959         jt->is_exiting() ||
 960         !java_lang_Thread::is_alive(jt->threadObj())   ||
 961         jt->is_hidden_from_external_view()) {
 962       continue;
 963     }
 964 
 965     // skip agent threads
 966     if (!include_jvmti_agent_threads && jt->is_jvmti_agent_thread()) {
 967       continue;
 968     }
 969 
 970     // skip jni threads in the process of attaching
 971     if (!include_jni_attaching_threads && jt->is_attaching_via_jni()) {
 972       continue;
 973     }
 974 
 975     instanceHandle h(cur_thread, (instanceOop) jt->threadObj());
 976     _threads_array->append(h);
 977   }
 978 }