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