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