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