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