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