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 "precompiled.hpp"
  26 #include "classfile/classLoader.hpp"
  27 #include "classfile/systemDictionary.hpp"
  28 #include "classfile/vmClasses.hpp"
  29 #include "compiler/compileBroker.hpp"
  30 #include "gc/shared/collectedHeap.hpp"
  31 #include "jmm.h"
  32 #include "memory/allocation.inline.hpp"
  33 #include "memory/iterator.hpp"
  34 #include "memory/oopFactory.hpp"
  35 #include "memory/resourceArea.hpp"
  36 #include "memory/universe.hpp"
  37 #include "oops/klass.hpp"
  38 #include "oops/klass.inline.hpp"
  39 #include "oops/objArrayKlass.hpp"
  40 #include "oops/objArrayOop.inline.hpp"
  41 #include "oops/oop.inline.hpp"
  42 #include "oops/oopHandle.inline.hpp"
  43 #include "oops/typeArrayOop.inline.hpp"
  44 #include "runtime/flags/jvmFlag.hpp"
  45 #include "runtime/globals.hpp"
  46 #include "runtime/handles.inline.hpp"
  47 #include "runtime/interfaceSupport.inline.hpp"
  48 #include "runtime/javaCalls.hpp"
  49 #include "runtime/jniHandles.inline.hpp"
  50 #include "runtime/mutexLocker.hpp"
  51 #include "runtime/notificationThread.hpp"
  52 #include "runtime/os.hpp"
  53 #include "runtime/thread.inline.hpp"
  54 #include "runtime/threads.hpp"
  55 #include "runtime/threadSMR.hpp"
  56 #include "runtime/vmOperations.hpp"
  57 #include "services/classLoadingService.hpp"
  58 #include "services/diagnosticCommand.hpp"
  59 #include "services/diagnosticFramework.hpp"
  60 #include "services/finalizerService.hpp"
  61 #include "services/writeableFlags.hpp"
  62 #include "services/heapDumper.hpp"
  63 #include "services/lowMemoryDetector.hpp"
  64 #include "services/gcNotifier.hpp"
  65 #include "services/management.hpp"
  66 #include "services/memoryManager.hpp"
  67 #include "services/memoryPool.hpp"
  68 #include "services/memoryService.hpp"
  69 #include "services/runtimeService.hpp"
  70 #include "services/threadService.hpp"
  71 #include "utilities/debug.hpp"
  72 #include "utilities/formatBuffer.hpp"
  73 #include "utilities/macros.hpp"
  74 
  75 PerfVariable* Management::_begin_vm_creation_time = nullptr;
  76 PerfVariable* Management::_end_vm_creation_time = nullptr;
  77 PerfVariable* Management::_vm_init_done_time = nullptr;
  78 
  79 InstanceKlass* Management::_diagnosticCommandImpl_klass = nullptr;
  80 InstanceKlass* Management::_garbageCollectorExtImpl_klass = nullptr;
  81 InstanceKlass* Management::_garbageCollectorMXBean_klass = nullptr;
  82 InstanceKlass* Management::_gcInfo_klass = nullptr;
  83 InstanceKlass* Management::_managementFactoryHelper_klass = nullptr;
  84 InstanceKlass* Management::_memoryManagerMXBean_klass = nullptr;
  85 InstanceKlass* Management::_memoryPoolMXBean_klass = nullptr;
  86 InstanceKlass* Management::_memoryUsage_klass = nullptr;
  87 InstanceKlass* Management::_sensor_klass = nullptr;
  88 InstanceKlass* Management::_threadInfo_klass = nullptr;
  89 
  90 jmmOptionalSupport Management::_optional_support = {0};
  91 TimeStamp Management::_stamp;
  92 
  93 void management_init() {
  94 #if INCLUDE_MANAGEMENT
  95   Management::init();
  96   ThreadService::init();
  97   RuntimeService::init();
  98   ClassLoadingService::init();
  99   FinalizerService::init();
 100 #else
 101   ThreadService::init();
 102 #endif // INCLUDE_MANAGEMENT
 103 }
 104 
 105 #if INCLUDE_MANAGEMENT
 106 
 107 void Management::init() {
 108   EXCEPTION_MARK;
 109 
 110   // These counters are for java.lang.management API support.
 111   // They are created even if -XX:-UsePerfData is set and in
 112   // that case, they will be allocated on C heap.
 113 
 114   _begin_vm_creation_time =
 115             PerfDataManager::create_variable(SUN_RT, "createVmBeginTime",
 116                                              PerfData::U_None, CHECK);
 117 
 118   _end_vm_creation_time =
 119             PerfDataManager::create_variable(SUN_RT, "createVmEndTime",
 120                                              PerfData::U_None, CHECK);
 121 
 122   _vm_init_done_time =
 123             PerfDataManager::create_variable(SUN_RT, "vmInitDoneTime",
 124                                              PerfData::U_None, CHECK);
 125 
 126   // Initialize optional support
 127   _optional_support.isLowMemoryDetectionSupported = 1;
 128   _optional_support.isCompilationTimeMonitoringSupported = 1;
 129   _optional_support.isThreadContentionMonitoringSupported = 1;
 130 
 131   if (os::is_thread_cpu_time_supported()) {
 132     _optional_support.isCurrentThreadCpuTimeSupported = 1;
 133     _optional_support.isOtherThreadCpuTimeSupported = 1;
 134   } else {
 135     _optional_support.isCurrentThreadCpuTimeSupported = 0;
 136     _optional_support.isOtherThreadCpuTimeSupported = 0;
 137   }
 138 
 139   _optional_support.isObjectMonitorUsageSupported = 1;
 140 #if INCLUDE_SERVICES
 141   // This depends on the heap inspector
 142   _optional_support.isSynchronizerUsageSupported = 1;
 143 #endif // INCLUDE_SERVICES
 144   _optional_support.isThreadAllocatedMemorySupported = 1;
 145   _optional_support.isRemoteDiagnosticCommandsSupported = 1;
 146 
 147   // Registration of the diagnostic commands
 148   DCmd::register_dcmds();
 149 }
 150 
 151 void Management::initialize(TRAPS) {
 152   NotificationThread::initialize();
 153 
 154   if (ManagementServer) {
 155     ResourceMark rm(THREAD);
 156     HandleMark hm(THREAD);
 157 
 158     // Load and initialize the jdk.internal.agent.Agent class
 159     // invoke startAgent method to start the management server
 160     Handle loader = Handle(THREAD, SystemDictionary::java_system_loader());
 161     Klass* k = SystemDictionary::resolve_or_null(vmSymbols::jdk_internal_agent_Agent(),
 162                                                    loader,
 163                                                    THREAD);
 164     if (k == nullptr) {
 165       vm_exit_during_initialization("Management agent initialization failure: "
 166           "class jdk.internal.agent.Agent not found.");
 167     }
 168 
 169     JavaValue result(T_VOID);
 170     JavaCalls::call_static(&result,
 171                            k,
 172                            vmSymbols::startAgent_name(),
 173                            vmSymbols::void_method_signature(),
 174                            CHECK);
 175   }
 176 }
 177 
 178 void Management::get_optional_support(jmmOptionalSupport* support) {
 179   memcpy(support, &_optional_support, sizeof(jmmOptionalSupport));
 180 }
 181 
 182 InstanceKlass* Management::load_and_initialize_klass(Symbol* sh, TRAPS) {
 183   Klass* k = SystemDictionary::resolve_or_fail(sh, true, CHECK_NULL);
 184   return initialize_klass(k, THREAD);
 185 }
 186 
 187 InstanceKlass* Management::load_and_initialize_klass_or_null(Symbol* sh, TRAPS) {
 188   Klass* k = SystemDictionary::resolve_or_null(sh, CHECK_NULL);
 189   if (k == nullptr) {
 190      return nullptr;
 191   }
 192   return initialize_klass(k, THREAD);
 193 }
 194 
 195 InstanceKlass* Management::initialize_klass(Klass* k, TRAPS) {
 196   InstanceKlass* ik = InstanceKlass::cast(k);
 197   if (ik->should_be_initialized()) {
 198     ik->initialize(CHECK_NULL);
 199   }
 200   // If these classes change to not be owned by the boot loader, they need
 201   // to be walked to keep their class loader alive in oops_do.
 202   assert(ik->class_loader() == nullptr, "need to follow in oops_do");
 203   return ik;
 204 }
 205 
 206 
 207 void Management::record_vm_init_completed() {
 208   // Initialize the timestamp to get the current time
 209   _vm_init_done_time->set_value(os::javaTimeMillis());
 210 
 211   // Update the timestamp to the vm init done time
 212   _stamp.update();
 213 }
 214 
 215 void Management::record_vm_startup_time(jlong begin, jlong duration) {
 216   // if the performance counter is not initialized,
 217   // then vm initialization failed; simply return.
 218   if (_begin_vm_creation_time == nullptr) return;
 219 
 220   _begin_vm_creation_time->set_value(begin);
 221   _end_vm_creation_time->set_value(begin + duration);
 222   PerfMemory::set_accessible(true);
 223 }
 224 
 225 jlong Management::begin_vm_creation_time() {
 226   return _begin_vm_creation_time->get_value();
 227 }
 228 
 229 jlong Management::vm_init_done_time() {
 230   return _vm_init_done_time->get_value();
 231 }
 232 
 233 jlong Management::timestamp() {
 234   TimeStamp t;
 235   t.update();
 236   return t.ticks() - _stamp.ticks();
 237 }
 238 
 239 InstanceKlass* Management::java_lang_management_ThreadInfo_klass(TRAPS) {
 240   if (_threadInfo_klass == nullptr) {
 241     _threadInfo_klass = load_and_initialize_klass(vmSymbols::java_lang_management_ThreadInfo(), CHECK_NULL);
 242   }
 243   return _threadInfo_klass;
 244 }
 245 
 246 InstanceKlass* Management::java_lang_management_MemoryUsage_klass(TRAPS) {
 247   if (_memoryUsage_klass == nullptr) {
 248     _memoryUsage_klass = load_and_initialize_klass(vmSymbols::java_lang_management_MemoryUsage(), CHECK_NULL);
 249   }
 250   return _memoryUsage_klass;
 251 }
 252 
 253 InstanceKlass* Management::java_lang_management_MemoryPoolMXBean_klass(TRAPS) {
 254   if (_memoryPoolMXBean_klass == nullptr) {
 255     _memoryPoolMXBean_klass = load_and_initialize_klass(vmSymbols::java_lang_management_MemoryPoolMXBean(), CHECK_NULL);
 256   }
 257   return _memoryPoolMXBean_klass;
 258 }
 259 
 260 InstanceKlass* Management::java_lang_management_MemoryManagerMXBean_klass(TRAPS) {
 261   if (_memoryManagerMXBean_klass == nullptr) {
 262     _memoryManagerMXBean_klass = load_and_initialize_klass(vmSymbols::java_lang_management_MemoryManagerMXBean(), CHECK_NULL);
 263   }
 264   return _memoryManagerMXBean_klass;
 265 }
 266 
 267 InstanceKlass* Management::java_lang_management_GarbageCollectorMXBean_klass(TRAPS) {
 268   if (_garbageCollectorMXBean_klass == nullptr) {
 269       _garbageCollectorMXBean_klass = load_and_initialize_klass(vmSymbols::java_lang_management_GarbageCollectorMXBean(), CHECK_NULL);
 270   }
 271   return _garbageCollectorMXBean_klass;
 272 }
 273 
 274 InstanceKlass* Management::sun_management_Sensor_klass(TRAPS) {
 275   if (_sensor_klass == nullptr) {
 276     _sensor_klass = load_and_initialize_klass(vmSymbols::sun_management_Sensor(), CHECK_NULL);
 277   }
 278   return _sensor_klass;
 279 }
 280 
 281 InstanceKlass* Management::sun_management_ManagementFactoryHelper_klass(TRAPS) {
 282   if (_managementFactoryHelper_klass == nullptr) {
 283     _managementFactoryHelper_klass = load_and_initialize_klass(vmSymbols::sun_management_ManagementFactoryHelper(), CHECK_NULL);
 284   }
 285   return _managementFactoryHelper_klass;
 286 }
 287 
 288 InstanceKlass* Management::com_sun_management_internal_GarbageCollectorExtImpl_klass(TRAPS) {
 289   if (_garbageCollectorExtImpl_klass == nullptr) {
 290     _garbageCollectorExtImpl_klass =
 291                 load_and_initialize_klass_or_null(vmSymbols::com_sun_management_internal_GarbageCollectorExtImpl(), CHECK_NULL);
 292   }
 293   return _garbageCollectorExtImpl_klass;
 294 }
 295 
 296 InstanceKlass* Management::com_sun_management_GcInfo_klass(TRAPS) {
 297   if (_gcInfo_klass == nullptr) {
 298     _gcInfo_klass = load_and_initialize_klass(vmSymbols::com_sun_management_GcInfo(), CHECK_NULL);
 299   }
 300   return _gcInfo_klass;
 301 }
 302 
 303 InstanceKlass* Management::com_sun_management_internal_DiagnosticCommandImpl_klass(TRAPS) {
 304   if (_diagnosticCommandImpl_klass == nullptr) {
 305     _diagnosticCommandImpl_klass = load_and_initialize_klass(vmSymbols::com_sun_management_internal_DiagnosticCommandImpl(), CHECK_NULL);
 306   }
 307   return _diagnosticCommandImpl_klass;
 308 }
 309 
 310 static void initialize_ThreadInfo_constructor_arguments(JavaCallArguments* args, ThreadSnapshot* snapshot, TRAPS) {
 311   Handle snapshot_thread(THREAD, snapshot->threadObj());
 312 
 313   jlong contended_time;
 314   jlong waited_time;
 315   if (ThreadService::is_thread_monitoring_contention()) {
 316     contended_time = Management::ticks_to_ms(snapshot->contended_enter_ticks());
 317     waited_time = Management::ticks_to_ms(snapshot->monitor_wait_ticks() + snapshot->sleep_ticks());
 318   } else {
 319     // set them to -1 if thread contention monitoring is disabled.
 320     contended_time = max_julong;
 321     waited_time = max_julong;
 322   }
 323 
 324   int thread_status = static_cast<int>(snapshot->thread_status());
 325   assert((thread_status & JMM_THREAD_STATE_FLAG_MASK) == 0, "Flags already set in thread_status in Thread object");
 326   if (snapshot->is_suspended()) {
 327     thread_status |= JMM_THREAD_STATE_FLAG_SUSPENDED;
 328   }
 329   if (snapshot->is_in_native()) {
 330     thread_status |= JMM_THREAD_STATE_FLAG_NATIVE;
 331   }
 332 
 333   ThreadStackTrace* st = snapshot->get_stack_trace();
 334   Handle stacktrace_h;
 335   if (st != nullptr) {
 336     stacktrace_h = st->allocate_fill_stack_trace_element_array(CHECK);
 337   } else {
 338     stacktrace_h = Handle();
 339   }
 340 
 341   args->push_oop(snapshot_thread);
 342   args->push_int(thread_status);
 343   args->push_oop(Handle(THREAD, snapshot->blocker_object()));
 344   args->push_oop(Handle(THREAD, snapshot->blocker_object_owner()));
 345   args->push_long(snapshot->contended_enter_count());
 346   args->push_long(contended_time);
 347   args->push_long(snapshot->monitor_wait_count() + snapshot->sleep_count());
 348   args->push_long(waited_time);
 349   args->push_oop(stacktrace_h);
 350 }
 351 
 352 // Helper function to construct a ThreadInfo object
 353 instanceOop Management::create_thread_info_instance(ThreadSnapshot* snapshot, TRAPS) {
 354   InstanceKlass* ik = Management::java_lang_management_ThreadInfo_klass(CHECK_NULL);
 355   JavaCallArguments args(14);
 356 
 357   // initialize the arguments for the ThreadInfo constructor
 358   initialize_ThreadInfo_constructor_arguments(&args, snapshot, CHECK_NULL);
 359 
 360   // Call ThreadInfo constructor with no locked monitors and synchronizers
 361   Handle element = JavaCalls::construct_new_instance(
 362                           ik,
 363                           vmSymbols::java_lang_management_ThreadInfo_constructor_signature(),
 364                           &args,
 365                           CHECK_NULL);
 366   return (instanceOop) element();
 367 }
 368 
 369 instanceOop Management::create_thread_info_instance(ThreadSnapshot* snapshot,
 370                                                     objArrayHandle monitors_array,
 371                                                     typeArrayHandle depths_array,
 372                                                     objArrayHandle synchronizers_array,
 373                                                     TRAPS) {
 374   InstanceKlass* ik = Management::java_lang_management_ThreadInfo_klass(CHECK_NULL);
 375   JavaCallArguments args(17);
 376 
 377   // initialize the arguments for the ThreadInfo constructor
 378   initialize_ThreadInfo_constructor_arguments(&args, snapshot, CHECK_NULL);
 379 
 380   // push the locked monitors and synchronizers in the arguments
 381   args.push_oop(monitors_array);
 382   args.push_oop(depths_array);
 383   args.push_oop(synchronizers_array);
 384 
 385   // Call ThreadInfo constructor with locked monitors and synchronizers
 386   Handle element = JavaCalls::construct_new_instance(
 387                           ik,
 388                           vmSymbols::java_lang_management_ThreadInfo_with_locks_constructor_signature(),
 389                           &args,
 390                           CHECK_NULL);
 391   return (instanceOop) element();
 392 }
 393 
 394 
 395 static GCMemoryManager* get_gc_memory_manager_from_jobject(jobject mgr, TRAPS) {
 396   if (mgr == nullptr) {
 397     THROW_(vmSymbols::java_lang_NullPointerException(), nullptr);
 398   }
 399   oop mgr_obj = JNIHandles::resolve(mgr);
 400   instanceHandle h(THREAD, (instanceOop) mgr_obj);
 401 
 402   InstanceKlass* k = Management::java_lang_management_GarbageCollectorMXBean_klass(CHECK_NULL);
 403   if (!h->is_a(k)) {
 404     THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
 405                "the object is not an instance of java.lang.management.GarbageCollectorMXBean class",
 406                nullptr);
 407   }
 408 
 409   MemoryManager* gc = MemoryService::get_memory_manager(h);
 410   if (gc == nullptr || !gc->is_gc_memory_manager()) {
 411     THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
 412                "Invalid GC memory manager",
 413                nullptr);
 414   }
 415   return (GCMemoryManager*) gc;
 416 }
 417 
 418 static MemoryPool* get_memory_pool_from_jobject(jobject obj, TRAPS) {
 419   if (obj == nullptr) {
 420     THROW_(vmSymbols::java_lang_NullPointerException(), nullptr);
 421   }
 422 
 423   oop pool_obj = JNIHandles::resolve(obj);
 424   assert(pool_obj->is_instance(), "Should be an instanceOop");
 425   instanceHandle ph(THREAD, (instanceOop) pool_obj);
 426 
 427   return MemoryService::get_memory_pool(ph);
 428 }
 429 
 430 static void validate_thread_id_array(typeArrayHandle ids_ah, TRAPS) {
 431   int num_threads = ids_ah->length();
 432 
 433   // Validate input thread IDs
 434   int i = 0;
 435   for (i = 0; i < num_threads; i++) {
 436     jlong tid = ids_ah->long_at(i);
 437     if (tid <= 0) {
 438       // throw exception if invalid thread id.
 439       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 440                 "Invalid thread ID entry");
 441     }
 442   }
 443 }
 444 
 445 // Returns true if the JavaThread's Java object is a platform thread
 446 static bool is_platform_thread(JavaThread* jt) {
 447   if (jt != nullptr) {
 448     oop thread_obj = jt->threadObj();
 449     return (thread_obj != nullptr) && !thread_obj->is_a(vmClasses::BoundVirtualThread_klass());
 450   } else {
 451     return false;
 452   }
 453 }
 454 
 455 static void validate_thread_info_array(objArrayHandle infoArray_h, TRAPS) {
 456   // check if the element of infoArray is of type ThreadInfo class
 457   Klass* threadinfo_klass = Management::java_lang_management_ThreadInfo_klass(CHECK);
 458   Klass* element_klass = ObjArrayKlass::cast(infoArray_h->klass())->element_klass();
 459   if (element_klass != threadinfo_klass) {
 460     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 461               "infoArray element type is not ThreadInfo class");
 462   }
 463 }
 464 
 465 // Returns true if the ThreadSnapshot's Java object is a platform thread
 466 static bool is_platform_thread(ThreadSnapshot* ts) {
 467   oop thread_obj = ts->threadObj();
 468   return (thread_obj != nullptr) && !thread_obj->is_a(vmClasses::BoundVirtualThread_klass());
 469 }
 470 
 471 static MemoryManager* get_memory_manager_from_jobject(jobject obj, TRAPS) {
 472   if (obj == nullptr) {
 473     THROW_(vmSymbols::java_lang_NullPointerException(), nullptr);
 474   }
 475 
 476   oop mgr_obj = JNIHandles::resolve(obj);
 477   assert(mgr_obj->is_instance(), "Should be an instanceOop");
 478   instanceHandle mh(THREAD, (instanceOop) mgr_obj);
 479 
 480   return MemoryService::get_memory_manager(mh);
 481 }
 482 
 483 // Returns a version string and sets major and minor version if
 484 // the input parameters are non-null.
 485 JVM_LEAF(jint, jmm_GetVersion(JNIEnv *env))
 486   return JMM_VERSION;
 487 JVM_END
 488 
 489 // Gets the list of VM monitoring and management optional supports
 490 // Returns 0 if succeeded; otherwise returns non-zero.
 491 JVM_LEAF(jint, jmm_GetOptionalSupport(JNIEnv *env, jmmOptionalSupport* support))
 492   if (support == nullptr) {
 493     return -1;
 494   }
 495   Management::get_optional_support(support);
 496   return 0;
 497 JVM_END
 498 
 499 // Returns an array of java/lang/management/MemoryPoolMXBean object
 500 // one for each memory pool if obj == null; otherwise returns
 501 // an array of memory pools for a given memory manager if
 502 // it is a valid memory manager.
 503 JVM_ENTRY(jobjectArray, jmm_GetMemoryPools(JNIEnv* env, jobject obj))
 504   ResourceMark rm(THREAD);
 505 
 506   int num_memory_pools;
 507   MemoryManager* mgr = nullptr;
 508   if (obj == nullptr) {
 509     num_memory_pools = MemoryService::num_memory_pools();
 510   } else {
 511     mgr = get_memory_manager_from_jobject(obj, CHECK_NULL);
 512     if (mgr == nullptr) {
 513       return nullptr;
 514     }
 515     num_memory_pools = mgr->num_memory_pools();
 516   }
 517 
 518   // Allocate the resulting MemoryPoolMXBean[] object
 519   InstanceKlass* ik = Management::java_lang_management_MemoryPoolMXBean_klass(CHECK_NULL);
 520   objArrayOop r = oopFactory::new_objArray(ik, num_memory_pools, CHECK_NULL);
 521   objArrayHandle poolArray(THREAD, r);
 522 
 523   if (mgr == nullptr) {
 524     // Get all memory pools
 525     for (int i = 0; i < num_memory_pools; i++) {
 526       MemoryPool* pool = MemoryService::get_memory_pool(i);
 527       instanceOop p = pool->get_memory_pool_instance(CHECK_NULL);
 528       instanceHandle ph(THREAD, p);
 529       poolArray->obj_at_put(i, ph());
 530     }
 531   } else {
 532     // Get memory pools managed by a given memory manager
 533     for (int i = 0; i < num_memory_pools; i++) {
 534       MemoryPool* pool = mgr->get_memory_pool(i);
 535       instanceOop p = pool->get_memory_pool_instance(CHECK_NULL);
 536       instanceHandle ph(THREAD, p);
 537       poolArray->obj_at_put(i, ph());
 538     }
 539   }
 540   return (jobjectArray) JNIHandles::make_local(THREAD, poolArray());
 541 JVM_END
 542 
 543 // Returns an array of java/lang/management/MemoryManagerMXBean object
 544 // one for each memory manager if obj == null; otherwise returns
 545 // an array of memory managers for a given memory pool if
 546 // it is a valid memory pool.
 547 JVM_ENTRY(jobjectArray, jmm_GetMemoryManagers(JNIEnv* env, jobject obj))
 548   ResourceMark rm(THREAD);
 549 
 550   int num_mgrs;
 551   MemoryPool* pool = nullptr;
 552   if (obj == nullptr) {
 553     num_mgrs = MemoryService::num_memory_managers();
 554   } else {
 555     pool = get_memory_pool_from_jobject(obj, CHECK_NULL);
 556     if (pool == nullptr) {
 557       return nullptr;
 558     }
 559     num_mgrs = pool->num_memory_managers();
 560   }
 561 
 562   // Allocate the resulting MemoryManagerMXBean[] object
 563   InstanceKlass* ik = Management::java_lang_management_MemoryManagerMXBean_klass(CHECK_NULL);
 564   objArrayOop r = oopFactory::new_objArray(ik, num_mgrs, CHECK_NULL);
 565   objArrayHandle mgrArray(THREAD, r);
 566 
 567   if (pool == nullptr) {
 568     // Get all memory managers
 569     for (int i = 0; i < num_mgrs; i++) {
 570       MemoryManager* mgr = MemoryService::get_memory_manager(i);
 571       instanceOop p = mgr->get_memory_manager_instance(CHECK_NULL);
 572       instanceHandle ph(THREAD, p);
 573       mgrArray->obj_at_put(i, ph());
 574     }
 575   } else {
 576     // Get memory managers for a given memory pool
 577     for (int i = 0; i < num_mgrs; i++) {
 578       MemoryManager* mgr = pool->get_memory_manager(i);
 579       instanceOop p = mgr->get_memory_manager_instance(CHECK_NULL);
 580       instanceHandle ph(THREAD, p);
 581       mgrArray->obj_at_put(i, ph());
 582     }
 583   }
 584   return (jobjectArray) JNIHandles::make_local(THREAD, mgrArray());
 585 JVM_END
 586 
 587 
 588 // Returns a java/lang/management/MemoryUsage object containing the memory usage
 589 // of a given memory pool.
 590 JVM_ENTRY(jobject, jmm_GetMemoryPoolUsage(JNIEnv* env, jobject obj))
 591   ResourceMark rm(THREAD);
 592 
 593   MemoryPool* pool = get_memory_pool_from_jobject(obj, CHECK_NULL);
 594   if (pool != nullptr) {
 595     MemoryUsage usage = pool->get_memory_usage();
 596     Handle h = MemoryService::create_MemoryUsage_obj(usage, CHECK_NULL);
 597     return JNIHandles::make_local(THREAD, h());
 598   } else {
 599     return nullptr;
 600   }
 601 JVM_END
 602 
 603 // Returns a java/lang/management/MemoryUsage object containing the memory usage
 604 // of a given memory pool.
 605 JVM_ENTRY(jobject, jmm_GetPeakMemoryPoolUsage(JNIEnv* env, jobject obj))
 606   ResourceMark rm(THREAD);
 607 
 608   MemoryPool* pool = get_memory_pool_from_jobject(obj, CHECK_NULL);
 609   if (pool != nullptr) {
 610     MemoryUsage usage = pool->get_peak_memory_usage();
 611     Handle h = MemoryService::create_MemoryUsage_obj(usage, CHECK_NULL);
 612     return JNIHandles::make_local(THREAD, h());
 613   } else {
 614     return nullptr;
 615   }
 616 JVM_END
 617 
 618 // Returns a java/lang/management/MemoryUsage object containing the memory usage
 619 // of a given memory pool after most recent GC.
 620 JVM_ENTRY(jobject, jmm_GetPoolCollectionUsage(JNIEnv* env, jobject obj))
 621   ResourceMark rm(THREAD);
 622 
 623   MemoryPool* pool = get_memory_pool_from_jobject(obj, CHECK_NULL);
 624   if (pool != nullptr && pool->is_collected_pool()) {
 625     MemoryUsage usage = pool->get_last_collection_usage();
 626     Handle h = MemoryService::create_MemoryUsage_obj(usage, CHECK_NULL);
 627     return JNIHandles::make_local(THREAD, h());
 628   } else {
 629     return nullptr;
 630   }
 631 JVM_END
 632 
 633 // Sets the memory pool sensor for a threshold type
 634 JVM_ENTRY(void, jmm_SetPoolSensor(JNIEnv* env, jobject obj, jmmThresholdType type, jobject sensorObj))
 635   if (obj == nullptr || sensorObj == nullptr) {
 636     THROW(vmSymbols::java_lang_NullPointerException());
 637   }
 638 
 639   InstanceKlass* sensor_klass = Management::sun_management_Sensor_klass(CHECK);
 640   oop s = JNIHandles::resolve(sensorObj);
 641   assert(s->is_instance(), "Sensor should be an instanceOop");
 642   instanceHandle sensor_h(THREAD, (instanceOop) s);
 643   if (!sensor_h->is_a(sensor_klass)) {
 644     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 645               "Sensor is not an instance of sun.management.Sensor class");
 646   }
 647 
 648   MemoryPool* mpool = get_memory_pool_from_jobject(obj, CHECK);
 649   assert(mpool != nullptr, "MemoryPool should exist");
 650 
 651   switch (type) {
 652     case JMM_USAGE_THRESHOLD_HIGH:
 653     case JMM_USAGE_THRESHOLD_LOW:
 654       // have only one sensor for threshold high and low
 655       mpool->set_usage_sensor_obj(sensor_h);
 656       break;
 657     case JMM_COLLECTION_USAGE_THRESHOLD_HIGH:
 658     case JMM_COLLECTION_USAGE_THRESHOLD_LOW:
 659       // have only one sensor for threshold high and low
 660       mpool->set_gc_usage_sensor_obj(sensor_h);
 661       break;
 662     default:
 663       assert(false, "Unrecognized type");
 664   }
 665 
 666 JVM_END
 667 
 668 
 669 // Sets the threshold of a given memory pool.
 670 // Returns the previous threshold.
 671 //
 672 // Input parameters:
 673 //   pool      - the MemoryPoolMXBean object
 674 //   type      - threshold type
 675 //   threshold - the new threshold (must not be negative)
 676 //
 677 JVM_ENTRY(jlong, jmm_SetPoolThreshold(JNIEnv* env, jobject obj, jmmThresholdType type, jlong threshold))
 678   if (threshold < 0) {
 679     THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
 680                "Invalid threshold value",
 681                -1);
 682   }
 683 
 684   if ((size_t)threshold > max_uintx) {
 685     stringStream st;
 686     st.print("Invalid valid threshold value. Threshold value (" JLONG_FORMAT ") > max value of size_t (%zu)", threshold, max_uintx);
 687     THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(), st.as_string(), -1);
 688   }
 689 
 690   MemoryPool* pool = get_memory_pool_from_jobject(obj, CHECK_(0L));
 691   assert(pool != nullptr, "MemoryPool should exist");
 692 
 693   jlong prev = 0;
 694   switch (type) {
 695     case JMM_USAGE_THRESHOLD_HIGH:
 696       if (!pool->usage_threshold()->is_high_threshold_supported()) {
 697         return -1;
 698       }
 699       prev = pool->usage_threshold()->set_high_threshold((size_t) threshold);
 700       break;
 701 
 702     case JMM_USAGE_THRESHOLD_LOW:
 703       if (!pool->usage_threshold()->is_low_threshold_supported()) {
 704         return -1;
 705       }
 706       prev = pool->usage_threshold()->set_low_threshold((size_t) threshold);
 707       break;
 708 
 709     case JMM_COLLECTION_USAGE_THRESHOLD_HIGH:
 710       if (!pool->gc_usage_threshold()->is_high_threshold_supported()) {
 711         return -1;
 712       }
 713       // return and the new threshold is effective for the next GC
 714       return pool->gc_usage_threshold()->set_high_threshold((size_t) threshold);
 715 
 716     case JMM_COLLECTION_USAGE_THRESHOLD_LOW:
 717       if (!pool->gc_usage_threshold()->is_low_threshold_supported()) {
 718         return -1;
 719       }
 720       // return and the new threshold is effective for the next GC
 721       return pool->gc_usage_threshold()->set_low_threshold((size_t) threshold);
 722 
 723     default:
 724       assert(false, "Unrecognized type");
 725       return -1;
 726   }
 727 
 728   // When the threshold is changed, reevaluate if the low memory
 729   // detection is enabled.
 730   if (prev != threshold) {
 731     LowMemoryDetector::recompute_enabled_for_collected_pools();
 732     LowMemoryDetector::detect_low_memory(pool);
 733   }
 734   return prev;
 735 JVM_END
 736 
 737 // Returns a java/lang/management/MemoryUsage object representing
 738 // the memory usage for the heap or non-heap memory.
 739 JVM_ENTRY(jobject, jmm_GetMemoryUsage(JNIEnv* env, jboolean heap))
 740   ResourceMark rm(THREAD);
 741 
 742   MemoryUsage usage;
 743 
 744   if (heap) {
 745     usage = Universe::heap()->memory_usage();
 746   } else {
 747     // Calculate the memory usage by summing up the pools.
 748     size_t total_init = 0;
 749     size_t total_used = 0;
 750     size_t total_committed = 0;
 751     size_t total_max = 0;
 752     bool   has_undefined_init_size = false;
 753     bool   has_undefined_max_size = false;
 754 
 755     for (int i = 0; i < MemoryService::num_memory_pools(); i++) {
 756       MemoryPool* pool = MemoryService::get_memory_pool(i);
 757       if (pool->is_non_heap()) {
 758         MemoryUsage u = pool->get_memory_usage();
 759         total_used += u.used();
 760         total_committed += u.committed();
 761 
 762         if (u.init_size() == MemoryUsage::undefined_size()) {
 763           has_undefined_init_size = true;
 764         }
 765         if (!has_undefined_init_size) {
 766           total_init += u.init_size();
 767         }
 768 
 769         if (u.max_size() == MemoryUsage::undefined_size()) {
 770           has_undefined_max_size = true;
 771         }
 772         if (!has_undefined_max_size) {
 773           total_max += u.max_size();
 774         }
 775       }
 776     }
 777 
 778     // if any one of the memory pool has undefined init_size or max_size,
 779     // set it to MemoryUsage::undefined_size()
 780     if (has_undefined_init_size) {
 781       total_init = MemoryUsage::undefined_size();
 782     }
 783     if (has_undefined_max_size) {
 784       total_max = MemoryUsage::undefined_size();
 785     }
 786 
 787     usage = MemoryUsage(total_init, total_used, total_committed, total_max);
 788   }
 789 
 790   Handle obj = MemoryService::create_MemoryUsage_obj(usage, CHECK_NULL);
 791   return JNIHandles::make_local(THREAD, obj());
 792 JVM_END
 793 
 794 // Returns the boolean value of a given attribute.
 795 JVM_LEAF(jboolean, jmm_GetBoolAttribute(JNIEnv *env, jmmBoolAttribute att))
 796   switch (att) {
 797   case JMM_VERBOSE_GC:
 798     return MemoryService::get_verbose();
 799   case JMM_VERBOSE_CLASS:
 800     return ClassLoadingService::get_verbose();
 801   case JMM_THREAD_CONTENTION_MONITORING:
 802     return ThreadService::is_thread_monitoring_contention();
 803   case JMM_THREAD_CPU_TIME:
 804     return ThreadService::is_thread_cpu_time_enabled();
 805   case JMM_THREAD_ALLOCATED_MEMORY:
 806     return ThreadService::is_thread_allocated_memory_enabled();
 807   default:
 808     assert(0, "Unrecognized attribute");
 809     return false;
 810   }
 811 JVM_END
 812 
 813 // Sets the given boolean attribute and returns the previous value.
 814 JVM_ENTRY(jboolean, jmm_SetBoolAttribute(JNIEnv *env, jmmBoolAttribute att, jboolean flag))
 815   switch (att) {
 816   case JMM_VERBOSE_GC:
 817     return MemoryService::set_verbose(flag != 0);
 818   case JMM_VERBOSE_CLASS:
 819     return ClassLoadingService::set_verbose(flag != 0);
 820   case JMM_THREAD_CONTENTION_MONITORING:
 821     return ThreadService::set_thread_monitoring_contention(flag != 0);
 822   case JMM_THREAD_CPU_TIME:
 823     return ThreadService::set_thread_cpu_time_enabled(flag != 0);
 824   case JMM_THREAD_ALLOCATED_MEMORY:
 825     return ThreadService::set_thread_allocated_memory_enabled(flag != 0);
 826   default:
 827     assert(0, "Unrecognized attribute");
 828     return false;
 829   }
 830 JVM_END
 831 
 832 
 833 static jlong get_gc_attribute(GCMemoryManager* mgr, jmmLongAttribute att) {
 834   switch (att) {
 835   case JMM_GC_TIME_MS:
 836     return mgr->gc_time_ms();
 837 
 838   case JMM_GC_COUNT:
 839     return mgr->gc_count();
 840 
 841   case JMM_GC_EXT_ATTRIBUTE_INFO_SIZE:
 842     // current implementation only has 1 ext attribute
 843     return 1;
 844 
 845   default:
 846     assert(0, "Unrecognized GC attribute");
 847     return -1;
 848   }
 849 }
 850 
 851 class VmThreadCountClosure: public ThreadClosure {
 852  private:
 853   int _count;
 854  public:
 855   VmThreadCountClosure() : _count(0) {};
 856   void do_thread(Thread* thread);
 857   int count() { return _count; }
 858 };
 859 
 860 void VmThreadCountClosure::do_thread(Thread* thread) {
 861   // exclude externally visible JavaThreads
 862   if (thread->is_Java_thread() && !thread->is_hidden_from_external_view()) {
 863     return;
 864   }
 865 
 866   _count++;
 867 }
 868 
 869 static jint get_vm_thread_count() {
 870   VmThreadCountClosure vmtcc;
 871   {
 872     MutexLocker ml(Threads_lock);
 873     Threads::threads_do(&vmtcc);
 874   }
 875 
 876   return vmtcc.count();
 877 }
 878 
 879 static jint get_num_flags() {
 880   // last flag entry is always null, so subtract 1
 881   int nFlags = (int) JVMFlag::numFlags - 1;
 882   int count = 0;
 883   for (int i = 0; i < nFlags; i++) {
 884     JVMFlag* flag = &JVMFlag::flags[i];
 885     // Exclude the locked (diagnostic, experimental) flags
 886     if (flag->is_unlocked() || flag->is_unlocker()) {
 887       count++;
 888     }
 889   }
 890   return count;
 891 }
 892 
 893 static jlong get_long_attribute(jmmLongAttribute att) {
 894   switch (att) {
 895   case JMM_CLASS_LOADED_COUNT:
 896     return ClassLoadingService::loaded_class_count();
 897 
 898   case JMM_CLASS_UNLOADED_COUNT:
 899     return ClassLoadingService::unloaded_class_count();
 900 
 901   case JMM_THREAD_TOTAL_COUNT:
 902     return ThreadService::get_total_thread_count();
 903 
 904   case JMM_THREAD_LIVE_COUNT:
 905     return ThreadService::get_live_thread_count();
 906 
 907   case JMM_THREAD_PEAK_COUNT:
 908     return ThreadService::get_peak_thread_count();
 909 
 910   case JMM_THREAD_DAEMON_COUNT:
 911     return ThreadService::get_daemon_thread_count();
 912 
 913   case JMM_JVM_INIT_DONE_TIME_MS:
 914     return Management::vm_init_done_time();
 915 
 916   case JMM_JVM_UPTIME_MS:
 917     return Management::ticks_to_ms(os::elapsed_counter());
 918 
 919   case JMM_COMPILE_TOTAL_TIME_MS:
 920     return Management::ticks_to_ms(CompileBroker::total_compilation_ticks());
 921 
 922   case JMM_OS_PROCESS_ID:
 923     return os::current_process_id();
 924 
 925   // Hotspot-specific counters
 926   case JMM_CLASS_LOADED_BYTES:
 927     return ClassLoadingService::loaded_class_bytes();
 928 
 929   case JMM_CLASS_UNLOADED_BYTES:
 930     return ClassLoadingService::unloaded_class_bytes();
 931 
 932   case JMM_SHARED_CLASS_LOADED_COUNT:
 933     return ClassLoadingService::loaded_shared_class_count();
 934 
 935   case JMM_SHARED_CLASS_UNLOADED_COUNT:
 936     return ClassLoadingService::unloaded_shared_class_count();
 937 
 938 
 939   case JMM_SHARED_CLASS_LOADED_BYTES:
 940     return ClassLoadingService::loaded_shared_class_bytes();
 941 
 942   case JMM_SHARED_CLASS_UNLOADED_BYTES:
 943     return ClassLoadingService::unloaded_shared_class_bytes();
 944 
 945   case JMM_TOTAL_CLASSLOAD_TIME_MS:
 946     return ClassLoader::classloader_time_ms();
 947 
 948   case JMM_VM_GLOBAL_COUNT:
 949     return get_num_flags();
 950 
 951   case JMM_SAFEPOINT_COUNT:
 952     return RuntimeService::safepoint_count();
 953 
 954   case JMM_TOTAL_SAFEPOINTSYNC_TIME_MS:
 955     return RuntimeService::safepoint_sync_time_ms();
 956 
 957   case JMM_TOTAL_STOPPED_TIME_MS:
 958     return RuntimeService::safepoint_time_ms();
 959 
 960   case JMM_TOTAL_APP_TIME_MS:
 961     return RuntimeService::application_time_ms();
 962 
 963   case JMM_VM_THREAD_COUNT:
 964     return get_vm_thread_count();
 965 
 966   case JMM_CLASS_INIT_TOTAL_COUNT:
 967     return ClassLoader::class_init_count();
 968 
 969   case JMM_CLASS_INIT_TOTAL_TIME_MS:
 970     return ClassLoader::class_init_time_ms();
 971 
 972   case JMM_CLASS_VERIFY_TOTAL_TIME_MS:
 973     return ClassLoader::class_verify_time_ms();
 974 
 975   case JMM_METHOD_DATA_SIZE_BYTES:
 976     return ClassLoadingService::class_method_data_size();
 977 
 978   case JMM_OS_MEM_TOTAL_PHYSICAL_BYTES:
 979     return os::physical_memory();
 980 
 981   default:
 982     return -1;
 983   }
 984 }
 985 
 986 
 987 // Returns the long value of a given attribute.
 988 JVM_ENTRY(jlong, jmm_GetLongAttribute(JNIEnv *env, jobject obj, jmmLongAttribute att))
 989   if (obj == nullptr) {
 990     return get_long_attribute(att);
 991   } else {
 992     GCMemoryManager* mgr = get_gc_memory_manager_from_jobject(obj, CHECK_(0L));
 993     if (mgr != nullptr) {
 994       return get_gc_attribute(mgr, att);
 995     }
 996   }
 997   return -1;
 998 JVM_END
 999 
