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