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