src/share/vm/services/management.cpp

Thu, 12 May 2011 10:30:11 -0700

author
fparain
date
Thu, 12 May 2011 10:30:11 -0700
changeset 2888
78542e2b5e35
parent 2574
02f78cfa4656
child 3329
3b688d6ff3d0
permissions
-rw-r--r--

7036199: Adding a notification to the implementation of GarbageCollectorMXBeans
Summary: Add a notification to the GarbageCollectorMXBeans
Reviewed-by: acorn, mchung

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

mercurial