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