1 /*
   2  * Copyright (c) 2003, 2026, 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         assert(dump_result.t_list()->includes(jt), "Must be protected");
1150         dump_result.add_thread_snapshot(jt);
1151       }
1152     }
1153   } else {
1154     // obtain thread dump with the specific list of threads with stack trace
1155     do_thread_dump(&dump_result,
1156                    ids_ah,
1157                    num_threads,
1158                    maxDepth,
1159                    false, /* no locked monitor */
1160                    false, /* no locked synchronizers */
1161                    CHECK_0);
1162   }
1163 
1164   int num_snapshots = dump_result.num_snapshots();
1165   assert(num_snapshots == num_threads, "Must match the number of thread snapshots");
1166   assert(num_snapshots == 0 || dump_result.t_list_has_been_set(), "ThreadsList must have been set if we have a snapshot");
1167   int index = 0;
1168   for (ThreadSnapshot* ts = dump_result.snapshots(); ts != nullptr; index++, ts = ts->next()) {
1169     // For each thread, create an java/lang/management/ThreadInfo object
1170     // and fill with the thread information
1171 
1172     if (!is_platform_thread(ts)) {
1173       // if the thread does not exist, has terminated, or is a virtual thread, then set threadinfo to null
1174       infoArray_h->obj_at_put(index, nullptr);
1175       continue;
1176     }
1177 
1178     // Create java.lang.management.ThreadInfo object
1179     instanceOop info_obj = Management::create_thread_info_instance(ts, CHECK_0);
1180     infoArray_h->obj_at_put(index, info_obj);
1181   }
1182   return 0;
1183 JVM_END
1184 
1185 // Dump thread info for the specified threads.
1186 // It returns an array of ThreadInfo objects. Each element is the ThreadInfo
1187 // for the thread ID specified in the corresponding entry in
1188 // the given array of thread IDs; or null if the thread does not exist
1189 // or has terminated.
1190 //
1191 // Input parameter:
1192 //    ids - array of thread IDs; null indicates all live threads
1193 //    locked_monitors - if true, dump locked object monitors
1194 //    locked_synchronizers - if true, dump locked JSR-166 synchronizers
1195 //
1196 JVM_ENTRY(jobjectArray, jmm_DumpThreads(JNIEnv *env, jlongArray thread_ids, jboolean locked_monitors,
1197                                         jboolean locked_synchronizers, jint maxDepth))
1198   ResourceMark rm(THREAD);
1199 
1200   typeArrayOop ta = typeArrayOop(JNIHandles::resolve(thread_ids));
1201   int num_threads = (ta != nullptr ? ta->length() : 0);
1202   typeArrayHandle ids_ah(THREAD, ta);
1203 
1204   ThreadDumpResult dump_result(num_threads);  // can safepoint
1205 
1206   if (ids_ah() != nullptr) {
1207 
1208     // validate the thread id array
1209     validate_thread_id_array(ids_ah, CHECK_NULL);
1210 
1211     // obtain thread dump of a specific list of threads
1212     do_thread_dump(&dump_result,
1213                    ids_ah,
1214                    num_threads,
1215                    maxDepth, /* stack depth */
1216                    (locked_monitors ? true : false),      /* with locked monitors */
1217                    (locked_synchronizers ? true : false), /* with locked synchronizers */
1218                    CHECK_NULL);
1219   } else {
1220     // obtain thread dump of all threads
1221     VM_ThreadDump op(&dump_result,
1222                      maxDepth, /* stack depth */
1223                      (locked_monitors ? true : false),     /* with locked monitors */
1224                      (locked_synchronizers ? true : false) /* with locked synchronizers */);
1225     VMThread::execute(&op);
1226   }
1227 
1228   int num_snapshots = dump_result.num_snapshots();
1229   assert(num_snapshots == 0 || dump_result.t_list_has_been_set(), "ThreadsList must have been set if we have a snapshot");
1230 
1231   // create the result ThreadInfo[] object
1232   InstanceKlass* ik = Management::java_lang_management_ThreadInfo_klass(CHECK_NULL);
1233   objArrayOop r = oopFactory::new_objArray(ik, num_snapshots, CHECK_NULL);
1234   objArrayHandle result_h(THREAD, r);
1235 
1236   int index = 0;
1237   for (ThreadSnapshot* ts = dump_result.snapshots(); ts != nullptr; ts = ts->next(), index++) {
1238     if (!is_platform_thread(ts)) {
1239       // if the thread does not exist, has terminated, or is a virtual thread, then set threadinfo to null
1240       result_h->obj_at_put(index, nullptr);
1241       continue;
1242     }
1243 
1244     ThreadStackTrace* stacktrace = ts->get_stack_trace();
1245     assert(stacktrace != nullptr, "Must have a stack trace dumped");
1246 
1247     // Create Object[] filled with locked monitors
1248     // Create int[] filled with the stack depth where a monitor was locked
1249     int num_frames = stacktrace->get_stack_depth();
1250     int num_locked_monitors = stacktrace->num_jni_locked_monitors();
1251 
1252     // Count the total number of locked monitors
1253     for (int i = 0; i < num_frames; i++) {
1254       StackFrameInfo* frame = stacktrace->stack_frame_at(i);
1255       num_locked_monitors += frame->num_locked_monitors();
1256     }
1257 
1258     objArrayHandle monitors_array;
1259     typeArrayHandle depths_array;
1260     objArrayHandle synchronizers_array;
1261 
1262     if (locked_monitors) {
1263       // Constructs Object[] and int[] to contain the object monitor and the stack depth
1264       // where the thread locked it
1265       objArrayOop array = oopFactory::new_objArray(vmClasses::Object_klass(), num_locked_monitors, CHECK_NULL);
1266       objArrayHandle mh(THREAD, array);
1267       monitors_array = mh;
1268 
1269       typeArrayOop tarray = oopFactory::new_typeArray(T_INT, num_locked_monitors, CHECK_NULL);
1270       typeArrayHandle dh(THREAD, tarray);
1271       depths_array = dh;
1272 
1273       int count = 0;
1274       int j = 0;
1275       for (int depth = 0; depth < num_frames; depth++) {
1276         StackFrameInfo* frame = stacktrace->stack_frame_at(depth);
1277         int len = frame->num_locked_monitors();
1278         GrowableArray<OopHandle>* locked_monitors = frame->locked_monitors();
1279         for (j = 0; j < len; j++) {
1280           oop monitor = locked_monitors->at(j).resolve();
1281           assert(monitor != nullptr, "must be a Java object");
1282           monitors_array->obj_at_put(count, monitor);
1283           depths_array->int_at_put(count, depth);
1284           count++;
1285         }
1286       }
1287 
1288       GrowableArray<OopHandle>* jni_locked_monitors = stacktrace->jni_locked_monitors();
1289       for (j = 0; j < jni_locked_monitors->length(); j++) {
1290         oop object = jni_locked_monitors->at(j).resolve();
1291         assert(object != nullptr, "must be a Java object");
1292         monitors_array->obj_at_put(count, object);
1293         // Monitor locked via JNI MonitorEnter call doesn't have stack depth info
1294         depths_array->int_at_put(count, -1);
1295         count++;
1296       }
1297       assert(count == num_locked_monitors, "number of locked monitors doesn't match");
1298     }
1299 
1300     if (locked_synchronizers) {
1301       // Create Object[] filled with locked JSR-166 synchronizers
1302       assert(ts->threadObj() != nullptr, "Must be a valid JavaThread");
1303       ThreadConcurrentLocks* tcl = ts->get_concurrent_locks();
1304       GrowableArray<OopHandle>* locks = (tcl != nullptr ? tcl->owned_locks() : nullptr);
1305       int num_locked_synchronizers = (locks != nullptr ? locks->length() : 0);
1306 
1307       objArrayOop array = oopFactory::new_objArray(vmClasses::Object_klass(), num_locked_synchronizers, CHECK_NULL);
1308       objArrayHandle sh(THREAD, array);
1309       synchronizers_array = sh;
1310 
1311       for (int k = 0; k < num_locked_synchronizers; k++) {
1312         synchronizers_array->obj_at_put(k, locks->at(k).resolve());
1313       }
1314     }
1315 
1316     // Create java.lang.management.ThreadInfo object
1317     instanceOop info_obj = Management::create_thread_info_instance(ts,
1318                                                                    monitors_array,
1319                                                                    depths_array,
1320                                                                    synchronizers_array,
1321                                                                    CHECK_NULL);
1322     result_h->obj_at_put(index, info_obj);
1323   }
1324 
1325   return (jobjectArray) JNIHandles::make_local(THREAD, result_h());
1326 JVM_END
1327 
1328 // Reset statistic.  Return true if the requested statistic is reset.
1329 // Otherwise, return false.
1330 //
1331 // Input parameters:
1332 //  obj  - specify which instance the statistic associated with to be reset
1333 //         For PEAK_POOL_USAGE stat, obj is required to be a memory pool object.
1334 //         For THREAD_CONTENTION_COUNT and TIME stat, obj is required to be a thread ID.
1335 //  type - the type of statistic to be reset
1336 //
1337 JVM_ENTRY(jboolean, jmm_ResetStatistic(JNIEnv *env, jvalue obj, jmmStatisticType type))
1338   ResourceMark rm(THREAD);
1339 
1340   switch (type) {
1341     case JMM_STAT_PEAK_THREAD_COUNT:
1342       ThreadService::reset_peak_thread_count();
1343       return true;
1344 
1345     case JMM_STAT_THREAD_CONTENTION_COUNT:
1346     case JMM_STAT_THREAD_CONTENTION_TIME: {
1347       jlong tid = obj.j;
1348       if (tid < 0) {
1349         THROW_(vmSymbols::java_lang_IllegalArgumentException(), JNI_FALSE);
1350       }
1351 
1352       // Look for the JavaThread of this given tid
1353       JavaThreadIteratorWithHandle jtiwh;
1354       if (tid == 0) {
1355         // reset contention statistics for all threads if tid == 0
1356         for (; JavaThread *java_thread = jtiwh.next(); ) {
1357           if (type == JMM_STAT_THREAD_CONTENTION_COUNT) {
1358             ThreadService::reset_contention_count_stat(java_thread);
1359           } else {
1360             ThreadService::reset_contention_time_stat(java_thread);
1361           }
1362         }
1363       } else {
1364         // reset contention statistics for a given thread
1365         JavaThread* java_thread = jtiwh.list()->find_JavaThread_from_java_tid(tid);
1366         if (java_thread == nullptr) {
1367           return false;
1368         }
1369 
1370         if (type == JMM_STAT_THREAD_CONTENTION_COUNT) {
1371           ThreadService::reset_contention_count_stat(java_thread);
1372         } else {
1373           ThreadService::reset_contention_time_stat(java_thread);
1374         }
1375       }
1376       return true;
1377       break;
1378     }
1379     case JMM_STAT_PEAK_POOL_USAGE: {
1380       jobject o = obj.l;
1381       if (o == nullptr) {
1382         THROW_(vmSymbols::java_lang_NullPointerException(), JNI_FALSE);
1383       }
1384 
1385       oop pool_obj = JNIHandles::resolve(o);
1386       assert(pool_obj->is_instance(), "Should be an instanceOop");
1387       instanceHandle ph(THREAD, (instanceOop) pool_obj);
1388 
1389       MemoryPool* pool = MemoryService::get_memory_pool(ph);
1390       if (pool != nullptr) {
1391         pool->reset_peak_memory_usage();
1392         return true;
1393       }
1394       break;
1395     }
1396     case JMM_STAT_GC_STAT: {
1397       jobject o = obj.l;
1398       if (o == nullptr) {
1399         THROW_(vmSymbols::java_lang_NullPointerException(), JNI_FALSE);
1400       }
1401 
1402       GCMemoryManager* mgr = get_gc_memory_manager_from_jobject(o, CHECK_false);
1403       if (mgr != nullptr) {
1404         mgr->reset_gc_stat();
1405         return true;
1406       }
1407       break;
1408     }
1409     default:
1410       assert(0, "Unknown Statistic Type");
1411   }
1412   return false;
1413 JVM_END
1414 
1415 // Returns the fast estimate of CPU time consumed by
1416 // a given thread (in nanoseconds).
1417 // If thread_id == 0, return CPU time for the current thread.
1418 JVM_ENTRY(jlong, jmm_GetThreadCpuTime(JNIEnv *env, jlong thread_id))
1419   if (!os::is_thread_cpu_time_supported()) {
1420     return -1;
1421   }
1422 
1423   if (thread_id < 0) {
1424     THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
1425                "Invalid thread ID", -1);
1426   }
1427 
1428   JavaThread* java_thread = nullptr;
1429   if (thread_id == 0) {
1430     // current thread
1431     return os::current_thread_cpu_time();
1432   } else {
1433     ThreadsListHandle tlh;
1434     java_thread = tlh.list()->find_JavaThread_from_java_tid(thread_id);
1435     if (is_platform_thread(java_thread)) {
1436       return os::thread_cpu_time((Thread*) java_thread);
1437     }
1438   }
1439   return -1;
1440 JVM_END
1441 
1442 // Returns a String array of all VM global flag names
1443 JVM_ENTRY(jobjectArray, jmm_GetVMGlobalNames(JNIEnv *env))
1444   // last flag entry is always null, so subtract 1
1445   int nFlags = (int) JVMFlag::numFlags - 1;
1446   // allocate a temp array
1447   objArrayOop r = oopFactory::new_objArray(vmClasses::String_klass(),
1448                                            nFlags, CHECK_NULL);
1449   objArrayHandle flags_ah(THREAD, r);
1450   int num_entries = 0;
1451   for (int i = 0; i < nFlags; i++) {
1452     JVMFlag* flag = &JVMFlag::flags[i];
1453     // Exclude develop flags in product builds.
1454     if (flag->is_constant_in_binary()) {
1455       continue;
1456     }
1457     // Exclude the locked (experimental, diagnostic) flags
1458     if (flag->is_unlocked() || flag->is_unlocker()) {
1459       Handle s = java_lang_String::create_from_str(flag->name(), CHECK_NULL);
1460       flags_ah->obj_at_put(num_entries, s());
1461       num_entries++;
1462     }
1463   }
1464 
1465   if (num_entries < nFlags) {
1466     // Return array of right length
1467     objArrayOop res = oopFactory::new_objArray(vmClasses::String_klass(), num_entries, CHECK_NULL);
1468     for(int i = 0; i < num_entries; i++) {
1469       res->obj_at_put(i, flags_ah->obj_at(i));
1470     }
1471     return (jobjectArray)JNIHandles::make_local(THREAD, res);
1472   }
1473 
1474   return (jobjectArray)JNIHandles::make_local(THREAD, flags_ah());
1475 JVM_END
1476 
1477 // Utility function used by jmm_GetVMGlobals.  Returns false if flag type
1478 // can't be determined, true otherwise.  If false is returned, then *global
1479 // will be incomplete and invalid.
1480 static bool add_global_entry(Handle name, jmmVMGlobal *global, JVMFlag *flag, TRAPS) {
1481   Handle flag_name;
1482   if (name() == nullptr) {
1483     flag_name = java_lang_String::create_from_str(flag->name(), CHECK_false);
1484   } else {
1485     flag_name = name;
1486   }
1487   global->name = (jstring)JNIHandles::make_local(THREAD, flag_name());
1488 
1489   if (flag->is_bool()) {
1490     global->value.z = flag->get_bool() ? JNI_TRUE : JNI_FALSE;
1491     global->type = JMM_VMGLOBAL_TYPE_JBOOLEAN;
1492   } else if (flag->is_int()) {
1493     global->value.j = (jlong)flag->get_int();
1494     global->type = JMM_VMGLOBAL_TYPE_JLONG;
1495   } else if (flag->is_uint()) {
1496     global->value.j = (jlong)flag->get_uint();
1497     global->type = JMM_VMGLOBAL_TYPE_JLONG;
1498   } else if (flag->is_intx()) {
1499     global->value.j = (jlong)flag->get_intx();
1500     global->type = JMM_VMGLOBAL_TYPE_JLONG;
1501   } else if (flag->is_uintx()) {
1502     global->value.j = (jlong)flag->get_uintx();
1503     global->type = JMM_VMGLOBAL_TYPE_JLONG;
1504   } else if (flag->is_uint64_t()) {
1505     global->value.j = (jlong)flag->get_uint64_t();
1506     global->type = JMM_VMGLOBAL_TYPE_JLONG;
1507   } else if (flag->is_double()) {
1508     global->value.d = (jdouble)flag->get_double();
1509     global->type = JMM_VMGLOBAL_TYPE_JDOUBLE;
1510   } else if (flag->is_size_t()) {
1511     global->value.j = (jlong)flag->get_size_t();
1512     global->type = JMM_VMGLOBAL_TYPE_JLONG;
1513   } else if (flag->is_ccstr()) {
1514     Handle str = java_lang_String::create_from_str(flag->get_ccstr(), CHECK_false);
1515     global->value.l = (jobject)JNIHandles::make_local(THREAD, str());
1516     global->type = JMM_VMGLOBAL_TYPE_JSTRING;
1517   } else {
1518     global->type = JMM_VMGLOBAL_TYPE_UNKNOWN;
1519     return false;
1520   }
1521 
1522   global->writeable = flag->is_writeable();
1523   global->external = flag->is_external();
1524   switch (flag->get_origin()) {
1525     case JVMFlagOrigin::DEFAULT:
1526       global->origin = JMM_VMGLOBAL_ORIGIN_DEFAULT;
1527       break;
1528     case JVMFlagOrigin::COMMAND_LINE:
1529       global->origin = JMM_VMGLOBAL_ORIGIN_COMMAND_LINE;
1530       break;
1531     case JVMFlagOrigin::ENVIRON_VAR:
1532       global->origin = JMM_VMGLOBAL_ORIGIN_ENVIRON_VAR;
1533       break;
1534     case JVMFlagOrigin::CONFIG_FILE:
1535       global->origin = JMM_VMGLOBAL_ORIGIN_CONFIG_FILE;
1536       break;
1537     case JVMFlagOrigin::MANAGEMENT:
1538       global->origin = JMM_VMGLOBAL_ORIGIN_MANAGEMENT;
1539       break;
1540     case JVMFlagOrigin::ERGONOMIC:
1541       global->origin = JMM_VMGLOBAL_ORIGIN_ERGONOMIC;
1542       break;
1543     case JVMFlagOrigin::ATTACH_ON_DEMAND:
1544       global->origin = JMM_VMGLOBAL_ORIGIN_ATTACH_ON_DEMAND;
1545       break;
1546     default:
1547       global->origin = JMM_VMGLOBAL_ORIGIN_OTHER;
1548   }
1549 
1550   return true;
1551 }
1552 
1553 // Fill globals array of count length with jmmVMGlobal entries
1554 // specified by names. If names == null, fill globals array
1555 // with all Flags. Return value is number of entries
1556 // created in globals.
1557 // If a JVMFlag with a given name in an array element does not
1558 // exist, globals[i].name will be set to null.
1559 JVM_ENTRY(jint, jmm_GetVMGlobals(JNIEnv *env,
1560                                  jobjectArray names,
1561                                  jmmVMGlobal *globals,
1562                                  jint count))
1563 
1564 
1565   if (globals == nullptr) {
1566     THROW_(vmSymbols::java_lang_NullPointerException(), 0);
1567   }
1568 
1569   ResourceMark rm(THREAD);
1570 
1571   if (names != nullptr) {
1572     // return the requested globals
1573     objArrayOop ta = objArrayOop(JNIHandles::resolve_non_null(names));
1574     objArrayHandle names_ah(THREAD, ta);
1575     // Make sure we have a String array
1576     Klass* element_klass = ObjArrayKlass::cast(names_ah->klass())->element_klass();
1577     if (element_klass != vmClasses::String_klass()) {
1578       THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
1579                  "Array element type is not String class", 0);
1580     }
1581 
1582     int names_length = names_ah->length();
1583     int num_entries = 0;
1584     for (int i = 0; i < names_length && i < count; i++) {
1585       oop s = names_ah->obj_at(i);
1586       if (s == nullptr) {
1587         THROW_(vmSymbols::java_lang_NullPointerException(), 0);
1588       }
1589 
1590       Handle sh(THREAD, s);
1591       char* str = java_lang_String::as_utf8_string(s);
1592       JVMFlag* flag = JVMFlag::find_flag(str);
1593       if (flag != nullptr &&
1594           add_global_entry(sh, &globals[i], flag, THREAD)) {
1595         num_entries++;
1596       } else {
1597         globals[i].name = nullptr;
1598       }
1599     }
1600     return num_entries;
1601   } else {
1602     // return all globals if names == null
1603 
1604     // last flag entry is always null, so subtract 1
1605     int nFlags = (int) JVMFlag::numFlags - 1;
1606     Handle null_h;
1607     int num_entries = 0;
1608     for (int i = 0; i < nFlags && num_entries < count;  i++) {
1609       JVMFlag* flag = &JVMFlag::flags[i];
1610       // Exclude develop flags in product builds.
1611       if (flag->is_constant_in_binary()) {
1612         continue;
1613       }
1614       // Exclude the locked (diagnostic, experimental) flags
1615       if ((flag->is_unlocked() || flag->is_unlocker()) &&
1616           add_global_entry(null_h, &globals[num_entries], flag, THREAD)) {
1617         num_entries++;
1618       }
1619     }
1620     return num_entries;
1621   }
1622 JVM_END
1623 
1624 JVM_ENTRY(void, jmm_SetVMGlobal(JNIEnv *env, jstring flag_name, jvalue new_value))
1625   ResourceMark rm(THREAD);
1626 
1627   oop fn = JNIHandles::resolve_external_guard(flag_name);
1628   if (fn == nullptr) {
1629     THROW_MSG(vmSymbols::java_lang_NullPointerException(),
1630               "The flag name cannot be null.");
1631   }
1632   char* name = java_lang_String::as_utf8_string(fn);
1633 
1634   FormatBuffer<80> error_msg("%s", "");
1635   int succeed = WriteableFlags::set_flag(name, new_value, JVMFlagOrigin::MANAGEMENT, error_msg);
1636 
1637   if (succeed != JVMFlag::SUCCESS) {
1638     if (succeed == JVMFlag::MISSING_VALUE) {
1639       // missing value causes NPE to be thrown
1640       THROW(vmSymbols::java_lang_NullPointerException());
1641     } else {
1642       // all the other errors are reported as IAE with the appropriate error message
1643       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
1644                 error_msg.buffer());
1645     }
1646   }
1647   assert(succeed == JVMFlag::SUCCESS, "Setting flag should succeed");
1648 JVM_END
1649 
1650 class ThreadTimesClosure: public ThreadClosure {
1651  private:
1652   objArrayHandle _names_strings;
1653   char **_names_chars;
1654   typeArrayHandle _times;
1655   int _names_len;
1656   int _times_len;
1657   int _count;
1658 
1659  public:
1660   ThreadTimesClosure(objArrayHandle names, typeArrayHandle times);
1661   ~ThreadTimesClosure();
1662   virtual void do_thread(Thread* thread);
1663   void do_unlocked(TRAPS);
1664   int count() { return _count; }
1665 };
1666 
1667 ThreadTimesClosure::ThreadTimesClosure(objArrayHandle names,
1668                                        typeArrayHandle times) {
1669   assert(names() != nullptr, "names was null");
1670   assert(times() != nullptr, "times was null");
1671   _names_strings = names;
1672   _names_len = names->length();
1673   _names_chars = NEW_C_HEAP_ARRAY(char*, _names_len, mtInternal);
1674   _times = times;
1675   _times_len = times->length();
1676   _count = 0;
1677 }
1678 
1679 //
1680 // Called with Threads_lock held
1681 //
1682 void ThreadTimesClosure::do_thread(Thread* thread) {
1683   assert(Threads_lock->owned_by_self(), "Must hold Threads_lock");
1684   assert(thread != nullptr, "thread was null");
1685 
1686   // exclude externally visible JavaThreads
1687   if (thread->is_Java_thread() && !thread->is_hidden_from_external_view()) {
1688     return;
1689   }
1690 
1691   if (_count >= _names_len || _count >= _times_len) {
1692     // skip if the result array is not big enough
1693     return;
1694   }
1695 
1696   ResourceMark rm; // thread->name() uses ResourceArea
1697 
1698   assert(thread->name() != nullptr, "All threads should have a name");
1699   _names_chars[_count] = os::strdup_check_oom(thread->name());
1700   _times->long_at_put(_count, os::is_thread_cpu_time_supported() ?
1701                         os::thread_cpu_time(thread) : -1);
1702   _count++;
1703 }
1704 
1705 // Called without Threads_lock, we can allocate String objects.
1706 void ThreadTimesClosure::do_unlocked(TRAPS) {
1707 
1708   for (int i = 0; i < _count; i++) {
1709     Handle s = java_lang_String::create_from_str(_names_chars[i],  CHECK);
1710     _names_strings->obj_at_put(i, s());
1711   }
1712 }
1713 
1714 ThreadTimesClosure::~ThreadTimesClosure() {
1715   for (int i = 0; i < _count; i++) {
1716     os::free(_names_chars[i]);
1717   }
1718   FREE_C_HEAP_ARRAY(char *, _names_chars);
1719 }
1720 
1721 // Fills names with VM internal thread names and times with the corresponding
1722 // CPU times.  If names or times is null, a NullPointerException is thrown.
1723 // If the element type of names is not String, an IllegalArgumentException is
1724 // thrown.
1725 // If an array is not large enough to hold all the entries, only the entries
1726 // that fit will be returned.  Return value is the number of VM internal
1727 // threads entries.
1728 JVM_ENTRY(jint, jmm_GetInternalThreadTimes(JNIEnv *env,
1729                                            jobjectArray names,
1730                                            jlongArray times))
1731   if (names == nullptr || times == nullptr) {
1732      THROW_(vmSymbols::java_lang_NullPointerException(), 0);
1733   }
1734   objArrayOop na = objArrayOop(JNIHandles::resolve_non_null(names));
1735   objArrayHandle names_ah(THREAD, na);
1736 
1737   // Make sure we have a String array
1738   Klass* element_klass = ObjArrayKlass::cast(names_ah->klass())->element_klass();
1739   if (element_klass != vmClasses::String_klass()) {
1740     THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
1741                "Array element type is not String class", 0);
1742   }
1743 
1744   typeArrayOop ta = typeArrayOop(JNIHandles::resolve_non_null(times));
1745   typeArrayHandle times_ah(THREAD, ta);
1746 
1747   ThreadTimesClosure ttc(names_ah, times_ah);
1748   {
1749     MutexLocker ml(THREAD, Threads_lock);
1750     Threads::threads_do(&ttc);
1751   }
1752   ttc.do_unlocked(THREAD);
1753   return ttc.count();
1754 JVM_END
1755 
1756 static Handle find_deadlocks(bool object_monitors_only, TRAPS) {
1757   ResourceMark rm(THREAD);
1758 
1759   VM_FindDeadlocks op(!object_monitors_only /* also check concurrent locks? */);
1760   VMThread::execute(&op);
1761 
1762   DeadlockCycle* deadlocks = op.result();
1763   if (deadlocks == nullptr) {
1764     // no deadlock found and return
1765     return Handle();
1766   }
1767 
1768   int num_threads = 0;
1769   DeadlockCycle* cycle;
1770   for (cycle = deadlocks; cycle != nullptr; cycle = cycle->next()) {
1771     num_threads += cycle->num_threads();
1772   }
1773 
1774   objArrayOop r = oopFactory::new_objArray(vmClasses::Thread_klass(), num_threads, CHECK_NH);
1775   objArrayHandle threads_ah(THREAD, r);
1776 
1777   int index = 0;
1778   for (cycle = deadlocks; cycle != nullptr; cycle = cycle->next()) {
1779     GrowableArray<JavaThread*>* deadlock_threads = cycle->threads();
1780     int len = deadlock_threads->length();
1781     for (int i = 0; i < len; i++) {
1782       threads_ah->obj_at_put(index, deadlock_threads->at(i)->threadObj());
1783       index++;
1784     }
1785   }
1786   return threads_ah;
1787 }
1788 
1789 // Finds cycles of threads that are deadlocked involved in object monitors
1790 // and JSR-166 synchronizers.
1791 // Returns an array of Thread objects which are in deadlock, if any.
1792 // Otherwise, returns null.
1793 //
1794 // Input parameter:
1795 //    object_monitors_only - if true, only check object monitors
1796 //
1797 JVM_ENTRY(jobjectArray, jmm_FindDeadlockedThreads(JNIEnv *env, jboolean object_monitors_only))
1798   Handle result = find_deadlocks(object_monitors_only != 0, CHECK_NULL);
1799   return (jobjectArray) JNIHandles::make_local(THREAD, result());
1800 JVM_END
1801 
1802 // Finds cycles of threads that are deadlocked on monitor locks
1803 // Returns an array of Thread objects which are in deadlock, if any.
1804 // Otherwise, returns null.
1805 JVM_ENTRY(jobjectArray, jmm_FindMonitorDeadlockedThreads(JNIEnv *env))
1806   Handle result = find_deadlocks(true, CHECK_NULL);
1807   return (jobjectArray) JNIHandles::make_local(THREAD, result());
1808 JVM_END
1809 
1810 // Gets the information about GC extension attributes including
1811 // the name of the attribute, its type, and a short description.
1812 //
1813 // Input parameters:
1814 //   mgr   - GC memory manager
1815 //   info  - caller allocated array of jmmExtAttributeInfo
1816 //   count - number of elements of the info array
1817 //
1818 // Returns the number of GC extension attributes filled in the info array; or
1819 // -1 if info is not big enough
1820 //
1821 JVM_ENTRY(jint, jmm_GetGCExtAttributeInfo(JNIEnv *env, jobject mgr, jmmExtAttributeInfo* info, jint count))
1822   // All GC memory managers have 1 attribute (number of GC threads)
1823   if (count == 0) {
1824     return 0;
1825   }
1826 
1827   if (info == nullptr) {
1828    THROW_(vmSymbols::java_lang_NullPointerException(), 0);
1829   }
1830 
1831   info[0].name = "GcThreadCount";
1832   info[0].type = 'I';
1833   info[0].description = "Number of GC threads";
1834   return 1;
1835 JVM_END
1836 
1837 // verify the given array is an array of java/lang/management/MemoryUsage objects
1838 // of a given length and return the objArrayOop
1839 static objArrayOop get_memory_usage_objArray(jobjectArray array, int length, TRAPS) {
1840   if (array == nullptr) {
1841     THROW_NULL(vmSymbols::java_lang_NullPointerException());
1842   }
1843 
1844   objArrayOop oa = objArrayOop(JNIHandles::resolve_non_null(array));
1845   objArrayHandle array_h(THREAD, oa);
1846 
1847   // array must be of the given length
1848   if (length != array_h->length()) {
1849     THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(),
1850                    "The length of the given MemoryUsage array does not match the number of memory pools.");
1851   }
1852 
1853   // check if the element of array is of type MemoryUsage class
1854   Klass* usage_klass = Management::java_lang_management_MemoryUsage_klass(CHECK_NULL);
1855   Klass* element_klass = ObjArrayKlass::cast(array_h->klass())->element_klass();
1856   if (element_klass != usage_klass) {
1857     THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(),
1858                    "The element type is not MemoryUsage class");
1859   }
1860 
1861   return array_h();
1862 }
1863 
1864 // Gets the statistics of the last GC of a given GC memory manager.
1865 // Input parameters:
1866 //   obj     - GarbageCollectorMXBean object
1867 //   gc_stat - caller allocated jmmGCStat where:
1868 //     a. before_gc_usage - array of MemoryUsage objects
1869 //     b. after_gc_usage  - array of MemoryUsage objects
1870 //     c. gc_ext_attributes_values_size is set to the
1871 //        gc_ext_attribute_values array allocated
1872 //     d. gc_ext_attribute_values is a caller allocated array of jvalue.
1873 //
1874 // On return,
1875 //   gc_index == 0 indicates no GC statistics available
1876 //
1877 //   before_gc_usage and after_gc_usage - filled with per memory pool
1878 //      before and after GC usage in the same order as the memory pools
1879 //      returned by GetMemoryPools for a given GC memory manager.
1880 //   num_gc_ext_attributes indicates the number of elements in
1881 //      the gc_ext_attribute_values array is filled; or
1882 //      -1 if the gc_ext_attributes_values array is not big enough
1883 //
1884 JVM_ENTRY(void, jmm_GetLastGCStat(JNIEnv *env, jobject obj, jmmGCStat *gc_stat))
1885   ResourceMark rm(THREAD);
1886 
1887   if (gc_stat->gc_ext_attribute_values_size > 0 && gc_stat->gc_ext_attribute_values == nullptr) {
1888     THROW(vmSymbols::java_lang_NullPointerException());
1889   }
1890 
1891   // Get the GCMemoryManager
1892   GCMemoryManager* mgr = get_gc_memory_manager_from_jobject(obj, CHECK);
1893 
1894   // Make a copy of the last GC statistics
1895   // GC may occur while constructing the last GC information
1896   int num_pools = MemoryService::num_memory_pools();
1897   GCStatInfo stat(num_pools);
1898   if (mgr->get_last_gc_stat(&stat) == 0) {
1899     gc_stat->gc_index = 0;
1900     return;
1901   }
1902 
1903   gc_stat->gc_index = stat.gc_index();
1904   gc_stat->start_time = Management::ticks_to_ms(stat.start_time());
1905   gc_stat->end_time = Management::ticks_to_ms(stat.end_time());
1906 
1907   // Current implementation does not have GC extension attributes
1908   gc_stat->num_gc_ext_attributes = 0;
1909 
1910   // Fill the arrays of MemoryUsage objects with before and after GC
1911   // per pool memory usage
1912   objArrayOop bu = get_memory_usage_objArray(gc_stat->usage_before_gc,
1913                                              num_pools,
1914                                              CHECK);
1915   objArrayHandle usage_before_gc_ah(THREAD, bu);
1916 
1917   objArrayOop au = get_memory_usage_objArray(gc_stat->usage_after_gc,
1918                                              num_pools,
1919                                              CHECK);
1920   objArrayHandle usage_after_gc_ah(THREAD, au);
1921 
1922   for (int i = 0; i < num_pools; i++) {
1923     Handle before_usage = MemoryService::create_MemoryUsage_obj(stat.before_gc_usage_for_pool(i), CHECK);
1924     Handle after_usage;
1925 
1926     MemoryUsage u = stat.after_gc_usage_for_pool(i);
1927     if (u.max_size() == 0 && u.used() > 0) {
1928       // If max size == 0, this pool is a survivor space.
1929       // Set max size = -1 since the pools will be swapped after GC.
1930       MemoryUsage usage(u.init_size(), u.used(), u.committed(), MemoryUsage::undefined_size());
1931       after_usage = MemoryService::create_MemoryUsage_obj(usage, CHECK);
1932     } else {
1933       after_usage = MemoryService::create_MemoryUsage_obj(stat.after_gc_usage_for_pool(i), CHECK);
1934     }
1935     usage_before_gc_ah->obj_at_put(i, before_usage());
1936     usage_after_gc_ah->obj_at_put(i, after_usage());
1937   }
1938 
1939   if (gc_stat->gc_ext_attribute_values_size > 0) {
1940     // Current implementation only has 1 attribute (number of GC threads)
1941     // The type is 'I'
1942     gc_stat->gc_ext_attribute_values[0].i = mgr->num_gc_threads();
1943   }
1944 JVM_END
1945 
1946 JVM_ENTRY(void, jmm_SetGCNotificationEnabled(JNIEnv *env, jobject obj, jboolean enabled))
1947   ResourceMark rm(THREAD);
1948   // Get the GCMemoryManager
1949   GCMemoryManager* mgr = get_gc_memory_manager_from_jobject(obj, CHECK);
1950   mgr->set_notification_enabled(enabled?true:false);
1951 JVM_END
1952 
1953 // Dump heap - Returns 0 if succeeds.
1954 JVM_ENTRY(jint, jmm_DumpHeap0(JNIEnv *env, jstring outputfile, jboolean live))
1955 #if INCLUDE_SERVICES
1956   ResourceMark rm(THREAD);
1957   oop on = JNIHandles::resolve_external_guard(outputfile);
1958   if (on == nullptr) {
1959     THROW_MSG_(vmSymbols::java_lang_NullPointerException(),
1960                "Output file name cannot be null.", -1);
1961   }
1962   Handle onhandle(THREAD, on);
1963   char* name = java_lang_String::as_platform_dependent_str(onhandle, CHECK_(-1));
1964   if (name == nullptr) {
1965     THROW_MSG_(vmSymbols::java_lang_NullPointerException(),
1966                "Output file name cannot be null.", -1);
1967   }
1968   HeapDumper dumper(live ? true : false);
1969   if (dumper.dump(name) != 0) {
1970     const char* errmsg = dumper.error_as_C_string();
1971     THROW_MSG_(vmSymbols::java_io_IOException(), errmsg, -1);
1972   }
1973   return 0;
1974 #else  // INCLUDE_SERVICES
1975   return -1;
1976 #endif // INCLUDE_SERVICES
1977 JVM_END
1978 
1979 JVM_ENTRY(jobjectArray, jmm_GetDiagnosticCommands(JNIEnv *env))
1980   ResourceMark rm(THREAD);
1981   GrowableArray<const char *>* dcmd_list = DCmdFactory::DCmd_list(DCmd_Source_MBean);
1982   objArrayOop cmd_array_oop = oopFactory::new_objArray(vmClasses::String_klass(),
1983           dcmd_list->length(), CHECK_NULL);
1984   objArrayHandle cmd_array(THREAD, cmd_array_oop);
1985   for (int i = 0; i < dcmd_list->length(); i++) {
1986     oop cmd_name = java_lang_String::create_oop_from_str(dcmd_list->at(i), CHECK_NULL);
1987     cmd_array->obj_at_put(i, cmd_name);
1988   }
1989   return (jobjectArray) JNIHandles::make_local(THREAD, cmd_array());
1990 JVM_END
1991 
1992 JVM_ENTRY(void, jmm_GetDiagnosticCommandInfo(JNIEnv *env, jobjectArray cmds,
1993           dcmdInfo* infoArray))
1994   if (cmds == nullptr || infoArray == nullptr) {
1995     THROW(vmSymbols::java_lang_NullPointerException());
1996   }
1997 
1998   ResourceMark rm(THREAD);
1999 
2000   objArrayOop ca = objArrayOop(JNIHandles::resolve_non_null(cmds));
2001   objArrayHandle cmds_ah(THREAD, ca);
2002 
2003   // Make sure we have a String array
2004   Klass* element_klass = ObjArrayKlass::cast(cmds_ah->klass())->element_klass();
2005   if (element_klass != vmClasses::String_klass()) {
2006     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
2007                "Array element type is not String class");
2008   }
2009 
2010   GrowableArray<DCmdInfo *>* info_list = DCmdFactory::DCmdInfo_list(DCmd_Source_MBean);
2011 
2012   int num_cmds = cmds_ah->length();
2013   for (int i = 0; i < num_cmds; i++) {
2014     oop cmd = cmds_ah->obj_at(i);
2015     if (cmd == nullptr) {
2016         THROW_MSG(vmSymbols::java_lang_NullPointerException(),
2017                 "Command name cannot be null.");
2018     }
2019     char* cmd_name = java_lang_String::as_utf8_string(cmd);
2020     if (cmd_name == nullptr) {
2021         THROW_MSG(vmSymbols::java_lang_NullPointerException(),
2022                 "Command name cannot be null.");
2023     }
2024     int pos = info_list->find_if([&](DCmdInfo* info) {
2025       return info->name_equals(cmd_name);
2026     });
2027     if (pos == -1) {
2028         THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
2029              "Unknown diagnostic command");
2030     }
2031     DCmdInfo* info = info_list->at(pos);
2032     infoArray[i].name = info->name();
2033     infoArray[i].description = info->description();
2034     infoArray[i].impact = info->impact();
2035     infoArray[i].num_arguments = info->num_arguments();
2036 
2037     // All registered DCmds are always enabled. We set the dcmdInfo::enabled
2038     // field to true to be compatible with the Java API
2039     // com.sun.management.internal.DiagnosticCommandInfo.
2040     infoArray[i].enabled = true;
2041   }
2042 JVM_END
2043 
2044 JVM_ENTRY(void, jmm_GetDiagnosticCommandArgumentsInfo(JNIEnv *env,
2045           jstring command, dcmdArgInfo* infoArray, jint count))
2046   ResourceMark rm(THREAD);
2047   oop cmd = JNIHandles::resolve_external_guard(command);
2048   if (cmd == nullptr) {
2049     THROW_MSG(vmSymbols::java_lang_NullPointerException(),
2050               "Command line cannot be null.");
2051   }
2052   char* cmd_name = java_lang_String::as_utf8_string(cmd);
2053   if (cmd_name == nullptr) {
2054     THROW_MSG(vmSymbols::java_lang_NullPointerException(),
2055               "Command line content cannot be null.");
2056   }
2057   DCmd* dcmd = nullptr;
2058   DCmdFactory*factory = DCmdFactory::factory(DCmd_Source_MBean, cmd_name,
2059                                              strlen(cmd_name));
2060   if (factory != nullptr) {
2061     dcmd = factory->create_resource_instance(nullptr);
2062   }
2063   if (dcmd == nullptr) {
2064     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
2065               "Unknown diagnostic command");
2066   }
2067   DCmdMark mark(dcmd);
2068   GrowableArray<DCmdArgumentInfo*>* array = dcmd->argument_info_array();
2069   const int num_args = array->length();
2070   if (num_args != count) {
2071     assert(false, "jmm_GetDiagnosticCommandArgumentsInfo count mismatch (%d vs %d)", count, num_args);
2072     THROW_MSG(vmSymbols::java_lang_InternalError(), "jmm_GetDiagnosticCommandArgumentsInfo count mismatch");
2073   }
2074   for (int i = 0; i < num_args; i++) {
2075     infoArray[i].name = array->at(i)->name();
2076     infoArray[i].description = array->at(i)->description();
2077     infoArray[i].type = array->at(i)->type();
2078     infoArray[i].default_string = array->at(i)->default_string();
2079     infoArray[i].mandatory = array->at(i)->is_mandatory();
2080     infoArray[i].option = array->at(i)->is_option();
2081     infoArray[i].multiple = array->at(i)->is_multiple();
2082     infoArray[i].position = array->at(i)->position();
2083   }
2084   return;
2085 JVM_END
2086 
2087 JVM_ENTRY(jstring, jmm_ExecuteDiagnosticCommand(JNIEnv *env, jstring commandline))
2088   ResourceMark rm(THREAD);
2089   oop cmd = JNIHandles::resolve_external_guard(commandline);
2090   if (cmd == nullptr) {
2091     THROW_MSG_NULL(vmSymbols::java_lang_NullPointerException(),
2092                    "Command line cannot be null.");
2093   }
2094   char* cmdline = java_lang_String::as_utf8_string(cmd);
2095   if (cmdline == nullptr) {
2096     THROW_MSG_NULL(vmSymbols::java_lang_NullPointerException(),
2097                    "Command line content cannot be null.");
2098   }
2099   bufferedStream output;
2100   DCmd::parse_and_execute(DCmd_Source_MBean, &output, cmdline, ' ', CHECK_NULL);
2101   oop result = java_lang_String::create_oop_from_str(output.as_string(), CHECK_NULL);
2102   return (jstring) JNIHandles::make_local(THREAD, result);
2103 JVM_END
2104 
2105 JVM_ENTRY(void, jmm_SetDiagnosticFrameworkNotificationEnabled(JNIEnv *env, jboolean enabled))
2106   DCmdFactory::set_jmx_notification_enabled(enabled?true:false);
2107 JVM_END
2108 
2109 jlong Management::ticks_to_ms(jlong ticks) {
2110   assert(os::elapsed_frequency() > 0, "Must be non-zero");
2111   return (jlong)(((double)ticks / (double)os::elapsed_frequency())
2112                  * (double)1000.0);
2113 }
2114 
2115 // Gets the amount of memory allocated on the Java heap since JVM launch.
2116 JVM_ENTRY(jlong, jmm_GetTotalThreadAllocatedMemory(JNIEnv *env))
2117     // A thread increments exited_allocated_bytes in ThreadService::remove_thread
2118     // only after it removes itself from the threads list, and once a TLH is
2119     // created, no thread it references can remove itself from the threads
2120     // list, so none can update exited_allocated_bytes. We therefore initialize
2121     // result with exited_allocated_bytes after after we create the TLH so that
2122     // the final result can only be short due to (1) threads that start after
2123     // the TLH is created, or (2) terminating threads that escape TLH creation
2124     // and don't update exited_allocated_bytes before we initialize result.
2125 
2126     // We keep a high water mark to ensure monotonicity in case threads counted
2127     // on a previous call end up in state (2).
2128     static uint64_t high_water_result = 0;
2129 
2130     JavaThreadIteratorWithHandle jtiwh;
2131     uint64_t result = ThreadService::exited_allocated_bytes();
2132     for (; JavaThread* thread = jtiwh.next();) {
2133       uint64_t size = thread->cooked_allocated_bytes();
2134       result += size;
2135     }
2136 
2137     {
2138       assert(MonitoringSupport_lock != nullptr, "Must be");
2139       MutexLocker ml(MonitoringSupport_lock, Mutex::_no_safepoint_check_flag);
2140       if (result < high_water_result) {
2141         // Encountered (2) above, or result wrapped to a negative value. In
2142         // the latter case, it's pegged at the last positive value.
2143         result = high_water_result;
2144       } else {
2145         high_water_result = result;
2146       }
2147     }
2148     return checked_cast<jlong>(result);
2149 JVM_END
2150 
2151 // Gets the amount of memory allocated on the Java heap for a single thread.
2152 // Returns -1 if the thread does not exist or has terminated.
2153 JVM_ENTRY(jlong, jmm_GetOneThreadAllocatedMemory(JNIEnv *env, jlong thread_id))
2154   if (thread_id < 0) {
2155     THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
2156                "Invalid thread ID", -1);
2157   }
2158 
2159   if (thread_id == 0) { // current thread
2160     return checked_cast<jlong>(thread->cooked_allocated_bytes());
2161   }
2162 
2163   ThreadsListHandle tlh;
2164   JavaThread* java_thread = tlh.list()->find_JavaThread_from_java_tid(thread_id);
2165   if (is_platform_thread(java_thread)) {
2166     return checked_cast<jlong>(java_thread->cooked_allocated_bytes());
2167   }
2168   return -1;
2169 JVM_END
2170 
2171 // Gets an array containing the amount of memory allocated on the Java
2172 // heap for a set of threads (in bytes).  Each element of the array is
2173 // the amount of memory allocated for the thread ID specified in the
2174 // corresponding entry in the given array of thread IDs; or -1 if the
2175 // thread does not exist or has terminated.
2176 JVM_ENTRY(void, jmm_GetThreadAllocatedMemory(JNIEnv *env, jlongArray ids,
2177                                              jlongArray sizeArray))
2178   // Check if threads is null
2179   if (ids == nullptr || sizeArray == nullptr) {
2180     THROW(vmSymbols::java_lang_NullPointerException());
2181   }
2182 
2183   ResourceMark rm(THREAD);
2184   typeArrayOop ta = typeArrayOop(JNIHandles::resolve_non_null(ids));
2185   typeArrayHandle ids_ah(THREAD, ta);
2186 
2187   typeArrayOop sa = typeArrayOop(JNIHandles::resolve_non_null(sizeArray));
2188   typeArrayHandle sizeArray_h(THREAD, sa);
2189 
2190   // validate the thread id array
2191   validate_thread_id_array(ids_ah, CHECK);
2192 
2193   // sizeArray must be of the same length as the given array of thread IDs
2194   int num_threads = ids_ah->length();
2195   if (num_threads != sizeArray_h->length()) {
2196     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
2197               "The length of the given long array does not match the length of "
2198               "the given array of thread IDs");
2199   }
2200 
2201   ThreadsListHandle tlh;
2202   for (int i = 0; i < num_threads; i++) {
2203     JavaThread* java_thread = tlh.list()->find_JavaThread_from_java_tid(ids_ah->long_at(i));
2204     if (is_platform_thread(java_thread)) {
2205       sizeArray_h->long_at_put(i, java_thread->cooked_allocated_bytes());
2206     }
2207   }
2208 JVM_END
2209 
2210 // Returns the CPU time consumed by a given thread (in nanoseconds).
2211 // If thread_id == 0, CPU time for the current thread is returned.
2212 // If user_sys_cpu_time = true, user level and system CPU time of
2213 // a given thread is returned; otherwise, only user level CPU time
2214 // is returned.
2215 JVM_ENTRY(jlong, jmm_GetThreadCpuTimeWithKind(JNIEnv *env, jlong thread_id, jboolean user_sys_cpu_time))
2216   if (!os::is_thread_cpu_time_supported()) {
2217     return -1;
2218   }
2219 
2220   if (thread_id < 0) {
2221     THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
2222                "Invalid thread ID", -1);
2223   }
2224 
2225   JavaThread* java_thread = nullptr;
2226   if (thread_id == 0) {
2227     // current thread
2228     return os::current_thread_cpu_time(user_sys_cpu_time != 0);
2229   } else {
2230     ThreadsListHandle tlh;
2231     java_thread = tlh.list()->find_JavaThread_from_java_tid(thread_id);
2232     if (is_platform_thread(java_thread)) {
2233       return os::thread_cpu_time((Thread*) java_thread, user_sys_cpu_time != 0);
2234     }
2235   }
2236   return -1;
2237 JVM_END
2238 
2239 // Gets an array containing the CPU times consumed by a set of threads
2240 // (in nanoseconds).  Each element of the array is the CPU time for the
2241 // thread ID specified in the corresponding entry in the given array
2242 // of thread IDs; or -1 if the thread does not exist or has terminated.
2243 // If user_sys_cpu_time = true, the sum of user level and system CPU time
2244 // for the given thread is returned; otherwise, only user level CPU time
2245 // is returned.
2246 JVM_ENTRY(void, jmm_GetThreadCpuTimesWithKind(JNIEnv *env, jlongArray ids,
2247                                               jlongArray timeArray,
2248                                               jboolean user_sys_cpu_time))
2249   // Check if threads is null
2250   if (ids == nullptr || timeArray == nullptr) {
2251     THROW(vmSymbols::java_lang_NullPointerException());
2252   }
2253 
2254   ResourceMark rm(THREAD);
2255   typeArrayOop ta = typeArrayOop(JNIHandles::resolve_non_null(ids));
2256   typeArrayHandle ids_ah(THREAD, ta);
2257 
2258   typeArrayOop tia = typeArrayOop(JNIHandles::resolve_non_null(timeArray));
2259   typeArrayHandle timeArray_h(THREAD, tia);
2260 
2261   // validate the thread id array
2262   validate_thread_id_array(ids_ah, CHECK);
2263 
2264   // timeArray must be of the same length as the given array of thread IDs
2265   int num_threads = ids_ah->length();
2266   if (num_threads != timeArray_h->length()) {
2267     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
2268               "The length of the given long array does not match the length of "
2269               "the given array of thread IDs");
2270   }
2271 
2272   ThreadsListHandle tlh;
2273   for (int i = 0; i < num_threads; i++) {
2274     JavaThread* java_thread = tlh.list()->find_JavaThread_from_java_tid(ids_ah->long_at(i));
2275     if (is_platform_thread(java_thread)) {
2276       timeArray_h->long_at_put(i, os::thread_cpu_time((Thread*)java_thread,
2277                                                       user_sys_cpu_time != 0));
2278     }
2279   }
2280 JVM_END
2281 
2282 const struct jmmInterface_1_ jmm_interface = {
2283   nullptr,
2284   nullptr,
2285   jmm_GetVersion,
2286   jmm_GetOptionalSupport,
2287   jmm_GetThreadInfo,
2288   jmm_GetMemoryPools,
2289   jmm_GetMemoryManagers,
2290   jmm_GetMemoryPoolUsage,
2291   jmm_GetPeakMemoryPoolUsage,
2292   jmm_GetTotalThreadAllocatedMemory,
2293   jmm_GetOneThreadAllocatedMemory,
2294   jmm_GetThreadAllocatedMemory,
2295   jmm_GetMemoryUsage,
2296   jmm_GetLongAttribute,
2297   jmm_GetBoolAttribute,
2298   jmm_SetBoolAttribute,
2299   jmm_GetLongAttributes,
2300   jmm_FindMonitorDeadlockedThreads,
2301   jmm_GetThreadCpuTime,
2302   jmm_GetVMGlobalNames,
2303   jmm_GetVMGlobals,
2304   jmm_GetInternalThreadTimes,
2305   jmm_ResetStatistic,
2306   jmm_SetPoolSensor,
2307   jmm_SetPoolThreshold,
2308   jmm_GetPoolCollectionUsage,
2309   jmm_GetGCExtAttributeInfo,
2310   jmm_GetLastGCStat,
2311   jmm_GetThreadCpuTimeWithKind,
2312   jmm_GetThreadCpuTimesWithKind,
2313   jmm_DumpHeap0,
2314   jmm_FindDeadlockedThreads,
2315   jmm_SetVMGlobal,
2316   nullptr,
2317   jmm_DumpThreads,
2318   jmm_SetGCNotificationEnabled,
2319   jmm_GetDiagnosticCommands,
2320   jmm_GetDiagnosticCommandInfo,
2321   jmm_GetDiagnosticCommandArgumentsInfo,
2322   jmm_ExecuteDiagnosticCommand,
2323   jmm_SetDiagnosticFrameworkNotificationEnabled
2324 };
2325 #endif // INCLUDE_MANAGEMENT
2326 
2327 void* Management::get_jmm_interface(int version) {
2328 #if INCLUDE_MANAGEMENT
2329   if (version == JMM_VERSION) {
2330     return (void*) &jmm_interface;
2331   }
2332 #endif // INCLUDE_MANAGEMENT
2333   return nullptr;
2334 }