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