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