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), _last(NULL), _next(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), _last(NULL), _next(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 GrowableArray<MonitorInfo*>* list = jvf->locked_monitors();
560 int length = list->length();
561 if (length > 0) {
562 _locked_monitors = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<oop>(length, true);
563 for (int i = 0; i < length; i++) {
564 MonitorInfo* monitor = list->at(i);
565 assert(monitor->owner() != NULL, "This monitor must have an owning object");
566 _locked_monitors->append(monitor->owner());
567 }
568 }
569 }
570 }
571
oops_do(OopClosure * f)572 void StackFrameInfo::oops_do(OopClosure* f) {
573 if (_locked_monitors != NULL) {
574 int length = _locked_monitors->length();
575 for (int i = 0; i < length; i++) {
576 f->do_oop((oop*) _locked_monitors->adr_at(i));
577 }
578 }
579 f->do_oop(&_class_holder);
580 }
581
metadata_do(void f (Metadata *))582 void StackFrameInfo::metadata_do(void f(Metadata*)) {
583 f(_method);
584 }
585
print_on(outputStream * st) const586 void StackFrameInfo::print_on(outputStream* st) const {
587 ResourceMark rm;
588 java_lang_Throwable::print_stack_element(st, method(), bci());
589 int len = (_locked_monitors != NULL ? _locked_monitors->length() : 0);
590 for (int i = 0; i < len; i++) {
591 oop o = _locked_monitors->at(i);
592 st->print_cr("\t- locked <" INTPTR_FORMAT "> (a %s)", p2i(o), o->klass()->external_name());
593 }
594
595 }
596
597 // Iterate through monitor cache to find JNI locked monitors
598 class InflatedMonitorsClosure: public MonitorClosure {
599 private:
600 ThreadStackTrace* _stack_trace;
601 Thread* _thread;
602 public:
InflatedMonitorsClosure(Thread * t,ThreadStackTrace * st)603 InflatedMonitorsClosure(Thread* t, ThreadStackTrace* st) {
604 _thread = t;
605 _stack_trace = st;
606 }
do_monitor(ObjectMonitor * mid)607 void do_monitor(ObjectMonitor* mid) {
608 if (mid->owner() == _thread) {
609 oop object = (oop) mid->object();
610 if (!_stack_trace->is_owned_monitor_on_stack(object)) {
611 _stack_trace->add_jni_locked_monitor(object);
612 }
613 }
614 }
615 };
616
ThreadStackTrace(JavaThread * t,bool with_locked_monitors)617 ThreadStackTrace::ThreadStackTrace(JavaThread* t, bool with_locked_monitors) {
618 _thread = t;
619 _frames = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<StackFrameInfo*>(INITIAL_ARRAY_SIZE, true);
620 _depth = 0;
621 _with_locked_monitors = with_locked_monitors;
622 if (_with_locked_monitors) {
623 _jni_locked_monitors = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<oop>(INITIAL_ARRAY_SIZE, true);
624 } else {
625 _jni_locked_monitors = NULL;
626 }
627 }
628
~ThreadStackTrace()629 ThreadStackTrace::~ThreadStackTrace() {
630 for (int i = 0; i < _frames->length(); i++) {
631 delete _frames->at(i);
632 }
633 delete _frames;
634 if (_jni_locked_monitors != NULL) {
635 delete _jni_locked_monitors;
636 }
637 }
638
dump_stack_at_safepoint(int maxDepth)639 void ThreadStackTrace::dump_stack_at_safepoint(int maxDepth) {
640 assert(SafepointSynchronize::is_at_safepoint(), "all threads are stopped");
641
642 if (_thread->has_last_Java_frame()) {
643 RegisterMap reg_map(_thread);
644 vframe* start_vf = _thread->last_java_vframe(®_map);
645 int count = 0;
646 for (vframe* f = start_vf; f; f = f->sender() ) {
647 if (maxDepth >= 0 && count == maxDepth) {
648 // Skip frames if more than maxDepth
649 break;
650 }
651 if (f->is_java_frame()) {
652 javaVFrame* jvf = javaVFrame::cast(f);
653 add_stack_frame(jvf);
654 count++;
655 } else {
656 // Ignore non-Java frames
657 }
658 }
659 }
660
661 if (_with_locked_monitors) {
662 // Iterate inflated monitors and find monitors locked by this thread
663 // not found in the stack
664 InflatedMonitorsClosure imc(_thread, this);
665 ObjectSynchronizer::monitors_iterate(&imc);
666 }
667 }
668
669
is_owned_monitor_on_stack(oop object)670 bool ThreadStackTrace::is_owned_monitor_on_stack(oop object) {
671 assert(SafepointSynchronize::is_at_safepoint(), "all threads are stopped");
672
673 bool found = false;
674 int num_frames = get_stack_depth();
675 for (int depth = 0; depth < num_frames; depth++) {
676 StackFrameInfo* frame = stack_frame_at(depth);
677 int len = frame->num_locked_monitors();
678 GrowableArray<oop>* locked_monitors = frame->locked_monitors();
679 for (int j = 0; j < len; j++) {
680 oop monitor = locked_monitors->at(j);
681 assert(monitor != NULL, "must be a Java object");
682 if (oopDesc::equals(monitor, object)) {
683 found = true;
684 break;
685 }
686 }
687 }
688 return found;
689 }
690
allocate_fill_stack_trace_element_array(TRAPS)691 Handle ThreadStackTrace::allocate_fill_stack_trace_element_array(TRAPS) {
692 InstanceKlass* ik = SystemDictionary::StackTraceElement_klass();
693 assert(ik != NULL, "must be loaded in 1.4+");
694
695 // Allocate an array of java/lang/StackTraceElement object
696 objArrayOop ste = oopFactory::new_objArray(ik, _depth, CHECK_NH);
697 objArrayHandle backtrace(THREAD, ste);
698 for (int j = 0; j < _depth; j++) {
699 StackFrameInfo* frame = _frames->at(j);
700 methodHandle mh(THREAD, frame->method());
701 oop element = java_lang_StackTraceElement::create(mh, frame->bci(), CHECK_NH);
702 backtrace->obj_at_put(j, element);
703 }
704 return backtrace;
705 }
706
add_stack_frame(javaVFrame * jvf)707 void ThreadStackTrace::add_stack_frame(javaVFrame* jvf) {
708 StackFrameInfo* frame = new StackFrameInfo(jvf, _with_locked_monitors);
709 _frames->append(frame);
710 _depth++;
711 }
712
oops_do(OopClosure * f)713 void ThreadStackTrace::oops_do(OopClosure* f) {
714 int length = _frames->length();
715 for (int i = 0; i < length; i++) {
716 _frames->at(i)->oops_do(f);
717 }
718
719 length = (_jni_locked_monitors != NULL ? _jni_locked_monitors->length() : 0);
720 for (int j = 0; j < length; j++) {
721 f->do_oop((oop*) _jni_locked_monitors->adr_at(j));
722 }
723 }
724
metadata_do(void f (Metadata *))725 void ThreadStackTrace::metadata_do(void f(Metadata*)) {
726 int length = _frames->length();
727 for (int i = 0; i < length; i++) {
728 _frames->at(i)->metadata_do(f);
729 }
730 }
731
732
~ConcurrentLocksDump()733 ConcurrentLocksDump::~ConcurrentLocksDump() {
734 if (_retain_map_on_free) {
735 return;
736 }
737
738 for (ThreadConcurrentLocks* t = _map; t != NULL;) {
739 ThreadConcurrentLocks* tcl = t;
740 t = t->next();
741 delete tcl;
742 }
743 }
744
dump_at_safepoint()745 void ConcurrentLocksDump::dump_at_safepoint() {
746 // dump all locked concurrent locks
747 assert(SafepointSynchronize::is_at_safepoint(), "all threads are stopped");
748
749 GrowableArray<oop>* aos_objects = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<oop>(INITIAL_ARRAY_SIZE, true /* C_heap */);
750
751 // Find all instances of AbstractOwnableSynchronizer
752 HeapInspection::find_instances_at_safepoint(SystemDictionary::java_util_concurrent_locks_AbstractOwnableSynchronizer_klass(),
753 aos_objects);
754 // Build a map of thread to its owned AQS locks
755 build_map(aos_objects);
756
757 delete aos_objects;
758 }
759
760
761 // build a map of JavaThread to all its owned AbstractOwnableSynchronizer
build_map(GrowableArray<oop> * aos_objects)762 void ConcurrentLocksDump::build_map(GrowableArray<oop>* aos_objects) {
763 int length = aos_objects->length();
764 for (int i = 0; i < length; i++) {
765 oop o = aos_objects->at(i);
766 oop owner_thread_obj = java_util_concurrent_locks_AbstractOwnableSynchronizer::get_owner_threadObj(o);
767 if (owner_thread_obj != NULL) {
768 // See comments in ThreadConcurrentLocks to see how this
769 // JavaThread* is protected.
770 JavaThread* thread = java_lang_Thread::thread(owner_thread_obj);
771 assert(o->is_instance(), "Must be an instanceOop");
772 add_lock(thread, (instanceOop) o);
773 }
774 }
775 }
776
add_lock(JavaThread * thread,instanceOop o)777 void ConcurrentLocksDump::add_lock(JavaThread* thread, instanceOop o) {
778 ThreadConcurrentLocks* tcl = thread_concurrent_locks(thread);
779 if (tcl != NULL) {
780 tcl->add_lock(o);
781 return;
782 }
783
784 // First owned lock found for this thread
785 tcl = new ThreadConcurrentLocks(thread);
786 tcl->add_lock(o);
787 if (_map == NULL) {
788 _map = tcl;
789 } else {
790 _last->set_next(tcl);
791 }
792 _last = tcl;
793 }
794
thread_concurrent_locks(JavaThread * thread)795 ThreadConcurrentLocks* ConcurrentLocksDump::thread_concurrent_locks(JavaThread* thread) {
796 for (ThreadConcurrentLocks* tcl = _map; tcl != NULL; tcl = tcl->next()) {
797 if (tcl->java_thread() == thread) {
798 return tcl;
799 }
800 }
801 return NULL;
802 }
803
print_locks_on(JavaThread * t,outputStream * st)804 void ConcurrentLocksDump::print_locks_on(JavaThread* t, outputStream* st) {
805 st->print_cr(" Locked ownable synchronizers:");
806 ThreadConcurrentLocks* tcl = thread_concurrent_locks(t);
807 GrowableArray<instanceOop>* locks = (tcl != NULL ? tcl->owned_locks() : NULL);
808 if (locks == NULL || locks->is_empty()) {
809 st->print_cr("\t- None");
810 st->cr();
811 return;
812 }
813
814 for (int i = 0; i < locks->length(); i++) {
815 instanceOop obj = locks->at(i);
816 st->print_cr("\t- <" INTPTR_FORMAT "> (a %s)", p2i(obj), obj->klass()->external_name());
817 }
818 st->cr();
819 }
820
ThreadConcurrentLocks(JavaThread * thread)821 ThreadConcurrentLocks::ThreadConcurrentLocks(JavaThread* thread) {
822 _thread = thread;
823 _owned_locks = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<instanceOop>(INITIAL_ARRAY_SIZE, true);
824 _next = NULL;
825 }
826
~ThreadConcurrentLocks()827 ThreadConcurrentLocks::~ThreadConcurrentLocks() {
828 delete _owned_locks;
829 }
830
add_lock(instanceOop o)831 void ThreadConcurrentLocks::add_lock(instanceOop o) {
832 _owned_locks->append(o);
833 }
834
oops_do(OopClosure * f)835 void ThreadConcurrentLocks::oops_do(OopClosure* f) {
836 int length = _owned_locks->length();
837 for (int i = 0; i < length; i++) {
838 f->do_oop((oop*) _owned_locks->adr_at(i));
839 }
840 }
841
ThreadStatistics()842 ThreadStatistics::ThreadStatistics() {
843 _contended_enter_count = 0;
844 _monitor_wait_count = 0;
845 _sleep_count = 0;
846 _count_pending_reset = false;
847 _timer_pending_reset = false;
848 memset((void*) _perf_recursion_counts, 0, sizeof(_perf_recursion_counts));
849 }
850
initialize(ThreadsList * t_list,JavaThread * thread)851 void ThreadSnapshot::initialize(ThreadsList * t_list, JavaThread* thread) {
852 _thread = thread;
853 _threadObj = thread->threadObj();
854
855 ThreadStatistics* stat = thread->get_thread_stat();
856 _contended_enter_ticks = stat->contended_enter_ticks();
857 _contended_enter_count = stat->contended_enter_count();
858 _monitor_wait_ticks = stat->monitor_wait_ticks();
859 _monitor_wait_count = stat->monitor_wait_count();
860 _sleep_ticks = stat->sleep_ticks();
861 _sleep_count = stat->sleep_count();
862
863 _thread_status = java_lang_Thread::get_thread_status(_threadObj);
864 _is_ext_suspended = thread->is_being_ext_suspended();
865 _is_in_native = (thread->thread_state() == _thread_in_native);
866
867 if (_thread_status == java_lang_Thread::BLOCKED_ON_MONITOR_ENTER ||
868 _thread_status == java_lang_Thread::IN_OBJECT_WAIT ||
869 _thread_status == java_lang_Thread::IN_OBJECT_WAIT_TIMED) {
870
871 Handle obj = ThreadService::get_current_contended_monitor(thread);
872 if (obj() == NULL) {
873 // monitor no longer exists; thread is not blocked
874 _thread_status = java_lang_Thread::RUNNABLE;
875 } else {
876 _blocker_object = obj();
877 JavaThread* owner = ObjectSynchronizer::get_lock_owner(t_list, obj);
878 if ((owner == NULL && _thread_status == java_lang_Thread::BLOCKED_ON_MONITOR_ENTER)
879 || (owner != NULL && owner->is_attaching_via_jni())) {
880 // ownership information of the monitor is not available
881 // (may no longer be owned or releasing to some other thread)
882 // make this thread in RUNNABLE state.
883 // And when the owner thread is in attaching state, the java thread
884 // is not completely initialized. For example thread name and id
885 // and may not be set, so hide the attaching thread.
886 _thread_status = java_lang_Thread::RUNNABLE;
887 _blocker_object = NULL;
888 } else if (owner != NULL) {
889 _blocker_object_owner = owner->threadObj();
890 }
891 }
892 }
893
894 // Support for JSR-166 locks
895 if (JDK_Version::current().supports_thread_park_blocker() &&
896 (_thread_status == java_lang_Thread::PARKED ||
897 _thread_status == java_lang_Thread::PARKED_TIMED)) {
898
899 _blocker_object = thread->current_park_blocker();
900 if (_blocker_object != NULL && _blocker_object->is_a(SystemDictionary::java_util_concurrent_locks_AbstractOwnableSynchronizer_klass())) {
901 _blocker_object_owner = java_util_concurrent_locks_AbstractOwnableSynchronizer::get_owner_threadObj(_blocker_object);
902 }
903 }
904 }
905
~ThreadSnapshot()906 ThreadSnapshot::~ThreadSnapshot() {
907 delete _stack_trace;
908 delete _concurrent_locks;
909 }
910
dump_stack_at_safepoint(int max_depth,bool with_locked_monitors)911 void ThreadSnapshot::dump_stack_at_safepoint(int max_depth, bool with_locked_monitors) {
912 _stack_trace = new ThreadStackTrace(_thread, with_locked_monitors);
913 _stack_trace->dump_stack_at_safepoint(max_depth);
914 }
915
916
oops_do(OopClosure * f)917 void ThreadSnapshot::oops_do(OopClosure* f) {
918 f->do_oop(&_threadObj);
919 f->do_oop(&_blocker_object);
920 f->do_oop(&_blocker_object_owner);
921 if (_stack_trace != NULL) {
922 _stack_trace->oops_do(f);
923 }
924 if (_concurrent_locks != NULL) {
925 _concurrent_locks->oops_do(f);
926 }
927 }
928
metadata_do(void f (Metadata *))929 void ThreadSnapshot::metadata_do(void f(Metadata*)) {
930 if (_stack_trace != NULL) {
931 _stack_trace->metadata_do(f);
932 }
933 }
934
935
DeadlockCycle()936 DeadlockCycle::DeadlockCycle() {
937 _is_deadlock = false;
938 _threads = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<JavaThread*>(INITIAL_ARRAY_SIZE, true);
939 _next = NULL;
940 }
941
~DeadlockCycle()942 DeadlockCycle::~DeadlockCycle() {
943 delete _threads;
944 }
945
print_on_with(ThreadsList * t_list,outputStream * st) const946 void DeadlockCycle::print_on_with(ThreadsList * t_list, outputStream* st) const {
947 st->cr();
948 st->print_cr("Found one Java-level deadlock:");
949 st->print("=============================");
950
951 JavaThread* currentThread;
952 ObjectMonitor* waitingToLockMonitor;
953 oop waitingToLockBlocker;
954 int len = _threads->length();
955 for (int i = 0; i < len; i++) {
956 currentThread = _threads->at(i);
957 waitingToLockMonitor = (ObjectMonitor*)currentThread->current_pending_monitor();
958 waitingToLockBlocker = currentThread->current_park_blocker();
959 st->cr();
960 st->print_cr("\"%s\":", currentThread->get_thread_name());
961 const char* owner_desc = ",\n which is held by";
962 if (waitingToLockMonitor != NULL) {
963 st->print(" waiting to lock monitor " INTPTR_FORMAT, p2i(waitingToLockMonitor));
964 oop obj = (oop)waitingToLockMonitor->object();
965 if (obj != NULL) {
966 st->print(" (object " INTPTR_FORMAT ", a %s)", p2i(obj),
967 obj->klass()->external_name());
968
969 if (!currentThread->current_pending_monitor_is_from_java()) {
970 owner_desc = "\n in JNI, which is held by";
971 }
972 } else {
973 // No Java object associated - a JVMTI raw monitor
974 owner_desc = " (JVMTI raw monitor),\n which is held by";
975 }
976 currentThread = Threads::owning_thread_from_monitor_owner(t_list,
977 (address)waitingToLockMonitor->owner());
978 if (currentThread == NULL) {
979 // The deadlock was detected at a safepoint so the JavaThread
980 // that owns waitingToLockMonitor should be findable, but
981 // if it is not findable, then the previous currentThread is
982 // blocked permanently.
983 st->print("%s UNKNOWN_owner_addr=" PTR_FORMAT, owner_desc,
984 p2i(waitingToLockMonitor->owner()));
985 continue;
986 }
987 } else {
988 st->print(" waiting for ownable synchronizer " INTPTR_FORMAT ", (a %s)",
989 p2i(waitingToLockBlocker),
990 waitingToLockBlocker->klass()->external_name());
991 assert(waitingToLockBlocker->is_a(SystemDictionary::java_util_concurrent_locks_AbstractOwnableSynchronizer_klass()),
992 "Must be an AbstractOwnableSynchronizer");
993 oop ownerObj = java_util_concurrent_locks_AbstractOwnableSynchronizer::get_owner_threadObj(waitingToLockBlocker);
994 currentThread = java_lang_Thread::thread(ownerObj);
995 assert(currentThread != NULL, "AbstractOwnableSynchronizer owning thread is unexpectedly NULL");
996 }
997 st->print("%s \"%s\"", owner_desc, currentThread->get_thread_name());
998 }
999
1000 st->cr();
1001 st->cr();
1002
1003 // Print stack traces
1004 bool oldJavaMonitorsInStackTrace = JavaMonitorsInStackTrace;
1005 JavaMonitorsInStackTrace = true;
1006 st->print_cr("Java stack information for the threads listed above:");
1007 st->print_cr("===================================================");
1008 for (int j = 0; j < len; j++) {
1009 currentThread = _threads->at(j);
1010 st->print_cr("\"%s\":", currentThread->get_thread_name());
1011 currentThread->print_stack_on(st);
1012 }
1013 JavaMonitorsInStackTrace = oldJavaMonitorsInStackTrace;
1014 }
1015
ThreadsListEnumerator(Thread * cur_thread,bool include_jvmti_agent_threads,bool include_jni_attaching_threads)1016 ThreadsListEnumerator::ThreadsListEnumerator(Thread* cur_thread,
1017 bool include_jvmti_agent_threads,
1018 bool include_jni_attaching_threads) {
1019 assert(cur_thread == Thread::current(), "Check current thread");
1020
1021 int init_size = ThreadService::get_live_thread_count();
1022 _threads_array = new GrowableArray<instanceHandle>(init_size);
1023
1024 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *jt = jtiwh.next(); ) {
1025 // skips JavaThreads in the process of exiting
1026 // and also skips VM internal JavaThreads
1027 // Threads in _thread_new or _thread_new_trans state are included.
1028 // i.e. threads have been started but not yet running.
1029 if (jt->threadObj() == NULL ||
1030 jt->is_exiting() ||
1031 !java_lang_Thread::is_alive(jt->threadObj()) ||
1032 jt->is_hidden_from_external_view()) {
1033 continue;
1034 }
1035
1036 // skip agent threads
1037 if (!include_jvmti_agent_threads && jt->is_jvmti_agent_thread()) {
1038 continue;
1039 }
1040
1041 // skip jni threads in the process of attaching
1042 if (!include_jni_attaching_threads && jt->is_attaching_via_jni()) {
1043 continue;
1044 }
1045
1046 instanceHandle h(cur_thread, (instanceOop) jt->threadObj());
1047 _threads_array->append(h);
1048 }
1049 }
1050