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