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