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