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