1000 // Gets the value of all attributes specified in the given array
1001 // and sets the value in the result array.
1002 // Returns the number of attributes found.
1003 JVM_ENTRY(jint, jmm_GetLongAttributes(JNIEnv *env,
1004                                       jobject obj,
1005                                       jmmLongAttribute* atts,
1006                                       jint count,
1007                                       jlong* result))
1008 
1009   int num_atts = 0;
1010   if (obj == nullptr) {
1011     for (int i = 0; i < count; i++) {
1012       result[i] = get_long_attribute(atts[i]);
1013       if (result[i] != -1) {
1014         num_atts++;
1015       }
1016     }
1017   } else {
1018     GCMemoryManager* mgr = get_gc_memory_manager_from_jobject(obj, CHECK_0);
1019     for (int i = 0; i < count; i++) {
1020       result[i] = get_gc_attribute(mgr, atts[i]);
1021       if (result[i] != -1) {
1022         num_atts++;
1023       }
1024     }
1025   }
1026   return num_atts;
1027 JVM_END
1028 
1029 // Helper function to do thread dump for a specific list of threads
1030 static void do_thread_dump(ThreadDumpResult* dump_result,
1031                            typeArrayHandle ids_ah,  // array of thread ID (long[])
1032                            int num_threads,
1033                            int max_depth,
1034                            bool with_locked_monitors,
1035                            bool with_locked_synchronizers,
1036                            TRAPS) {
1037   // no need to actually perform thread dump if no TIDs are specified
1038   if (num_threads == 0) return;
1039 
1040   // First get an array of threadObj handles.
1041   // A JavaThread may terminate before we get the stack trace.
1042   GrowableArray<instanceHandle>* thread_handle_array = new GrowableArray<instanceHandle>(num_threads);
1043 
1044   {
1045     // Need this ThreadsListHandle for converting Java thread IDs into
1046     // threadObj handles; dump_result->set_t_list() is called in the
1047     // VM op below so we can't use it yet.
1048     ThreadsListHandle tlh;
1049     for (int i = 0; i < num_threads; i++) {
1050       jlong tid = ids_ah->long_at(i);
1051       JavaThread* jt = tlh.list()->find_JavaThread_from_java_tid(tid);
1052       oop thread_obj = is_platform_thread(jt) ? jt->threadObj() : (oop)nullptr;
1053       instanceHandle threadObj_h(THREAD, (instanceOop) thread_obj);
1054       thread_handle_array->append(threadObj_h);
1055     }
1056   }
1057 
1058   // Obtain thread dumps and thread snapshot information
1059   VM_ThreadDump op(dump_result,
1060                    thread_handle_array,
1061                    num_threads,
1062                    max_depth, /* stack depth */
1063                    with_locked_monitors,
1064                    with_locked_synchronizers);
1065   VMThread::execute(&op);
1066 }
1067 
1068 // Gets an array of ThreadInfo objects. Each element is the ThreadInfo
1069 // for the thread ID specified in the corresponding entry in
1070 // the given array of thread IDs; or null if the thread does not exist
1071 // or has terminated.
1072 //
1073 // Input parameters:
1074 //   ids       - array of thread IDs
1075 //   maxDepth  - the maximum depth of stack traces to be dumped:
1076 //               maxDepth == -1 requests to dump entire stack trace.
1077 //               maxDepth == 0  requests no stack trace.
1078 //   infoArray - array of ThreadInfo objects
1079 //
1080 // QQQ - Why does this method return a value instead of void?
1081 JVM_ENTRY(jint, jmm_GetThreadInfo(JNIEnv *env, jlongArray ids, jint maxDepth, jobjectArray infoArray))
1082   // Check if threads is null
1083   if (ids == nullptr || infoArray == nullptr) {
1084     THROW_(vmSymbols::java_lang_NullPointerException(), -1);
1085   }
1086 
1087   if (maxDepth < -1) {
1088     THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
1089                "Invalid maxDepth", -1);
1090   }
1091 
1092   ResourceMark rm(THREAD);
1093   typeArrayOop ta = typeArrayOop(JNIHandles::resolve_non_null(ids));
1094   typeArrayHandle ids_ah(THREAD, ta);
1095 
1096   oop infoArray_obj = JNIHandles::resolve_non_null(infoArray);
1097   objArrayOop oa = objArrayOop(infoArray_obj);
1098   objArrayHandle infoArray_h(THREAD, oa);
1099 
1100   // validate the thread id array
1101   validate_thread_id_array(ids_ah, CHECK_0);
1102 
1103   // validate the ThreadInfo[] parameters
1104   validate_thread_info_array(infoArray_h, CHECK_0);
1105 
1106   // infoArray must be of the same length as the given array of thread IDs
1107   int num_threads = ids_ah->length();
1108   if (num_threads != infoArray_h->length()) {
1109     THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
1110                "The length of the given ThreadInfo array does not match the length of the given array of thread IDs", -1);
1111   }
1112 
1113   // Must use ThreadDumpResult to store the ThreadSnapshot.
1114   // GC may occur after the thread snapshots are taken but before
1115   // this function returns. The threadObj and other oops kept
1116   // in the ThreadSnapshot are marked and adjusted during GC.
1117   ThreadDumpResult dump_result(num_threads);
1118 
1119   if (maxDepth == 0) {
1120     // No stack trace to dump so we do not need to stop the world.
1121     // Since we never do the VM op here we must set the threads list.
1122     dump_result.set_t_list();
1123     for (int i = 0; i < num_threads; i++) {
1124       jlong tid = ids_ah->long_at(i);
1125       JavaThread* jt = dump_result.t_list()->find_JavaThread_from_java_tid(tid);
1126       if (jt == nullptr) {
1127         // if the thread does not exist or now it is terminated,
1128         // create dummy snapshot
1129         dump_result.add_thread_snapshot();
1130       } else {
1131         dump_result.add_thread_snapshot(jt);
1132       }
1133     }
1134   } else {
1135     // obtain thread dump with the specific list of threads with stack trace
1136     do_thread_dump(&dump_result,
1137                    ids_ah,
1138                    num_threads,
1139                    maxDepth,
1140                    false, /* no locked monitor */
1141                    false, /* no locked synchronizers */
1142                    CHECK_0);
1143   }
1144 
1145   int num_snapshots = dump_result.num_snapshots();
1146   assert(num_snapshots == num_threads, "Must match the number of thread snapshots");
1147   assert(num_snapshots == 0 || dump_result.t_list_has_been_set(), "ThreadsList must have been set if we have a snapshot");
1148   int index = 0;
1149   for (ThreadSnapshot* ts = dump_result.snapshots(); ts != nullptr; index++, ts = ts->next()) {
1150     // For each thread, create an java/lang/management/ThreadInfo object
1151     // and fill with the thread information
1152 
1153     if (!is_platform_thread(ts)) {
1154       // if the thread does not exist, has terminated, or is a virtual thread, then set threadinfo to null
1155       infoArray_h->obj_at_put(index, nullptr);
1156       continue;
1157     }
1158 
1159     // Create java.lang.management.ThreadInfo object
1160     instanceOop info_obj = Management::create_thread_info_instance(ts, CHECK_0);
1161     infoArray_h->obj_at_put(index, info_obj);
1162   }
1163   return 0;
1164 JVM_END
1165 
1166 // Dump thread info for the specified threads.
1167 // It returns an array of ThreadInfo objects. Each element is the ThreadInfo
1168 // for the thread ID specified in the corresponding entry in
1169 // the given array of thread IDs; or null if the thread does not exist
1170 // or has terminated.
1171 //
1172 // Input parameter:
1173 //    ids - array of thread IDs; null indicates all live threads
1174 //    locked_monitors - if true, dump locked object monitors
1175 //    locked_synchronizers - if true, dump locked JSR-166 synchronizers
1176 //
1177 JVM_ENTRY(jobjectArray, jmm_DumpThreads(JNIEnv *env, jlongArray thread_ids, jboolean locked_monitors,
1178                                         jboolean locked_synchronizers, jint maxDepth))
1179   ResourceMark rm(THREAD);
1180 
1181   typeArrayOop ta = typeArrayOop(JNIHandles::resolve(thread_ids));
1182   int num_threads = (ta != nullptr ? ta->length() : 0);
1183   typeArrayHandle ids_ah(THREAD, ta);
1184 
1185   ThreadDumpResult dump_result(num_threads);  // can safepoint
1186 
1187   if (ids_ah() != nullptr) {
1188 
1189     // validate the thread id array
1190     validate_thread_id_array(ids_ah, CHECK_NULL);
1191 
1192     // obtain thread dump of a specific list of threads
1193     do_thread_dump(&dump_result,
1194                    ids_ah,
1195                    num_threads,
1196                    maxDepth, /* stack depth */
1197                    (locked_monitors ? true : false),      /* with locked monitors */
1198                    (locked_synchronizers ? true : false), /* with locked synchronizers */
1199                    CHECK_NULL);
1200   } else {
1201     // obtain thread dump of all threads
1202     VM_ThreadDump op(&dump_result,
1203                      maxDepth, /* stack depth */
1204                      (locked_monitors ? true : false),     /* with locked monitors */
1205                      (locked_synchronizers ? true : false) /* with locked synchronizers */);
1206     VMThread::execute(&op);
1207   }
1208 
1209   int num_snapshots = dump_result.num_snapshots();
1210   assert(num_snapshots == 0 || dump_result.t_list_has_been_set(), "ThreadsList must have been set if we have a snapshot");
1211 
1212   // create the result ThreadInfo[] object
1213   InstanceKlass* ik = Management::java_lang_management_ThreadInfo_klass(CHECK_NULL);
1214   objArrayOop r = oopFactory::new_objArray(ik, num_snapshots, CHECK_NULL);
1215   objArrayHandle result_h(THREAD, r);
1216 
1217   int index = 0;
1218   for (ThreadSnapshot* ts = dump_result.snapshots(); ts != nullptr; ts = ts->next(), index++) {
1219     if (!is_platform_thread(ts)) {
1220       // if the thread does not exist, has terminated, or is a virtual thread, then set threadinfo to null
1221       result_h->obj_at_put(index, nullptr);
1222       continue;
1223     }
1224 
1225     ThreadStackTrace* stacktrace = ts->get_stack_trace();
1226     assert(stacktrace != nullptr, "Must have a stack trace dumped");
1227 
1228     // Create Object[] filled with locked monitors
1229     // Create int[] filled with the stack depth where a monitor was locked
1230     int num_frames = stacktrace->get_stack_depth();
1231     int num_locked_monitors = stacktrace->num_jni_locked_monitors();
1232 
1233     // Count the total number of locked monitors
1234     for (int i = 0; i < num_frames; i++) {
1235       StackFrameInfo* frame = stacktrace->stack_frame_at(i);
1236       num_locked_monitors += frame->num_locked_monitors();
1237     }
1238 
1239     objArrayHandle monitors_array;
1240     typeArrayHandle depths_array;
1241     objArrayHandle synchronizers_array;
1242 
1243     if (locked_monitors) {
1244       // Constructs Object[] and int[] to contain the object monitor and the stack depth
1245       // where the thread locked it
1246       objArrayOop array = oopFactory::new_objArray(vmClasses::Object_klass(), num_locked_monitors, CHECK_NULL);
1247       objArrayHandle mh(THREAD, array);
1248       monitors_array = mh;
1249 
1250       typeArrayOop tarray = oopFactory::new_typeArray(T_INT, num_locked_monitors, CHECK_NULL);
1251       typeArrayHandle dh(THREAD, tarray);
1252       depths_array = dh;
1253 
1254       int count = 0;
1255       int j = 0;
1256       for (int depth = 0; depth < num_frames; depth++) {
1257         StackFrameInfo* frame = stacktrace->stack_frame_at(depth);
1258         int len = frame->num_locked_monitors();
1259         GrowableArray<OopHandle>* locked_monitors = frame->locked_monitors();
1260         for (j = 0; j < len; j++) {
1261           oop monitor = locked_monitors->at(j).resolve();
1262           assert(monitor != nullptr, "must be a Java object");
1263           monitors_array->obj_at_put(count, monitor);
1264           depths_array->int_at_put(count, depth);
1265           count++;
1266         }
1267       }
1268 
1269       GrowableArray<OopHandle>* jni_locked_monitors = stacktrace->jni_locked_monitors();
1270       for (j = 0; j < jni_locked_monitors->length(); j++) {
1271         oop object = jni_locked_monitors->at(j).resolve();
1272         assert(object != nullptr, "must be a Java object");
1273         monitors_array->obj_at_put(count, object);
1274         // Monitor locked via JNI MonitorEnter call doesn't have stack depth info
1275         depths_array->int_at_put(count, -1);
1276         count++;
1277       }
1278       assert(count == num_locked_monitors, "number of locked monitors doesn't match");
1279     }
1280 
1281     if (locked_synchronizers) {
1282       // Create Object[] filled with locked JSR-166 synchronizers
1283       assert(ts->threadObj() != nullptr, "Must be a valid JavaThread");
1284       ThreadConcurrentLocks* tcl = ts->get_concurrent_locks();
1285       GrowableArray<OopHandle>* locks = (tcl != nullptr ? tcl->owned_locks() : nullptr);
1286       int num_locked_synchronizers = (locks != nullptr ? locks->length() : 0);
1287 
1288       objArrayOop array = oopFactory::new_objArray(vmClasses::Object_klass(), num_locked_synchronizers, CHECK_NULL);
1289       objArrayHandle sh(THREAD, array);
1290       synchronizers_array = sh;
1291 
1292       for (int k = 0; k < num_locked_synchronizers; k++) {
1293         synchronizers_array->obj_at_put(k, locks->at(k).resolve());
1294       }
1295     }
1296 
1297     // Create java.lang.management.ThreadInfo object
1298     instanceOop info_obj = Management::create_thread_info_instance(ts,
1299                                                                    monitors_array,
1300                                                                    depths_array,
1301                                                                    synchronizers_array,
1302                                                                    CHECK_NULL);
1303     result_h->obj_at_put(index, info_obj);
1304   }
1305 
1306   return (jobjectArray) JNIHandles::make_local(THREAD, result_h());
1307 JVM_END
1308 
1309 // Reset statistic.  Return true if the requested statistic is reset.
1310 // Otherwise, return false.
1311 //
1312 // Input parameters:
1313 //  obj  - specify which instance the statistic associated with to be reset
1314 //         For PEAK_POOL_USAGE stat, obj is required to be a memory pool object.
1315 //         For THREAD_CONTENTION_COUNT and TIME stat, obj is required to be a thread ID.
1316 //  type - the type of statistic to be reset
1317 //
1318 JVM_ENTRY(jboolean, jmm_ResetStatistic(JNIEnv *env, jvalue obj, jmmStatisticType type))
1319   ResourceMark rm(THREAD);
1320 
1321   switch (type) {
1322     case JMM_STAT_PEAK_THREAD_COUNT:
1323       ThreadService::reset_peak_thread_count();
1324       return true;
1325 
1326     case JMM_STAT_THREAD_CONTENTION_COUNT:
1327     case JMM_STAT_THREAD_CONTENTION_TIME: {
1328       jlong tid = obj.j;
1329       if (tid < 0) {
1330         THROW_(vmSymbols::java_lang_IllegalArgumentException(), JNI_FALSE);
1331       }
1332 
1333       // Look for the JavaThread of this given tid
1334       JavaThreadIteratorWithHandle jtiwh;
1335       if (tid == 0) {
1336         // reset contention statistics for all threads if tid == 0
1337         for (; JavaThread *java_thread = jtiwh.next(); ) {
1338           if (type == JMM_STAT_THREAD_CONTENTION_COUNT) {
1339             ThreadService::reset_contention_count_stat(java_thread);
1340           } else {
1341             ThreadService::reset_contention_time_stat(java_thread);
1342           }
1343         }
1344       } else {
1345         // reset contention statistics for a given thread
1346         JavaThread* java_thread = jtiwh.list()->find_JavaThread_from_java_tid(tid);
1347         if (java_thread == nullptr) {
1348           return false;
1349         }
1350 
1351         if (type == JMM_STAT_THREAD_CONTENTION_COUNT) {
1352           ThreadService::reset_contention_count_stat(java_thread);
1353         } else {
1354           ThreadService::reset_contention_time_stat(java_thread);
1355         }
1356       }
1357       return true;
1358       break;
1359     }
1360     case JMM_STAT_PEAK_POOL_USAGE: {
1361       jobject o = obj.l;
1362       if (o == nullptr) {
1363         THROW_(vmSymbols::java_lang_NullPointerException(), JNI_FALSE);
1364       }
1365 
1366       oop pool_obj = JNIHandles::resolve(o);
1367       assert(pool_obj->is_instance(), "Should be an instanceOop");
1368       instanceHandle ph(THREAD, (instanceOop) pool_obj);
1369 
1370       MemoryPool* pool = MemoryService::get_memory_pool(ph);
1371       if (pool != nullptr) {
1372         pool->reset_peak_memory_usage();
1373         return true;
1374       }
1375       break;
1376     }
1377     case JMM_STAT_GC_STAT: {
1378       jobject o = obj.l;
1379       if (o == nullptr) {
1380         THROW_(vmSymbols::java_lang_NullPointerException(), JNI_FALSE);
1381       }
1382 
1383       GCMemoryManager* mgr = get_gc_memory_manager_from_jobject(o, CHECK_false);
1384       if (mgr != nullptr) {
1385         mgr->reset_gc_stat();
1386         return true;
1387       }
1388       break;
1389     }
1390     default:
1391       assert(0, "Unknown Statistic Type");
1392   }
1393   return false;
1394 JVM_END
1395 
1396 // Returns the fast estimate of CPU time consumed by
1397 // a given thread (in nanoseconds).
1398 // If thread_id == 0, return CPU time for the current thread.
1399 JVM_ENTRY(jlong, jmm_GetThreadCpuTime(JNIEnv *env, jlong thread_id))
1400   if (!os::is_thread_cpu_time_supported()) {
1401     return -1;
1402   }
1403 
1404   if (thread_id < 0) {
1405     THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
1406                "Invalid thread ID", -1);
1407   }
1408 
1409   JavaThread* java_thread = nullptr;
1410   if (thread_id == 0) {
1411     // current thread
1412     return os::current_thread_cpu_time();
1413   } else {
1414     ThreadsListHandle tlh;
1415     java_thread = tlh.list()->find_JavaThread_from_java_tid(thread_id);
1416     if (is_platform_thread(java_thread)) {
1417       return os::thread_cpu_time((Thread*) java_thread);
1418     }
1419   }
1420   return -1;
1421 JVM_END
1422 
1423 // Returns a String array of all VM global flag names
1424 JVM_ENTRY(jobjectArray, jmm_GetVMGlobalNames(JNIEnv *env))
1425   // last flag entry is always null, so subtract 1
1426   int nFlags = (int) JVMFlag::numFlags - 1;
1427   // allocate a temp array
1428   objArrayOop r = oopFactory::new_objArray(vmClasses::String_klass(),
1429                                            nFlags, CHECK_NULL);
1430   objArrayHandle flags_ah(THREAD, r);
1431   int num_entries = 0;
1432   for (int i = 0; i < nFlags; i++) {
1433     JVMFlag* flag = &JVMFlag::flags[i];
1434     // Exclude develop flags in product builds.
1435     if (flag->is_constant_in_binary()) {
1436       continue;
1437     }
1438     // Exclude the locked (experimental, diagnostic) flags
1439     if (flag->is_unlocked() || flag->is_unlocker()) {
1440       Handle s = java_lang_String::create_from_str(flag->name(), CHECK_NULL);
1441       flags_ah->obj_at_put(num_entries, s());
1442       num_entries++;
1443     }
1444   }
1445 
1446   if (num_entries < nFlags) {
1447     // Return array of right length
1448     objArrayOop res = oopFactory::new_objArray(vmClasses::String_klass(), num_entries, CHECK_NULL);
1449     for(int i = 0; i < num_entries; i++) {
1450       res->obj_at_put(i, flags_ah->obj_at(i));
1451     }
1452     return (jobjectArray)JNIHandles::make_local(THREAD, res);
1453   }
1454 
1455   return (jobjectArray)JNIHandles::make_local(THREAD, flags_ah());
1456 JVM_END
1457 
1458 // Utility function used by jmm_GetVMGlobals.  Returns false if flag type
1459 // can't be determined, true otherwise.  If false is returned, then *global
1460 // will be incomplete and invalid.
1461 static bool add_global_entry(Handle name, jmmVMGlobal *global, JVMFlag *flag, TRAPS) {
1462   Handle flag_name;
1463   if (name() == nullptr) {
1464     flag_name = java_lang_String::create_from_str(flag->name(), CHECK_false);
1465   } else {
1466     flag_name = name;
1467   }
1468   global->name = (jstring)JNIHandles::make_local(THREAD, flag_name());
1469 
1470   if (flag->is_bool()) {
1471     global->value.z = flag->get_bool() ? JNI_TRUE : JNI_FALSE;
1472     global->type = JMM_VMGLOBAL_TYPE_JBOOLEAN;
1473   } else if (flag->is_int()) {
1474     global->value.j = (jlong)flag->get_int();
1475     global->type = JMM_VMGLOBAL_TYPE_JLONG;
1476   } else if (flag->is_uint()) {
1477     global->value.j = (jlong)flag->get_uint();
1478     global->type = JMM_VMGLOBAL_TYPE_JLONG;
1479   } else if (flag->is_intx()) {
1480     global->value.j = (jlong)flag->get_intx();
1481     global->type = JMM_VMGLOBAL_TYPE_JLONG;
1482   } else if (flag->is_uintx()) {
1483     global->value.j = (jlong)flag->get_uintx();
1484     global->type = JMM_VMGLOBAL_TYPE_JLONG;
1485   } else if (flag->is_uint64_t()) {
1486     global->value.j = (jlong)flag->get_uint64_t();
1487     global->type = JMM_VMGLOBAL_TYPE_JLONG;
1488   } else if (flag->is_double()) {
1489     global->value.d = (jdouble)flag->get_double();
1490     global->type = JMM_VMGLOBAL_TYPE_JDOUBLE;
1491   } else if (flag->is_size_t()) {
1492     global->value.j = (jlong)flag->get_size_t();
1493     global->type = JMM_VMGLOBAL_TYPE_JLONG;
1494   } else if (flag->is_ccstr()) {
1495     Handle str = java_lang_String::create_from_str(flag->get_ccstr(), CHECK_false);
1496     global->value.l = (jobject)JNIHandles::make_local(THREAD, str());
1497     global->type = JMM_VMGLOBAL_TYPE_JSTRING;
1498   } else {
1499     global->type = JMM_VMGLOBAL_TYPE_UNKNOWN;
1500     return false;
1501   }
1502 
1503   global->writeable = flag->is_writeable();
1504   global->external = flag->is_external();
1505   switch (flag->get_origin()) {
1506     case JVMFlagOrigin::DEFAULT:
1507       global->origin = JMM_VMGLOBAL_ORIGIN_DEFAULT;
1508       break;
1509     case JVMFlagOrigin::COMMAND_LINE:
1510       global->origin = JMM_VMGLOBAL_ORIGIN_COMMAND_LINE;
1511       break;
1512     case JVMFlagOrigin::ENVIRON_VAR:
1513       global->origin = JMM_VMGLOBAL_ORIGIN_ENVIRON_VAR;
1514       break;
1515     case JVMFlagOrigin::CONFIG_FILE:
1516       global->origin = JMM_VMGLOBAL_ORIGIN_CONFIG_FILE;
1517       break;
1518     case JVMFlagOrigin::MANAGEMENT:
1519       global->origin = JMM_VMGLOBAL_ORIGIN_MANAGEMENT;
1520       break;
1521     case JVMFlagOrigin::ERGONOMIC:
1522       global->origin = JMM_VMGLOBAL_ORIGIN_ERGONOMIC;
1523       break;
1524     case JVMFlagOrigin::ATTACH_ON_DEMAND:
1525       global->origin = JMM_VMGLOBAL_ORIGIN_ATTACH_ON_DEMAND;
1526       break;
1527     default:
1528       global->origin = JMM_VMGLOBAL_ORIGIN_OTHER;
1529   }
1530 
1531   return true;
1532 }
1533 
1534 // Fill globals array of count length with jmmVMGlobal entries
1535 // specified by names. If names == null, fill globals array
1536 // with all Flags. Return value is number of entries
1537 // created in globals.
1538 // If a JVMFlag with a given name in an array element does not
1539 // exist, globals[i].name will be set to null.
1540 JVM_ENTRY(jint, jmm_GetVMGlobals(JNIEnv *env,
1541                                  jobjectArray names,
1542                                  jmmVMGlobal *globals,
1543                                  jint count))
1544 
1545 
1546   if (globals == nullptr) {
1547     THROW_(vmSymbols::java_lang_NullPointerException(), 0);
1548   }
1549 
1550   ResourceMark rm(THREAD);
1551 
1552   if (names != nullptr) {
1553     // return the requested globals
1554     objArrayOop ta = objArrayOop(JNIHandles::resolve_non_null(names));
1555     objArrayHandle names_ah(THREAD, ta);
1556     // Make sure we have a String array
1557     Klass* element_klass = ObjArrayKlass::cast(names_ah->klass())->element_klass();
1558     if (element_klass != vmClasses::String_klass()) {
1559       THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
1560                  "Array element type is not String class", 0);
1561     }
1562 
1563     int names_length = names_ah->length();
1564     int num_entries = 0;
1565     for (int i = 0; i < names_length && i < count; i++) {
1566       oop s = names_ah->obj_at(i);
1567       if (s == nullptr) {
1568         THROW_(vmSymbols::java_lang_NullPointerException(), 0);
1569       }
1570 
1571       Handle sh(THREAD, s);
1572       char* str = java_lang_String::as_utf8_string(s);
1573       JVMFlag* flag = JVMFlag::find_flag(str);
1574       if (flag != nullptr &&
1575           add_global_entry(sh, &globals[i], flag, THREAD)) {
1576         num_entries++;
1577       } else {
1578         globals[i].name = nullptr;
1579       }
1580     }
1581     return num_entries;
1582   } else {
1583     // return all globals if names == null
1584 
1585     // last flag entry is always null, so subtract 1
1586     int nFlags = (int) JVMFlag::numFlags - 1;
1587     Handle null_h;
1588     int num_entries = 0;
1589     for (int i = 0; i < nFlags && num_entries < count;  i++) {
1590       JVMFlag* flag = &JVMFlag::flags[i];
1591       // Exclude develop flags in product builds.
1592       if (flag->is_constant_in_binary()) {
1593         continue;
1594       }
1595       // Exclude the locked (diagnostic, experimental) flags
1596       if ((flag->is_unlocked() || flag->is_unlocker()) &&
1597           add_global_entry(null_h, &globals[num_entries], flag, THREAD)) {
1598         num_entries++;
1599       }
1600     }
1601     return num_entries;
1602   }
1603 JVM_END
1604 
1605 JVM_ENTRY(void, jmm_SetVMGlobal(JNIEnv *env, jstring flag_name, jvalue new_value))
1606   ResourceMark rm(THREAD);
1607 
1608   oop fn = JNIHandles::resolve_external_guard(flag_name);
1609   if (fn == nullptr) {
1610     THROW_MSG(vmSymbols::java_lang_NullPointerException(),
1611               "The flag name cannot be null.");
1612   }
1613   char* name = java_lang_String::as_utf8_string(fn);
1614 
1615   FormatBuffer<80> error_msg("%s", "");
1616   int succeed = WriteableFlags::set_flag(name, new_value, JVMFlagOrigin::MANAGEMENT, error_msg);
1617 
1618   if (succeed != JVMFlag::SUCCESS) {
1619     if (succeed == JVMFlag::MISSING_VALUE) {
1620       // missing value causes NPE to be thrown
1621       THROW(vmSymbols::java_lang_NullPointerException());
1622     } else {
1623       // all the other errors are reported as IAE with the appropriate error message
1624       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
1625                 error_msg.buffer());
1626     }
1627   }
1628   assert(succeed == JVMFlag::SUCCESS, "Setting flag should succeed");
1629 JVM_END
1630 
1631 class ThreadTimesClosure: public ThreadClosure {
1632  private:
1633   objArrayHandle _names_strings;
1634   char **_names_chars;
1635   typeArrayHandle _times;
1636   int _names_len;
1637   int _times_len;
1638   int _count;
1639 
1640  public:
1641   ThreadTimesClosure(objArrayHandle names, typeArrayHandle times);
1642   ~ThreadTimesClosure();
1643   virtual void do_thread(Thread* thread);
1644   void do_unlocked(TRAPS);
1645   int count() { return _count; }
1646 };
1647 
1648 ThreadTimesClosure::ThreadTimesClosure(objArrayHandle names,
1649                                        typeArrayHandle times) {
1650   assert(names() != nullptr, "names was null");
1651   assert(times() != nullptr, "times was null");
1652   _names_strings = names;
1653   _names_len = names->length();
1654   _names_chars = NEW_C_HEAP_ARRAY(char*, _names_len, mtInternal);
1655   _times = times;
1656   _times_len = times->length();
1657   _count = 0;
1658 }
1659 
1660 //
1661 // Called with Threads_lock held
1662 //
1663 void ThreadTimesClosure::do_thread(Thread* thread) {
1664   assert(Threads_lock->owned_by_self(), "Must hold Threads_lock");
1665   assert(thread != nullptr, "thread was null");
1666 
1667   // exclude externally visible JavaThreads
1668   if (thread->is_Java_thread() && !thread->is_hidden_from_external_view()) {
1669     return;
1670   }
1671 
1672   if (_count >= _names_len || _count >= _times_len) {
1673     // skip if the result array is not big enough
1674     return;
1675   }
1676 
1677   ResourceMark rm; // thread->name() uses ResourceArea
1678 
1679   assert(thread->name() != nullptr, "All threads should have a name");
1680   _names_chars[_count] = os::strdup_check_oom(thread->name());
1681   _times->long_at_put(_count, os::is_thread_cpu_time_supported() ?
1682                         os::thread_cpu_time(thread) : -1);
1683   _count++;
1684 }
1685 
1686 // Called without Threads_lock, we can allocate String objects.
1687 void ThreadTimesClosure::do_unlocked(TRAPS) {
1688 
1689   for (int i = 0; i < _count; i++) {
1690     Handle s = java_lang_String::create_from_str(_names_chars[i],  CHECK);
1691     _names_strings->obj_at_put(i, s());
1692   }
1693 }
1694 
1695 ThreadTimesClosure::~ThreadTimesClosure() {
1696   for (int i = 0; i < _count; i++) {
1697     os::free(_names_chars[i]);
1698   }
1699   FREE_C_HEAP_ARRAY(char *, _names_chars);
1700 }
1701 
1702 // Fills names with VM internal thread names and times with the corresponding
1703 // CPU times.  If names or times is null, a NullPointerException is thrown.
1704 // If the element type of names is not String, an IllegalArgumentException is
1705 // thrown.
1706 // If an array is not large enough to hold all the entries, only the entries
1707 // that fit will be returned.  Return value is the number of VM internal
1708 // threads entries.
1709 JVM_ENTRY(jint, jmm_GetInternalThreadTimes(JNIEnv *env,
1710                                            jobjectArray names,
1711                                            jlongArray times))
1712   if (names == nullptr || times == nullptr) {
1713      THROW_(vmSymbols::java_lang_NullPointerException(), 0);
1714   }
1715   objArrayOop na = objArrayOop(JNIHandles::resolve_non_null(names));
1716   objArrayHandle names_ah(THREAD, na);
1717 
1718   // Make sure we have a String array
1719   Klass* element_klass = ObjArrayKlass::cast(names_ah->klass())->element_klass();
1720   if (element_klass != vmClasses::String_klass()) {
1721     THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
1722                "Array element type is not String class", 0);
1723   }
1724 
1725   typeArrayOop ta = typeArrayOop(JNIHandles::resolve_non_null(times));
1726   typeArrayHandle times_ah(THREAD, ta);
1727 
1728   ThreadTimesClosure ttc(names_ah, times_ah);
1729   {
1730     MutexLocker ml(THREAD, Threads_lock);
1731     Threads::threads_do(&ttc);
1732   }
1733   ttc.do_unlocked(THREAD);
1734   return ttc.count();
1735 JVM_END
1736 
1737 static Handle find_deadlocks(bool object_monitors_only, TRAPS) {
1738   ResourceMark rm(THREAD);
1739 
1740   VM_FindDeadlocks op(!object_monitors_only /* also check concurrent locks? */);
1741   VMThread::execute(&op);
1742 
1743   DeadlockCycle* deadlocks = op.result();
1744   if (deadlocks == nullptr) {
1745     // no deadlock found and return
1746     return Handle();
1747   }
1748 
1749   int num_threads = 0;
1750   DeadlockCycle* cycle;
1751   for (cycle = deadlocks; cycle != nullptr; cycle = cycle->next()) {
1752     num_threads += cycle->num_threads();
1753   }
1754 
1755   objArrayOop r = oopFactory::new_objArray(vmClasses::Thread_klass(), num_threads, CHECK_NH);
1756   objArrayHandle threads_ah(THREAD, r);
1757 
1758   int index = 0;
1759   for (cycle = deadlocks; cycle != nullptr; cycle = cycle->next()) {
1760     GrowableArray<JavaThread*>* deadlock_threads = cycle->threads();
1761     int len = deadlock_threads->length();
1762     for (int i = 0; i < len; i++) {
1763       threads_ah->obj_at_put(index, deadlock_threads->at(i)->threadObj());
1764       index++;
1765     }
1766   }
1767   return threads_ah;
1768 }
1769 
1770 // Finds cycles of threads that are deadlocked involved in object monitors
1771 // and JSR-166 synchronizers.
1772 // Returns an array of Thread objects which are in deadlock, if any.
1773 // Otherwise, returns null.
1774 //
1775 // Input parameter:
1776 //    object_monitors_only - if true, only check object monitors
1777 //
1778 JVM_ENTRY(jobjectArray, jmm_FindDeadlockedThreads(JNIEnv *env, jboolean object_monitors_only))
1779   Handle result = find_deadlocks(object_monitors_only != 0, CHECK_NULL);
1780   return (jobjectArray) JNIHandles::make_local(THREAD, result());
1781 JVM_END
1782 
1783 // Finds cycles of threads that are deadlocked on monitor locks
1784 // Returns an array of Thread objects which are in deadlock, if any.
1785 // Otherwise, returns null.
1786 JVM_ENTRY(jobjectArray, jmm_FindMonitorDeadlockedThreads(JNIEnv *env))
1787   Handle result = find_deadlocks(true, CHECK_NULL);
1788   return (jobjectArray) JNIHandles::make_local(THREAD, result());
1789 JVM_END
1790 
1791 // Gets the information about GC extension attributes including
1792 // the name of the attribute, its type, and a short description.
1793 //
1794 // Input parameters:
1795 //   mgr   - GC memory manager
1796 //   info  - caller allocated array of jmmExtAttributeInfo
1797 //   count - number of elements of the info array
1798 //
1799 // Returns the number of GC extension attributes filled in the info array; or
1800 // -1 if info is not big enough
1801 //
1802 JVM_ENTRY(jint, jmm_GetGCExtAttributeInfo(JNIEnv *env, jobject mgr, jmmExtAttributeInfo* info, jint count))
1803   // All GC memory managers have 1 attribute (number of GC threads)
1804   if (count == 0) {
1805     return 0;
1806   }
1807 
1808   if (info == nullptr) {
1809    THROW_(vmSymbols::java_lang_NullPointerException(), 0);
1810   }
1811 
1812   info[0].name = "GcThreadCount";
1813   info[0].type = 'I';
1814   info[0].description = "Number of GC threads";
1815   return 1;
1816 JVM_END
1817 
1818 // verify the given array is an array of java/lang/management/MemoryUsage objects
1819 // of a given length and return the objArrayOop
1820 static objArrayOop get_memory_usage_objArray(jobjectArray array, int length, TRAPS) {
1821   if (array == nullptr) {
1822     THROW_NULL(vmSymbols::java_lang_NullPointerException());
1823   }
1824 
1825   objArrayOop oa = objArrayOop(JNIHandles::resolve_non_null(array));
1826   objArrayHandle array_h(THREAD, oa);
1827 
1828   // array must be of the given length
1829   if (length != array_h->length()) {
1830     THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(),
1831                    "The length of the given MemoryUsage array does not match the number of memory pools.");
1832   }
1833 
1834   // check if the element of array is of type MemoryUsage class
1835   Klass* usage_klass = Management::java_lang_management_MemoryUsage_klass(CHECK_NULL);
1836   Klass* element_klass = ObjArrayKlass::cast(array_h->klass())->element_klass();
1837   if (element_klass != usage_klass) {
1838     THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(),
1839                    "The element type is not MemoryUsage class");
1840   }
1841 
1842   return array_h();
1843 }
1844 
1845 // Gets the statistics of the last GC of a given GC memory manager.
1846 // Input parameters:
1847 //   obj     - GarbageCollectorMXBean object
1848 //   gc_stat - caller allocated jmmGCStat where:
1849 //     a. before_gc_usage - array of MemoryUsage objects
1850 //     b. after_gc_usage  - array of MemoryUsage objects
1851 //     c. gc_ext_attributes_values_size is set to the
1852 //        gc_ext_attribute_values array allocated
1853 //     d. gc_ext_attribute_values is a caller allocated array of jvalue.
1854 //
1855 // On return,
1856 //   gc_index == 0 indicates no GC statistics available
1857 //
1858 //   before_gc_usage and after_gc_usage - filled with per memory pool
1859 //      before and after GC usage in the same order as the memory pools
1860 //      returned by GetMemoryPools for a given GC memory manager.
1861 //   num_gc_ext_attributes indicates the number of elements in
1862 //      the gc_ext_attribute_values array is filled; or
1863 //      -1 if the gc_ext_attributes_values array is not big enough
1864 //
1865 JVM_ENTRY(void, jmm_GetLastGCStat(JNIEnv *env, jobject obj, jmmGCStat *gc_stat))
1866   ResourceMark rm(THREAD);
1867 
1868   if (gc_stat->gc_ext_attribute_values_size > 0 && gc_stat->gc_ext_attribute_values == nullptr) {
1869     THROW(vmSymbols::java_lang_NullPointerException());
1870   }
1871 
1872   // Get the GCMemoryManager
1873   GCMemoryManager* mgr = get_gc_memory_manager_from_jobject(obj, CHECK);
1874 
1875   // Make a copy of the last GC statistics
1876   // GC may occur while constructing the last GC information
1877   int num_pools = MemoryService::num_memory_pools();
1878   GCStatInfo stat(num_pools);
1879   if (mgr->get_last_gc_stat(&stat) == 0) {
1880     gc_stat->gc_index = 0;
1881     return;
1882   }
1883 
1884   gc_stat->gc_index = stat.gc_index();
1885   gc_stat->start_time = Management::ticks_to_ms(stat.start_time());
1886   gc_stat->end_time = Management::ticks_to_ms(stat.end_time());
1887 
1888   // Current implementation does not have GC extension attributes
1889   gc_stat->num_gc_ext_attributes = 0;
1890 
1891   // Fill the arrays of MemoryUsage objects with before and after GC
1892   // per pool memory usage
1893   objArrayOop bu = get_memory_usage_objArray(gc_stat->usage_before_gc,
1894                                              num_pools,
1895                                              CHECK);
1896   objArrayHandle usage_before_gc_ah(THREAD, bu);
1897 
1898   objArrayOop au = get_memory_usage_objArray(gc_stat->usage_after_gc,
1899                                              num_pools,
1900                                              CHECK);
1901   objArrayHandle usage_after_gc_ah(THREAD, au);
1902 
1903   for (int i = 0; i < num_pools; i++) {
1904     Handle before_usage = MemoryService::create_MemoryUsage_obj(stat.before_gc_usage_for_pool(i), CHECK);
1905     Handle after_usage;
1906 
1907     MemoryUsage u = stat.after_gc_usage_for_pool(i);
1908     if (u.max_size() == 0 && u.used() > 0) {
1909       // If max size == 0, this pool is a survivor space.
1910       // Set max size = -1 since the pools will be swapped after GC.
1911       MemoryUsage usage(u.init_size(), u.used(), u.committed(), MemoryUsage::undefined_size());
1912       after_usage = MemoryService::create_MemoryUsage_obj(usage, CHECK);
1913     } else {
1914       after_usage = MemoryService::create_MemoryUsage_obj(stat.after_gc_usage_for_pool(i), CHECK);
1915     }
1916     usage_before_gc_ah->obj_at_put(i, before_usage());
1917     usage_after_gc_ah->obj_at_put(i, after_usage());
1918   }
1919 
1920   if (gc_stat->gc_ext_attribute_values_size > 0) {
1921     // Current implementation only has 1 attribute (number of GC threads)
1922     // The type is 'I'
1923     gc_stat->gc_ext_attribute_values[0].i = mgr->num_gc_threads();
1924   }
1925 JVM_END
1926 
1927 JVM_ENTRY(void, jmm_SetGCNotificationEnabled(JNIEnv *env, jobject obj, jboolean enabled))
1928   ResourceMark rm(THREAD);
1929   // Get the GCMemoryManager
1930   GCMemoryManager* mgr = get_gc_memory_manager_from_jobject(obj, CHECK);
1931   mgr->set_notification_enabled(enabled?true:false);
1932 JVM_END
1933 
1934 // Dump heap - Returns 0 if succeeds.
1935 JVM_ENTRY(jint, jmm_DumpHeap0(JNIEnv *env, jstring outputfile, jboolean live))
1936 #if INCLUDE_SERVICES
1937   ResourceMark rm(THREAD);
1938   oop on = JNIHandles::resolve_external_guard(outputfile);
1939   if (on == nullptr) {
1940     THROW_MSG_(vmSymbols::java_lang_NullPointerException(),
1941                "Output file name cannot be null.", -1);
1942   }
1943   Handle onhandle(THREAD, on);
1944   char* name = java_lang_String::as_platform_dependent_str(onhandle, CHECK_(-1));
1945   if (name == nullptr) {
1946     THROW_MSG_(vmSymbols::java_lang_NullPointerException(),
1947                "Output file name cannot be null.", -1);
1948   }
1949   HeapDumper dumper(live ? true : false);
1950   if (dumper.dump(name) != 0) {
1951     const char* errmsg = dumper.error_as_C_string();
1952     THROW_MSG_(vmSymbols::java_io_IOException(), errmsg, -1);
1953   }
1954   return 0;
1955 #else  // INCLUDE_SERVICES
1956   return -1;
1957 #endif // INCLUDE_SERVICES
1958 JVM_END
1959 
1960 JVM_ENTRY(jobjectArray, jmm_GetDiagnosticCommands(JNIEnv *env))
1961   ResourceMark rm(THREAD);
1962   GrowableArray<const char *>* dcmd_list = DCmdFactory::DCmd_list(DCmd_Source_MBean);
1963   objArrayOop cmd_array_oop = oopFactory::new_objArray(vmClasses::String_klass(),
1964           dcmd_list->length(), CHECK_NULL);
1965   objArrayHandle cmd_array(THREAD, cmd_array_oop);
1966   for (int i = 0; i < dcmd_list->length(); i++) {
1967     oop cmd_name = java_lang_String::create_oop_from_str(dcmd_list->at(i), CHECK_NULL);
1968     cmd_array->obj_at_put(i, cmd_name);
1969   }
1970   return (jobjectArray) JNIHandles::make_local(THREAD, cmd_array());
1971 JVM_END
1972 
1973 JVM_ENTRY(void, jmm_GetDiagnosticCommandInfo(JNIEnv *env, jobjectArray cmds,
1974           dcmdInfo* infoArray))
1975   if (cmds == nullptr || infoArray == nullptr) {
1976     THROW(vmSymbols::java_lang_NullPointerException());
1977   }
1978 
1979   ResourceMark rm(THREAD);
1980 
1981   objArrayOop ca = objArrayOop(JNIHandles::resolve_non_null(cmds));
1982   objArrayHandle cmds_ah(THREAD, ca);
1983 
1984   // Make sure we have a String array
1985   Klass* element_klass = ObjArrayKlass::cast(cmds_ah->klass())->element_klass();
1986   if (element_klass != vmClasses::String_klass()) {
1987     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
1988                "Array element type is not String class");
1989   }
1990 
1991   GrowableArray<DCmdInfo *>* info_list = DCmdFactory::DCmdInfo_list(DCmd_Source_MBean);
1992 
1993   int num_cmds = cmds_ah->length();
1994   for (int i = 0; i < num_cmds; i++) {
1995     oop cmd = cmds_ah->obj_at(i);
1996     if (cmd == nullptr) {
1997         THROW_MSG(vmSymbols::java_lang_NullPointerException(),
1998                 "Command name cannot be null.");
1999     }
2000     char* cmd_name = java_lang_String::as_utf8_string(cmd);
2001     if (cmd_name == nullptr) {
2002         THROW_MSG(vmSymbols::java_lang_NullPointerException(),
2003                 "Command name cannot be null.");
2004     }
2005     int pos = info_list->find_if([&](DCmdInfo* info) {
2006       return info->name_equals(cmd_name);
2007     });
2008     if (pos == -1) {
2009         THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
2010              "Unknown diagnostic command");
2011     }
2012     DCmdInfo* info = info_list->at(pos);
2013     infoArray[i].name = info->name();
2014     infoArray[i].description = info->description();
2015     infoArray[i].impact = info->impact();
2016     infoArray[i].num_arguments = info->num_arguments();
2017     infoArray[i].enabled = info->is_enabled();
2018   }
2019 JVM_END
2020 
2021 JVM_ENTRY(void, jmm_GetDiagnosticCommandArgumentsInfo(JNIEnv *env,
2022           jstring command, dcmdArgInfo* infoArray, jint count))
2023   ResourceMark rm(THREAD);
2024   oop cmd = JNIHandles::resolve_external_guard(command);
2025   if (cmd == nullptr) {
2026     THROW_MSG(vmSymbols::java_lang_NullPointerException(),
2027               "Command line cannot be null.");
2028   }
2029   char* cmd_name = java_lang_String::as_utf8_string(cmd);
2030   if (cmd_name == nullptr) {
2031     THROW_MSG(vmSymbols::java_lang_NullPointerException(),
2032               "Command line content cannot be null.");
2033   }
2034   DCmd* dcmd = nullptr;
2035   DCmdFactory*factory = DCmdFactory::factory(DCmd_Source_MBean, cmd_name,
2036                                              strlen(cmd_name));
2037   if (factory != nullptr) {
2038     dcmd = factory->create_resource_instance(nullptr);
2039   }
2040   if (dcmd == nullptr) {
2041     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
2042               "Unknown diagnostic command");
2043   }
2044   DCmdMark mark(dcmd);
2045   GrowableArray<DCmdArgumentInfo*>* array = dcmd->argument_info_array();
2046   const int num_args = array->length();
2047   if (num_args != count) {
2048     assert(false, "jmm_GetDiagnosticCommandArgumentsInfo count mismatch (%d vs %d)", count, num_args);
2049     THROW_MSG(vmSymbols::java_lang_InternalError(), "jmm_GetDiagnosticCommandArgumentsInfo count mismatch");
2050   }
2051   for (int i = 0; i < num_args; i++) {
2052     infoArray[i].name = array->at(i)->name();
2053     infoArray[i].description = array->at(i)->description();
2054     infoArray[i].type = array->at(i)->type();
2055     infoArray[i].default_string = array->at(i)->default_string();
2056     infoArray[i].mandatory = array->at(i)->is_mandatory();
2057     infoArray[i].option = array->at(i)->is_option();
2058     infoArray[i].multiple = array->at(i)->is_multiple();
2059     infoArray[i].position = array->at(i)->position();
2060   }
2061   return;
2062 JVM_END
2063 
2064 JVM_ENTRY(jstring, jmm_ExecuteDiagnosticCommand(JNIEnv *env, jstring commandline))
2065   ResourceMark rm(THREAD);
2066   oop cmd = JNIHandles::resolve_external_guard(commandline);
2067   if (cmd == nullptr) {
2068     THROW_MSG_NULL(vmSymbols::java_lang_NullPointerException(),
2069                    "Command line cannot be null.");
2070   }
2071   char* cmdline = java_lang_String::as_utf8_string(cmd);
2072   if (cmdline == nullptr) {
2073     THROW_MSG_NULL(vmSymbols::java_lang_NullPointerException(),
2074                    "Command line content cannot be null.");
2075   }
2076   bufferedStream output;
2077   DCmd::parse_and_execute(DCmd_Source_MBean, &output, cmdline, ' ', CHECK_NULL);
2078   oop result = java_lang_String::create_oop_from_str(output.as_string(), CHECK_NULL);
2079   return (jstring) JNIHandles::make_local(THREAD, result);
2080 JVM_END
2081 
2082 JVM_ENTRY(void, jmm_SetDiagnosticFrameworkNotificationEnabled(JNIEnv *env, jboolean enabled))
2083   DCmdFactory::set_jmx_notification_enabled(enabled?true:false);
2084 JVM_END
2085 
2086 jlong Management::ticks_to_ms(jlong ticks) {
2087   assert(os::elapsed_frequency() > 0, "Must be non-zero");
2088   return (jlong)(((double)ticks / (double)os::elapsed_frequency())
2089                  * (double)1000.0);
2090 }
2091 
2092 jlong Management::ticks_to_us(jlong ticks) {
2093   assert(os::elapsed_frequency() > 0, "Must be non-zero");
2094   return (jlong)(((double)ticks / (double)os::elapsed_frequency())
2095                  * (double)1000000.0);
2096 }
2097 
2098 // Gets the amount of memory allocated on the Java heap since JVM launch.
2099 JVM_ENTRY(jlong, jmm_GetTotalThreadAllocatedMemory(JNIEnv *env))
2100     // A thread increments exited_allocated_bytes in ThreadService::remove_thread
2101     // only after it removes itself from the threads list, and once a TLH is
2102     // created, no thread it references can remove itself from the threads
2103     // list, so none can update exited_allocated_bytes. We therefore initialize
2104     // result with exited_allocated_bytes after after we create the TLH so that
2105     // the final result can only be short due to (1) threads that start after
2106     // the TLH is created, or (2) terminating threads that escape TLH creation
2107     // and don't update exited_allocated_bytes before we initialize result.
2108 
2109     // We keep a high water mark to ensure monotonicity in case threads counted
2110     // on a previous call end up in state (2).
2111     static jlong high_water_result = 0;
2112 
2113     JavaThreadIteratorWithHandle jtiwh;
2114     jlong result = ThreadService::exited_allocated_bytes();
2115     for (; JavaThread* thread = jtiwh.next();) {
2116       jlong size = thread->cooked_allocated_bytes();
2117       result += size;
2118     }
2119 
2120     {
2121       assert(MonitoringSupport_lock != nullptr, "Must be");
2122       MutexLocker ml(MonitoringSupport_lock, Mutex::_no_safepoint_check_flag);
2123       if (result < high_water_result) {
2124         // Encountered (2) above, or result wrapped to a negative value. In
2125         // the latter case, it's pegged at the last positive value.
2126         result = high_water_result;
2127       } else {
2128         high_water_result = result;
2129       }
2130     }
2131     return result;
2132 JVM_END
2133 
2134 // Gets the amount of memory allocated on the Java heap for a single thread.
2135 // Returns -1 if the thread does not exist or has terminated.
2136 JVM_ENTRY(jlong, jmm_GetOneThreadAllocatedMemory(JNIEnv *env, jlong thread_id))
2137   if (thread_id < 0) {
2138     THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
2139                "Invalid thread ID", -1);
2140   }
2141 
2142   if (thread_id == 0) { // current thread
2143     return thread->cooked_allocated_bytes();
2144   }
2145 
2146   ThreadsListHandle tlh;
2147   JavaThread* java_thread = tlh.list()->find_JavaThread_from_java_tid(thread_id);
2148   if (is_platform_thread(java_thread)) {
2149     return java_thread->cooked_allocated_bytes();
2150   }
2151   return -1;
2152 JVM_END
2153 
2154 // Gets an array containing the amount of memory allocated on the Java
2155 // heap for a set of threads (in bytes).  Each element of the array is
2156 // the amount of memory allocated for the thread ID specified in the
2157 // corresponding entry in the given array of thread IDs; or -1 if the
2158 // thread does not exist or has terminated.
2159 JVM_ENTRY(void, jmm_GetThreadAllocatedMemory(JNIEnv *env, jlongArray ids,
2160                                              jlongArray sizeArray))
2161   // Check if threads is null
2162   if (ids == nullptr || sizeArray == nullptr) {
2163     THROW(vmSymbols::java_lang_NullPointerException());
2164   }
2165 
2166   ResourceMark rm(THREAD);
2167   typeArrayOop ta = typeArrayOop(JNIHandles::resolve_non_null(ids));
2168   typeArrayHandle ids_ah(THREAD, ta);
2169 
2170   typeArrayOop sa = typeArrayOop(JNIHandles::resolve_non_null(sizeArray));
2171   typeArrayHandle sizeArray_h(THREAD, sa);
2172 
2173   // validate the thread id array
2174   validate_thread_id_array(ids_ah, CHECK);
2175 
2176   // sizeArray must be of the same length as the given array of thread IDs
2177   int num_threads = ids_ah->length();
2178   if (num_threads != sizeArray_h->length()) {
2179     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
2180               "The length of the given long array does not match the length of "
2181               "the given array of thread IDs");
2182   }
2183 
2184   ThreadsListHandle tlh;
2185   for (int i = 0; i < num_threads; i++) {
2186     JavaThread* java_thread = tlh.list()->find_JavaThread_from_java_tid(ids_ah->long_at(i));
2187     if (is_platform_thread(java_thread)) {
2188       sizeArray_h->long_at_put(i, java_thread->cooked_allocated_bytes());
2189     }
2190   }
2191 JVM_END
2192 
2193 // Returns the CPU time consumed by a given thread (in nanoseconds).
2194 // If thread_id == 0, CPU time for the current thread is returned.
2195 // If user_sys_cpu_time = true, user level and system CPU time of
2196 // a given thread is returned; otherwise, only user level CPU time
2197 // is returned.
2198 JVM_ENTRY(jlong, jmm_GetThreadCpuTimeWithKind(JNIEnv *env, jlong thread_id, jboolean user_sys_cpu_time))
2199   if (!os::is_thread_cpu_time_supported()) {
2200     return -1;
2201   }
2202 
2203   if (thread_id < 0) {
2204     THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
2205                "Invalid thread ID", -1);
2206   }
2207 
2208   JavaThread* java_thread = nullptr;
2209   if (thread_id == 0) {
2210     // current thread
2211     return os::current_thread_cpu_time(user_sys_cpu_time != 0);
2212   } else {
2213     ThreadsListHandle tlh;
2214     java_thread = tlh.list()->find_JavaThread_from_java_tid(thread_id);
2215     if (is_platform_thread(java_thread)) {
2216       return os::thread_cpu_time((Thread*) java_thread, user_sys_cpu_time != 0);
2217     }
2218   }
2219   return -1;
2220 JVM_END
2221 
2222 // Gets an array containing the CPU times consumed by a set of threads
2223 // (in nanoseconds).  Each element of the array is the CPU time for the
2224 // thread ID specified in the corresponding entry in the given array
2225 // of thread IDs; or -1 if the thread does not exist or has terminated.
2226 // If user_sys_cpu_time = true, the sum of user level and system CPU time
2227 // for the given thread is returned; otherwise, only user level CPU time
2228 // is returned.
2229 JVM_ENTRY(void, jmm_GetThreadCpuTimesWithKind(JNIEnv *env, jlongArray ids,
2230                                               jlongArray timeArray,
2231                                               jboolean user_sys_cpu_time))
2232   // Check if threads is null
2233   if (ids == nullptr || timeArray == nullptr) {
2234     THROW(vmSymbols::java_lang_NullPointerException());
2235   }
2236 
2237   ResourceMark rm(THREAD);
2238   typeArrayOop ta = typeArrayOop(JNIHandles::resolve_non_null(ids));
2239   typeArrayHandle ids_ah(THREAD, ta);
2240 
2241   typeArrayOop tia = typeArrayOop(JNIHandles::resolve_non_null(timeArray));
2242   typeArrayHandle timeArray_h(THREAD, tia);
2243 
2244   // validate the thread id array
2245   validate_thread_id_array(ids_ah, CHECK);
2246 
2247   // timeArray must be of the same length as the given array of thread IDs
2248   int num_threads = ids_ah->length();
2249   if (num_threads != timeArray_h->length()) {
2250     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
2251               "The length of the given long array does not match the length of "
2252               "the given array of thread IDs");
2253   }
2254 
2255   ThreadsListHandle tlh;
2256   for (int i = 0; i < num_threads; i++) {
2257     JavaThread* java_thread = tlh.list()->find_JavaThread_from_java_tid(ids_ah->long_at(i));
2258     if (is_platform_thread(java_thread)) {
2259       timeArray_h->long_at_put(i, os::thread_cpu_time((Thread*)java_thread,
2260                                                       user_sys_cpu_time != 0));
2261     }
2262   }
2263 JVM_END
2264 
2265 const struct jmmInterface_1_ jmm_interface = {
2266   nullptr,
2267   nullptr,
2268   jmm_GetVersion,
2269   jmm_GetOptionalSupport,
2270   jmm_GetThreadInfo,
2271   jmm_GetMemoryPools,
2272   jmm_GetMemoryManagers,
2273   jmm_GetMemoryPoolUsage,
2274   jmm_GetPeakMemoryPoolUsage,
2275   jmm_GetTotalThreadAllocatedMemory,
2276   jmm_GetOneThreadAllocatedMemory,
2277   jmm_GetThreadAllocatedMemory,
2278   jmm_GetMemoryUsage,
2279   jmm_GetLongAttribute,
2280   jmm_GetBoolAttribute,
2281   jmm_SetBoolAttribute,
2282   jmm_GetLongAttributes,
2283   jmm_FindMonitorDeadlockedThreads,
2284   jmm_GetThreadCpuTime,
2285   jmm_GetVMGlobalNames,
2286   jmm_GetVMGlobals,
2287   jmm_GetInternalThreadTimes,
2288   jmm_ResetStatistic,
2289   jmm_SetPoolSensor,
2290   jmm_SetPoolThreshold,
2291   jmm_GetPoolCollectionUsage,
2292   jmm_GetGCExtAttributeInfo,
2293   jmm_GetLastGCStat,
2294   jmm_GetThreadCpuTimeWithKind,
2295   jmm_GetThreadCpuTimesWithKind,
2296   jmm_DumpHeap0,
2297   jmm_FindDeadlockedThreads,
2298   jmm_SetVMGlobal,
2299   nullptr,
2300   jmm_DumpThreads,
2301   jmm_SetGCNotificationEnabled,
2302   jmm_GetDiagnosticCommands,
2303   jmm_GetDiagnosticCommandInfo,
2304   jmm_GetDiagnosticCommandArgumentsInfo,
2305   jmm_ExecuteDiagnosticCommand,
2306   jmm_SetDiagnosticFrameworkNotificationEnabled
2307 };
2308 #endif // INCLUDE_MANAGEMENT
2309 
2310 void* Management::get_jmm_interface(int version) {
2311 #if INCLUDE_MANAGEMENT
2312   if (version == JMM_VERSION) {
2313     return (void*) &jmm_interface;
2314   }
2315 #endif // INCLUDE_MANAGEMENT
2316   return nullptr;
2317 }