Path: blob/aarch64-shenandoah-jdk8u272-b10/hotspot/src/share/vm/services/management.cpp
32285 views
/*1* Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324#include "precompiled.hpp"25#include "classfile/systemDictionary.hpp"26#include "compiler/compileBroker.hpp"27#include "memory/iterator.hpp"28#include "memory/oopFactory.hpp"29#include "memory/resourceArea.hpp"30#include "oops/klass.hpp"31#include "oops/objArrayKlass.hpp"32#include "oops/oop.inline.hpp"33#include "runtime/arguments.hpp"34#include "runtime/globals.hpp"35#include "runtime/handles.inline.hpp"36#include "runtime/interfaceSupport.hpp"37#include "runtime/javaCalls.hpp"38#include "runtime/jniHandles.hpp"39#include "runtime/os.hpp"40#include "runtime/serviceThread.hpp"41#include "runtime/thread.inline.hpp"42#include "services/classLoadingService.hpp"43#include "services/diagnosticCommand.hpp"44#include "services/diagnosticFramework.hpp"45#include "services/heapDumper.hpp"46#include "services/jmm.h"47#include "services/lowMemoryDetector.hpp"48#include "services/gcNotifier.hpp"49#include "services/nmtDCmd.hpp"50#include "services/management.hpp"51#include "services/memoryManager.hpp"52#include "services/memoryPool.hpp"53#include "services/memoryService.hpp"54#include "services/runtimeService.hpp"55#include "services/threadService.hpp"56#include "utilities/macros.hpp"5758PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC5960PerfVariable* Management::_begin_vm_creation_time = NULL;61PerfVariable* Management::_end_vm_creation_time = NULL;62PerfVariable* Management::_vm_init_done_time = NULL;6364Klass* Management::_sensor_klass = NULL;65Klass* Management::_threadInfo_klass = NULL;66Klass* Management::_memoryUsage_klass = NULL;67Klass* Management::_memoryPoolMXBean_klass = NULL;68Klass* Management::_memoryManagerMXBean_klass = NULL;69Klass* Management::_garbageCollectorMXBean_klass = NULL;70Klass* Management::_managementFactory_klass = NULL;71Klass* Management::_garbageCollectorImpl_klass = NULL;72Klass* Management::_gcInfo_klass = NULL;73Klass* Management::_diagnosticCommandImpl_klass = NULL;74Klass* Management::_managementFactoryHelper_klass = NULL;757677jmmOptionalSupport Management::_optional_support = {0};78TimeStamp Management::_stamp;7980void management_init() {81#if INCLUDE_MANAGEMENT82Management::init();83ThreadService::init();84RuntimeService::init();85ClassLoadingService::init();86#else87ThreadService::init();88// Make sure the VM version is initialized89// This is normally called by RuntimeService::init().90// Since that is conditionalized out, we need to call it here.91Abstract_VM_Version::initialize();92#endif // INCLUDE_MANAGEMENT93}9495#if INCLUDE_MANAGEMENT9697void Management::init() {98EXCEPTION_MARK;99100// These counters are for java.lang.management API support.101// They are created even if -XX:-UsePerfData is set and in102// that case, they will be allocated on C heap.103104_begin_vm_creation_time =105PerfDataManager::create_variable(SUN_RT, "createVmBeginTime",106PerfData::U_None, CHECK);107108_end_vm_creation_time =109PerfDataManager::create_variable(SUN_RT, "createVmEndTime",110PerfData::U_None, CHECK);111112_vm_init_done_time =113PerfDataManager::create_variable(SUN_RT, "vmInitDoneTime",114PerfData::U_None, CHECK);115116// Initialize optional support117_optional_support.isLowMemoryDetectionSupported = 1;118_optional_support.isCompilationTimeMonitoringSupported = 1;119_optional_support.isThreadContentionMonitoringSupported = 1;120121if (os::is_thread_cpu_time_supported()) {122_optional_support.isCurrentThreadCpuTimeSupported = 1;123_optional_support.isOtherThreadCpuTimeSupported = 1;124} else {125_optional_support.isCurrentThreadCpuTimeSupported = 0;126_optional_support.isOtherThreadCpuTimeSupported = 0;127}128129_optional_support.isBootClassPathSupported = 1;130_optional_support.isObjectMonitorUsageSupported = 1;131#if INCLUDE_SERVICES132// This depends on the heap inspector133_optional_support.isSynchronizerUsageSupported = 1;134#endif // INCLUDE_SERVICES135_optional_support.isThreadAllocatedMemorySupported = 1;136_optional_support.isRemoteDiagnosticCommandsSupported = 1;137138// Registration of the diagnostic commands139DCmdRegistrant::register_dcmds();140DCmdRegistrant::register_dcmds_ext();141uint32_t full_export = DCmd_Source_Internal | DCmd_Source_AttachAPI142| DCmd_Source_MBean;143DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<NMTDCmd>(full_export, true, false));144}145146void Management::initialize(TRAPS) {147// Start the service thread148ServiceThread::initialize();149150if (ManagementServer) {151ResourceMark rm(THREAD);152HandleMark hm(THREAD);153154// Load and initialize the sun.management.Agent class155// invoke startAgent method to start the management server156Handle loader = Handle(THREAD, SystemDictionary::java_system_loader());157Klass* k = SystemDictionary::resolve_or_null(vmSymbols::sun_management_Agent(),158loader,159Handle(),160THREAD);161if (k == NULL) {162vm_exit_during_initialization("Management agent initialization failure: "163"class sun.management.Agent not found.");164}165instanceKlassHandle ik (THREAD, k);166167JavaValue result(T_VOID);168JavaCalls::call_static(&result,169ik,170vmSymbols::startAgent_name(),171vmSymbols::void_method_signature(),172CHECK);173}174}175176void Management::get_optional_support(jmmOptionalSupport* support) {177memcpy(support, &_optional_support, sizeof(jmmOptionalSupport));178}179180Klass* Management::load_and_initialize_klass(Symbol* sh, TRAPS) {181Klass* k = SystemDictionary::resolve_or_fail(sh, true, CHECK_NULL);182instanceKlassHandle ik (THREAD, k);183if (ik->should_be_initialized()) {184ik->initialize(CHECK_NULL);185}186// If these classes change to not be owned by the boot loader, they need187// to be walked to keep their class loader alive in oops_do.188assert(ik->class_loader() == NULL, "need to follow in oops_do");189return ik();190}191192void Management::record_vm_startup_time(jlong begin, jlong duration) {193// if the performance counter is not initialized,194// then vm initialization failed; simply return.195if (_begin_vm_creation_time == NULL) return;196197_begin_vm_creation_time->set_value(begin);198_end_vm_creation_time->set_value(begin + duration);199PerfMemory::set_accessible(true);200}201202jlong Management::timestamp() {203TimeStamp t;204t.update();205return t.ticks() - _stamp.ticks();206}207208void Management::oops_do(OopClosure* f) {209MemoryService::oops_do(f);210ThreadService::oops_do(f);211}212213Klass* Management::java_lang_management_ThreadInfo_klass(TRAPS) {214if (_threadInfo_klass == NULL) {215_threadInfo_klass = load_and_initialize_klass(vmSymbols::java_lang_management_ThreadInfo(), CHECK_NULL);216}217return _threadInfo_klass;218}219220Klass* Management::java_lang_management_MemoryUsage_klass(TRAPS) {221if (_memoryUsage_klass == NULL) {222_memoryUsage_klass = load_and_initialize_klass(vmSymbols::java_lang_management_MemoryUsage(), CHECK_NULL);223}224return _memoryUsage_klass;225}226227Klass* Management::java_lang_management_MemoryPoolMXBean_klass(TRAPS) {228if (_memoryPoolMXBean_klass == NULL) {229_memoryPoolMXBean_klass = load_and_initialize_klass(vmSymbols::java_lang_management_MemoryPoolMXBean(), CHECK_NULL);230}231return _memoryPoolMXBean_klass;232}233234Klass* Management::java_lang_management_MemoryManagerMXBean_klass(TRAPS) {235if (_memoryManagerMXBean_klass == NULL) {236_memoryManagerMXBean_klass = load_and_initialize_klass(vmSymbols::java_lang_management_MemoryManagerMXBean(), CHECK_NULL);237}238return _memoryManagerMXBean_klass;239}240241Klass* Management::java_lang_management_GarbageCollectorMXBean_klass(TRAPS) {242if (_garbageCollectorMXBean_klass == NULL) {243_garbageCollectorMXBean_klass = load_and_initialize_klass(vmSymbols::java_lang_management_GarbageCollectorMXBean(), CHECK_NULL);244}245return _garbageCollectorMXBean_klass;246}247248Klass* Management::sun_management_Sensor_klass(TRAPS) {249if (_sensor_klass == NULL) {250_sensor_klass = load_and_initialize_klass(vmSymbols::sun_management_Sensor(), CHECK_NULL);251}252return _sensor_klass;253}254255Klass* Management::sun_management_ManagementFactory_klass(TRAPS) {256if (_managementFactory_klass == NULL) {257_managementFactory_klass = load_and_initialize_klass(vmSymbols::sun_management_ManagementFactory(), CHECK_NULL);258}259return _managementFactory_klass;260}261262Klass* Management::sun_management_GarbageCollectorImpl_klass(TRAPS) {263if (_garbageCollectorImpl_klass == NULL) {264_garbageCollectorImpl_klass = load_and_initialize_klass(vmSymbols::sun_management_GarbageCollectorImpl(), CHECK_NULL);265}266return _garbageCollectorImpl_klass;267}268269Klass* Management::com_sun_management_GcInfo_klass(TRAPS) {270if (_gcInfo_klass == NULL) {271_gcInfo_klass = load_and_initialize_klass(vmSymbols::com_sun_management_GcInfo(), CHECK_NULL);272}273return _gcInfo_klass;274}275276Klass* Management::sun_management_DiagnosticCommandImpl_klass(TRAPS) {277if (_diagnosticCommandImpl_klass == NULL) {278_diagnosticCommandImpl_klass = load_and_initialize_klass(vmSymbols::sun_management_DiagnosticCommandImpl(), CHECK_NULL);279}280return _diagnosticCommandImpl_klass;281}282283Klass* Management::sun_management_ManagementFactoryHelper_klass(TRAPS) {284if (_managementFactoryHelper_klass == NULL) {285_managementFactoryHelper_klass = load_and_initialize_klass(vmSymbols::sun_management_ManagementFactoryHelper(), CHECK_NULL);286}287return _managementFactoryHelper_klass;288}289290static void initialize_ThreadInfo_constructor_arguments(JavaCallArguments* args, ThreadSnapshot* snapshot, TRAPS) {291Handle snapshot_thread(THREAD, snapshot->threadObj());292293jlong contended_time;294jlong waited_time;295if (ThreadService::is_thread_monitoring_contention()) {296contended_time = Management::ticks_to_ms(snapshot->contended_enter_ticks());297waited_time = Management::ticks_to_ms(snapshot->monitor_wait_ticks() + snapshot->sleep_ticks());298} else {299// set them to -1 if thread contention monitoring is disabled.300contended_time = max_julong;301waited_time = max_julong;302}303304int thread_status = snapshot->thread_status();305assert((thread_status & JMM_THREAD_STATE_FLAG_MASK) == 0, "Flags already set in thread_status in Thread object");306if (snapshot->is_ext_suspended()) {307thread_status |= JMM_THREAD_STATE_FLAG_SUSPENDED;308}309if (snapshot->is_in_native()) {310thread_status |= JMM_THREAD_STATE_FLAG_NATIVE;311}312313ThreadStackTrace* st = snapshot->get_stack_trace();314Handle stacktrace_h;315if (st != NULL) {316stacktrace_h = st->allocate_fill_stack_trace_element_array(CHECK);317} else {318stacktrace_h = Handle();319}320321args->push_oop(snapshot_thread);322args->push_int(thread_status);323args->push_oop(Handle(THREAD, snapshot->blocker_object()));324args->push_oop(Handle(THREAD, snapshot->blocker_object_owner()));325args->push_long(snapshot->contended_enter_count());326args->push_long(contended_time);327args->push_long(snapshot->monitor_wait_count() + snapshot->sleep_count());328args->push_long(waited_time);329args->push_oop(stacktrace_h);330}331332// Helper function to construct a ThreadInfo object333instanceOop Management::create_thread_info_instance(ThreadSnapshot* snapshot, TRAPS) {334Klass* k = Management::java_lang_management_ThreadInfo_klass(CHECK_NULL);335instanceKlassHandle ik (THREAD, k);336337JavaValue result(T_VOID);338JavaCallArguments args(14);339340// First allocate a ThreadObj object and341// push the receiver as the first argument342Handle element = ik->allocate_instance_handle(CHECK_NULL);343args.push_oop(element);344345// initialize the arguments for the ThreadInfo constructor346initialize_ThreadInfo_constructor_arguments(&args, snapshot, CHECK_NULL);347348// Call ThreadInfo constructor with no locked monitors and synchronizers349JavaCalls::call_special(&result,350ik,351vmSymbols::object_initializer_name(),352vmSymbols::java_lang_management_ThreadInfo_constructor_signature(),353&args,354CHECK_NULL);355356return (instanceOop) element();357}358359instanceOop Management::create_thread_info_instance(ThreadSnapshot* snapshot,360objArrayHandle monitors_array,361typeArrayHandle depths_array,362objArrayHandle synchronizers_array,363TRAPS) {364Klass* k = Management::java_lang_management_ThreadInfo_klass(CHECK_NULL);365instanceKlassHandle ik (THREAD, k);366367JavaValue result(T_VOID);368JavaCallArguments args(17);369370// First allocate a ThreadObj object and371// push the receiver as the first argument372Handle element = ik->allocate_instance_handle(CHECK_NULL);373args.push_oop(element);374375// initialize the arguments for the ThreadInfo constructor376initialize_ThreadInfo_constructor_arguments(&args, snapshot, CHECK_NULL);377378// push the locked monitors and synchronizers in the arguments379args.push_oop(monitors_array);380args.push_oop(depths_array);381args.push_oop(synchronizers_array);382383// Call ThreadInfo constructor with locked monitors and synchronizers384JavaCalls::call_special(&result,385ik,386vmSymbols::object_initializer_name(),387vmSymbols::java_lang_management_ThreadInfo_with_locks_constructor_signature(),388&args,389CHECK_NULL);390391return (instanceOop) element();392}393394395static GCMemoryManager* get_gc_memory_manager_from_jobject(jobject mgr, TRAPS) {396if (mgr == NULL) {397THROW_(vmSymbols::java_lang_NullPointerException(), NULL);398}399oop mgr_obj = JNIHandles::resolve(mgr);400instanceHandle h(THREAD, (instanceOop) mgr_obj);401402Klass* k = Management::java_lang_management_GarbageCollectorMXBean_klass(CHECK_NULL);403if (!h->is_a(k)) {404THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),405"the object is not an instance of java.lang.management.GarbageCollectorMXBean class",406NULL);407}408409MemoryManager* gc = MemoryService::get_memory_manager(h);410if (gc == NULL || !gc->is_gc_memory_manager()) {411THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),412"Invalid GC memory manager",413NULL);414}415return (GCMemoryManager*) gc;416}417418static MemoryPool* get_memory_pool_from_jobject(jobject obj, TRAPS) {419if (obj == NULL) {420THROW_(vmSymbols::java_lang_NullPointerException(), NULL);421}422423oop pool_obj = JNIHandles::resolve(obj);424assert(pool_obj->is_instance(), "Should be an instanceOop");425instanceHandle ph(THREAD, (instanceOop) pool_obj);426427return MemoryService::get_memory_pool(ph);428}429430#endif // INCLUDE_MANAGEMENT431432static void validate_thread_id_array(typeArrayHandle ids_ah, TRAPS) {433int num_threads = ids_ah->length();434435// Validate input thread IDs436int i = 0;437for (i = 0; i < num_threads; i++) {438jlong tid = ids_ah->long_at(i);439if (tid <= 0) {440// throw exception if invalid thread id.441THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),442"Invalid thread ID entry");443}444}445}446447#if INCLUDE_MANAGEMENT448449static void validate_thread_info_array(objArrayHandle infoArray_h, TRAPS) {450// check if the element of infoArray is of type ThreadInfo class451Klass* threadinfo_klass = Management::java_lang_management_ThreadInfo_klass(CHECK);452Klass* element_klass = ObjArrayKlass::cast(infoArray_h->klass())->element_klass();453if (element_klass != threadinfo_klass) {454THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),455"infoArray element type is not ThreadInfo class");456}457}458459460static MemoryManager* get_memory_manager_from_jobject(jobject obj, TRAPS) {461if (obj == NULL) {462THROW_(vmSymbols::java_lang_NullPointerException(), NULL);463}464465oop mgr_obj = JNIHandles::resolve(obj);466assert(mgr_obj->is_instance(), "Should be an instanceOop");467instanceHandle mh(THREAD, (instanceOop) mgr_obj);468469return MemoryService::get_memory_manager(mh);470}471472// Returns a version string and sets major and minor version if473// the input parameters are non-null.474JVM_LEAF(jint, jmm_GetVersion(JNIEnv *env))475return JMM_VERSION;476JVM_END477478// Gets the list of VM monitoring and management optional supports479// Returns 0 if succeeded; otherwise returns non-zero.480JVM_LEAF(jint, jmm_GetOptionalSupport(JNIEnv *env, jmmOptionalSupport* support))481if (support == NULL) {482return -1;483}484Management::get_optional_support(support);485return 0;486JVM_END487488// Returns a java.lang.String object containing the input arguments to the VM.489JVM_ENTRY(jobject, jmm_GetInputArguments(JNIEnv *env))490ResourceMark rm(THREAD);491492if (Arguments::num_jvm_args() == 0 && Arguments::num_jvm_flags() == 0) {493return NULL;494}495496char** vm_flags = Arguments::jvm_flags_array();497char** vm_args = Arguments::jvm_args_array();498int num_flags = Arguments::num_jvm_flags();499int num_args = Arguments::num_jvm_args();500501size_t length = 1; // null terminator502int i;503for (i = 0; i < num_flags; i++) {504length += strlen(vm_flags[i]);505}506for (i = 0; i < num_args; i++) {507length += strlen(vm_args[i]);508}509// add a space between each argument510length += num_flags + num_args - 1;511512// Return the list of input arguments passed to the VM513// and preserve the order that the VM processes.514char* args = NEW_RESOURCE_ARRAY(char, length);515args[0] = '\0';516// concatenate all jvm_flags517if (num_flags > 0) {518strcat(args, vm_flags[0]);519for (i = 1; i < num_flags; i++) {520strcat(args, " ");521strcat(args, vm_flags[i]);522}523}524525if (num_args > 0 && num_flags > 0) {526// append a space if args already contains one or more jvm_flags527strcat(args, " ");528}529530// concatenate all jvm_args531if (num_args > 0) {532strcat(args, vm_args[0]);533for (i = 1; i < num_args; i++) {534strcat(args, " ");535strcat(args, vm_args[i]);536}537}538539Handle hargs = java_lang_String::create_from_platform_dependent_str(args, CHECK_NULL);540return JNIHandles::make_local(env, hargs());541JVM_END542543// Returns an array of java.lang.String object containing the input arguments to the VM.544JVM_ENTRY(jobjectArray, jmm_GetInputArgumentArray(JNIEnv *env))545ResourceMark rm(THREAD);546547if (Arguments::num_jvm_args() == 0 && Arguments::num_jvm_flags() == 0) {548return NULL;549}550551char** vm_flags = Arguments::jvm_flags_array();552char** vm_args = Arguments::jvm_args_array();553int num_flags = Arguments::num_jvm_flags();554int num_args = Arguments::num_jvm_args();555556instanceKlassHandle ik (THREAD, SystemDictionary::String_klass());557objArrayOop r = oopFactory::new_objArray(ik(), num_args + num_flags, CHECK_NULL);558objArrayHandle result_h(THREAD, r);559560int index = 0;561for (int j = 0; j < num_flags; j++, index++) {562Handle h = java_lang_String::create_from_platform_dependent_str(vm_flags[j], CHECK_NULL);563result_h->obj_at_put(index, h());564}565for (int i = 0; i < num_args; i++, index++) {566Handle h = java_lang_String::create_from_platform_dependent_str(vm_args[i], CHECK_NULL);567result_h->obj_at_put(index, h());568}569return (jobjectArray) JNIHandles::make_local(env, result_h());570JVM_END571572// Returns an array of java/lang/management/MemoryPoolMXBean object573// one for each memory pool if obj == null; otherwise returns574// an array of memory pools for a given memory manager if575// it is a valid memory manager.576JVM_ENTRY(jobjectArray, jmm_GetMemoryPools(JNIEnv* env, jobject obj))577ResourceMark rm(THREAD);578579int num_memory_pools;580MemoryManager* mgr = NULL;581if (obj == NULL) {582num_memory_pools = MemoryService::num_memory_pools();583} else {584mgr = get_memory_manager_from_jobject(obj, CHECK_NULL);585if (mgr == NULL) {586return NULL;587}588num_memory_pools = mgr->num_memory_pools();589}590591// Allocate the resulting MemoryPoolMXBean[] object592Klass* k = Management::java_lang_management_MemoryPoolMXBean_klass(CHECK_NULL);593instanceKlassHandle ik (THREAD, k);594objArrayOop r = oopFactory::new_objArray(ik(), num_memory_pools, CHECK_NULL);595objArrayHandle poolArray(THREAD, r);596597if (mgr == NULL) {598// Get all memory pools599for (int i = 0; i < num_memory_pools; i++) {600MemoryPool* pool = MemoryService::get_memory_pool(i);601instanceOop p = pool->get_memory_pool_instance(CHECK_NULL);602instanceHandle ph(THREAD, p);603poolArray->obj_at_put(i, ph());604}605} else {606// Get memory pools managed by a given memory manager607for (int i = 0; i < num_memory_pools; i++) {608MemoryPool* pool = mgr->get_memory_pool(i);609instanceOop p = pool->get_memory_pool_instance(CHECK_NULL);610instanceHandle ph(THREAD, p);611poolArray->obj_at_put(i, ph());612}613}614return (jobjectArray) JNIHandles::make_local(env, poolArray());615JVM_END616617// Returns an array of java/lang/management/MemoryManagerMXBean object618// one for each memory manager if obj == null; otherwise returns619// an array of memory managers for a given memory pool if620// it is a valid memory pool.621JVM_ENTRY(jobjectArray, jmm_GetMemoryManagers(JNIEnv* env, jobject obj))622ResourceMark rm(THREAD);623624int num_mgrs;625MemoryPool* pool = NULL;626if (obj == NULL) {627num_mgrs = MemoryService::num_memory_managers();628} else {629pool = get_memory_pool_from_jobject(obj, CHECK_NULL);630if (pool == NULL) {631return NULL;632}633num_mgrs = pool->num_memory_managers();634}635636// Allocate the resulting MemoryManagerMXBean[] object637Klass* k = Management::java_lang_management_MemoryManagerMXBean_klass(CHECK_NULL);638instanceKlassHandle ik (THREAD, k);639objArrayOop r = oopFactory::new_objArray(ik(), num_mgrs, CHECK_NULL);640objArrayHandle mgrArray(THREAD, r);641642if (pool == NULL) {643// Get all memory managers644for (int i = 0; i < num_mgrs; i++) {645MemoryManager* mgr = MemoryService::get_memory_manager(i);646instanceOop p = mgr->get_memory_manager_instance(CHECK_NULL);647instanceHandle ph(THREAD, p);648mgrArray->obj_at_put(i, ph());649}650} else {651// Get memory managers for a given memory pool652for (int i = 0; i < num_mgrs; i++) {653MemoryManager* mgr = pool->get_memory_manager(i);654instanceOop p = mgr->get_memory_manager_instance(CHECK_NULL);655instanceHandle ph(THREAD, p);656mgrArray->obj_at_put(i, ph());657}658}659return (jobjectArray) JNIHandles::make_local(env, mgrArray());660JVM_END661662663// Returns a java/lang/management/MemoryUsage object containing the memory usage664// of a given memory pool.665JVM_ENTRY(jobject, jmm_GetMemoryPoolUsage(JNIEnv* env, jobject obj))666ResourceMark rm(THREAD);667668MemoryPool* pool = get_memory_pool_from_jobject(obj, CHECK_NULL);669if (pool != NULL) {670MemoryUsage usage = pool->get_memory_usage();671Handle h = MemoryService::create_MemoryUsage_obj(usage, CHECK_NULL);672return JNIHandles::make_local(env, h());673} else {674return NULL;675}676JVM_END677678// Returns a java/lang/management/MemoryUsage object containing the memory usage679// of a given memory pool.680JVM_ENTRY(jobject, jmm_GetPeakMemoryPoolUsage(JNIEnv* env, jobject obj))681ResourceMark rm(THREAD);682683MemoryPool* pool = get_memory_pool_from_jobject(obj, CHECK_NULL);684if (pool != NULL) {685MemoryUsage usage = pool->get_peak_memory_usage();686Handle h = MemoryService::create_MemoryUsage_obj(usage, CHECK_NULL);687return JNIHandles::make_local(env, h());688} else {689return NULL;690}691JVM_END692693// Returns a java/lang/management/MemoryUsage object containing the memory usage694// of a given memory pool after most recent GC.695JVM_ENTRY(jobject, jmm_GetPoolCollectionUsage(JNIEnv* env, jobject obj))696ResourceMark rm(THREAD);697698MemoryPool* pool = get_memory_pool_from_jobject(obj, CHECK_NULL);699if (pool != NULL && pool->is_collected_pool()) {700MemoryUsage usage = pool->get_last_collection_usage();701Handle h = MemoryService::create_MemoryUsage_obj(usage, CHECK_NULL);702return JNIHandles::make_local(env, h());703} else {704return NULL;705}706JVM_END707708// Sets the memory pool sensor for a threshold type709JVM_ENTRY(void, jmm_SetPoolSensor(JNIEnv* env, jobject obj, jmmThresholdType type, jobject sensorObj))710if (obj == NULL || sensorObj == NULL) {711THROW(vmSymbols::java_lang_NullPointerException());712}713714Klass* sensor_klass = Management::sun_management_Sensor_klass(CHECK);715oop s = JNIHandles::resolve(sensorObj);716assert(s->is_instance(), "Sensor should be an instanceOop");717instanceHandle sensor_h(THREAD, (instanceOop) s);718if (!sensor_h->is_a(sensor_klass)) {719THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),720"Sensor is not an instance of sun.management.Sensor class");721}722723MemoryPool* mpool = get_memory_pool_from_jobject(obj, CHECK);724assert(mpool != NULL, "MemoryPool should exist");725726switch (type) {727case JMM_USAGE_THRESHOLD_HIGH:728case JMM_USAGE_THRESHOLD_LOW:729// have only one sensor for threshold high and low730mpool->set_usage_sensor_obj(sensor_h);731break;732case JMM_COLLECTION_USAGE_THRESHOLD_HIGH:733case JMM_COLLECTION_USAGE_THRESHOLD_LOW:734// have only one sensor for threshold high and low735mpool->set_gc_usage_sensor_obj(sensor_h);736break;737default:738assert(false, "Unrecognized type");739}740741JVM_END742743744// Sets the threshold of a given memory pool.745// Returns the previous threshold.746//747// Input parameters:748// pool - the MemoryPoolMXBean object749// type - threshold type750// threshold - the new threshold (must not be negative)751//752JVM_ENTRY(jlong, jmm_SetPoolThreshold(JNIEnv* env, jobject obj, jmmThresholdType type, jlong threshold))753if (threshold < 0) {754THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),755"Invalid threshold value",756-1);757}758759if ((size_t)threshold > max_uintx) {760stringStream st;761st.print("Invalid valid threshold value. Threshold value (" UINT64_FORMAT ") > max value of size_t (" SIZE_FORMAT ")", (size_t)threshold, max_uintx);762THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(), st.as_string(), -1);763}764765MemoryPool* pool = get_memory_pool_from_jobject(obj, CHECK_(0L));766assert(pool != NULL, "MemoryPool should exist");767768jlong prev = 0;769switch (type) {770case JMM_USAGE_THRESHOLD_HIGH:771if (!pool->usage_threshold()->is_high_threshold_supported()) {772return -1;773}774prev = pool->usage_threshold()->set_high_threshold((size_t) threshold);775break;776777case JMM_USAGE_THRESHOLD_LOW:778if (!pool->usage_threshold()->is_low_threshold_supported()) {779return -1;780}781prev = pool->usage_threshold()->set_low_threshold((size_t) threshold);782break;783784case JMM_COLLECTION_USAGE_THRESHOLD_HIGH:785if (!pool->gc_usage_threshold()->is_high_threshold_supported()) {786return -1;787}788// return and the new threshold is effective for the next GC789return pool->gc_usage_threshold()->set_high_threshold((size_t) threshold);790791case JMM_COLLECTION_USAGE_THRESHOLD_LOW:792if (!pool->gc_usage_threshold()->is_low_threshold_supported()) {793return -1;794}795// return and the new threshold is effective for the next GC796return pool->gc_usage_threshold()->set_low_threshold((size_t) threshold);797798default:799assert(false, "Unrecognized type");800return -1;801}802803// When the threshold is changed, reevaluate if the low memory804// detection is enabled.805if (prev != threshold) {806LowMemoryDetector::recompute_enabled_for_collected_pools();807LowMemoryDetector::detect_low_memory(pool);808}809return prev;810JVM_END811812// Returns a java/lang/management/MemoryUsage object representing813// the memory usage for the heap or non-heap memory.814JVM_ENTRY(jobject, jmm_GetMemoryUsage(JNIEnv* env, jboolean heap))815ResourceMark rm(THREAD);816817// Calculate the memory usage818size_t total_init = 0;819size_t total_used = 0;820size_t total_committed = 0;821size_t total_max = 0;822bool has_undefined_init_size = false;823bool has_undefined_max_size = false;824825for (int i = 0; i < MemoryService::num_memory_pools(); i++) {826MemoryPool* pool = MemoryService::get_memory_pool(i);827if ((heap && pool->is_heap()) || (!heap && pool->is_non_heap())) {828MemoryUsage u = pool->get_memory_usage();829total_used += u.used();830total_committed += u.committed();831832if (u.init_size() == (size_t)-1) {833has_undefined_init_size = true;834}835if (!has_undefined_init_size) {836total_init += u.init_size();837}838839if (u.max_size() == (size_t)-1) {840has_undefined_max_size = true;841}842if (!has_undefined_max_size) {843total_max += u.max_size();844}845}846}847848// if any one of the memory pool has undefined init_size or max_size,849// set it to -1850if (has_undefined_init_size) {851total_init = (size_t)-1;852}853if (has_undefined_max_size) {854total_max = (size_t)-1;855}856857MemoryUsage usage((heap ? InitialHeapSize : total_init),858total_used,859total_committed,860(heap ? Universe::heap()->max_capacity() : total_max));861862Handle obj = MemoryService::create_MemoryUsage_obj(usage, CHECK_NULL);863return JNIHandles::make_local(env, obj());864JVM_END865866// Returns the boolean value of a given attribute.867JVM_LEAF(jboolean, jmm_GetBoolAttribute(JNIEnv *env, jmmBoolAttribute att))868switch (att) {869case JMM_VERBOSE_GC:870return MemoryService::get_verbose();871case JMM_VERBOSE_CLASS:872return ClassLoadingService::get_verbose();873case JMM_THREAD_CONTENTION_MONITORING:874return ThreadService::is_thread_monitoring_contention();875case JMM_THREAD_CPU_TIME:876return ThreadService::is_thread_cpu_time_enabled();877case JMM_THREAD_ALLOCATED_MEMORY:878return ThreadService::is_thread_allocated_memory_enabled();879default:880assert(0, "Unrecognized attribute");881return false;882}883JVM_END884885// Sets the given boolean attribute and returns the previous value.886JVM_ENTRY(jboolean, jmm_SetBoolAttribute(JNIEnv *env, jmmBoolAttribute att, jboolean flag))887switch (att) {888case JMM_VERBOSE_GC:889return MemoryService::set_verbose(flag != 0);890case JMM_VERBOSE_CLASS:891return ClassLoadingService::set_verbose(flag != 0);892case JMM_THREAD_CONTENTION_MONITORING:893return ThreadService::set_thread_monitoring_contention(flag != 0);894case JMM_THREAD_CPU_TIME:895return ThreadService::set_thread_cpu_time_enabled(flag != 0);896case JMM_THREAD_ALLOCATED_MEMORY:897return ThreadService::set_thread_allocated_memory_enabled(flag != 0);898default:899assert(0, "Unrecognized attribute");900return false;901}902JVM_END903904905static jlong get_gc_attribute(GCMemoryManager* mgr, jmmLongAttribute att) {906switch (att) {907case JMM_GC_TIME_MS:908return mgr->gc_time_ms();909910case JMM_GC_COUNT:911return mgr->gc_count();912913case JMM_GC_EXT_ATTRIBUTE_INFO_SIZE:914// current implementation only has 1 ext attribute915return 1;916917default:918assert(0, "Unrecognized GC attribute");919return -1;920}921}922923class VmThreadCountClosure: public ThreadClosure {924private:925int _count;926public:927VmThreadCountClosure() : _count(0) {};928void do_thread(Thread* thread);929int count() { return _count; }930};931932void VmThreadCountClosure::do_thread(Thread* thread) {933// exclude externally visible JavaThreads934if (thread->is_Java_thread() && !thread->is_hidden_from_external_view()) {935return;936}937938_count++;939}940941static jint get_vm_thread_count() {942VmThreadCountClosure vmtcc;943{944MutexLockerEx ml(Threads_lock);945Threads::threads_do(&vmtcc);946}947948return vmtcc.count();949}950951static jint get_num_flags() {952// last flag entry is always NULL, so subtract 1953int nFlags = (int) Flag::numFlags - 1;954int count = 0;955for (int i = 0; i < nFlags; i++) {956Flag* flag = &Flag::flags[i];957// Exclude the locked (diagnostic, experimental) flags958if (flag->is_unlocked() || flag->is_unlocker()) {959count++;960}961}962return count;963}964965static jlong get_long_attribute(jmmLongAttribute att) {966switch (att) {967case JMM_CLASS_LOADED_COUNT:968return ClassLoadingService::loaded_class_count();969970case JMM_CLASS_UNLOADED_COUNT:971return ClassLoadingService::unloaded_class_count();972973case JMM_THREAD_TOTAL_COUNT:974return ThreadService::get_total_thread_count();975976case JMM_THREAD_LIVE_COUNT:977return ThreadService::get_live_thread_count();978979case JMM_THREAD_PEAK_COUNT:980return ThreadService::get_peak_thread_count();981982case JMM_THREAD_DAEMON_COUNT:983return ThreadService::get_daemon_thread_count();984985case JMM_JVM_INIT_DONE_TIME_MS:986return Management::vm_init_done_time();987988case JMM_JVM_UPTIME_MS:989return Management::ticks_to_ms(os::elapsed_counter());990991case JMM_COMPILE_TOTAL_TIME_MS:992return Management::ticks_to_ms(CompileBroker::total_compilation_ticks());993994case JMM_OS_PROCESS_ID:995return os::current_process_id();996997// Hotspot-specific counters998case JMM_CLASS_LOADED_BYTES:999return ClassLoadingService::loaded_class_bytes();10001001case JMM_CLASS_UNLOADED_BYTES:1002return ClassLoadingService::unloaded_class_bytes();10031004case JMM_SHARED_CLASS_LOADED_COUNT:1005return ClassLoadingService::loaded_shared_class_count();10061007case JMM_SHARED_CLASS_UNLOADED_COUNT:1008return ClassLoadingService::unloaded_shared_class_count();100910101011case JMM_SHARED_CLASS_LOADED_BYTES:1012return ClassLoadingService::loaded_shared_class_bytes();10131014case JMM_SHARED_CLASS_UNLOADED_BYTES:1015return ClassLoadingService::unloaded_shared_class_bytes();10161017case JMM_TOTAL_CLASSLOAD_TIME_MS:1018return ClassLoader::classloader_time_ms();10191020case JMM_VM_GLOBAL_COUNT:1021return get_num_flags();10221023case JMM_SAFEPOINT_COUNT:1024return RuntimeService::safepoint_count();10251026case JMM_TOTAL_SAFEPOINTSYNC_TIME_MS:1027return RuntimeService::safepoint_sync_time_ms();10281029case JMM_TOTAL_STOPPED_TIME_MS:1030return RuntimeService::safepoint_time_ms();10311032case JMM_TOTAL_APP_TIME_MS:1033return RuntimeService::application_time_ms();10341035case JMM_VM_THREAD_COUNT:1036return get_vm_thread_count();10371038case JMM_CLASS_INIT_TOTAL_COUNT:1039return ClassLoader::class_init_count();10401041case JMM_CLASS_INIT_TOTAL_TIME_MS:1042return ClassLoader::class_init_time_ms();10431044case JMM_CLASS_VERIFY_TOTAL_TIME_MS:1045return ClassLoader::class_verify_time_ms();10461047case JMM_METHOD_DATA_SIZE_BYTES:1048return ClassLoadingService::class_method_data_size();10491050case JMM_OS_MEM_TOTAL_PHYSICAL_BYTES:1051return os::physical_memory();10521053default:1054return -1;1055}1056}105710581059// Returns the long value of a given attribute.1060JVM_ENTRY(jlong, jmm_GetLongAttribute(JNIEnv *env, jobject obj, jmmLongAttribute att))1061if (obj == NULL) {1062return get_long_attribute(att);1063} else {1064GCMemoryManager* mgr = get_gc_memory_manager_from_jobject(obj, CHECK_(0L));1065if (mgr != NULL) {1066return get_gc_attribute(mgr, att);1067}1068}1069return -1;1070JVM_END10711072// Gets the value of all attributes specified in the given array1073// and sets the value in the result array.1074// Returns the number of attributes found.1075JVM_ENTRY(jint, jmm_GetLongAttributes(JNIEnv *env,1076jobject obj,1077jmmLongAttribute* atts,1078jint count,1079jlong* result))10801081int num_atts = 0;1082if (obj == NULL) {1083for (int i = 0; i < count; i++) {1084result[i] = get_long_attribute(atts[i]);1085if (result[i] != -1) {1086num_atts++;1087}1088}1089} else {1090GCMemoryManager* mgr = get_gc_memory_manager_from_jobject(obj, CHECK_0);1091for (int i = 0; i < count; i++) {1092result[i] = get_gc_attribute(mgr, atts[i]);1093if (result[i] != -1) {1094num_atts++;1095}1096}1097}1098return num_atts;1099JVM_END11001101// Helper function to do thread dump for a specific list of threads1102static void do_thread_dump(ThreadDumpResult* dump_result,1103typeArrayHandle ids_ah, // array of thread ID (long[])1104int num_threads,1105int max_depth,1106bool with_locked_monitors,1107bool with_locked_synchronizers,1108TRAPS) {1109// no need to actually perform thread dump if no TIDs are specified1110if (num_threads == 0) return;11111112// First get an array of threadObj handles.1113// A JavaThread may terminate before we get the stack trace.1114GrowableArray<instanceHandle>* thread_handle_array = new GrowableArray<instanceHandle>(num_threads);1115{1116MutexLockerEx ml(Threads_lock);1117for (int i = 0; i < num_threads; i++) {1118jlong tid = ids_ah->long_at(i);1119JavaThread* jt = Threads::find_java_thread_from_java_tid(tid);1120oop thread_obj = (jt != NULL ? jt->threadObj() : (oop)NULL);1121instanceHandle threadObj_h(THREAD, (instanceOop) thread_obj);1122thread_handle_array->append(threadObj_h);1123}1124}11251126// Obtain thread dumps and thread snapshot information1127VM_ThreadDump op(dump_result,1128thread_handle_array,1129num_threads,1130max_depth, /* stack depth */1131with_locked_monitors,1132with_locked_synchronizers);1133VMThread::execute(&op);1134}11351136// Gets an array of ThreadInfo objects. Each element is the ThreadInfo1137// for the thread ID specified in the corresponding entry in1138// the given array of thread IDs; or NULL if the thread does not exist1139// or has terminated.1140//1141// Input parameters:1142// ids - array of thread IDs1143// maxDepth - the maximum depth of stack traces to be dumped:1144// maxDepth == -1 requests to dump entire stack trace.1145// maxDepth == 0 requests no stack trace.1146// infoArray - array of ThreadInfo objects1147//1148// QQQ - Why does this method return a value instead of void?1149JVM_ENTRY(jint, jmm_GetThreadInfo(JNIEnv *env, jlongArray ids, jint maxDepth, jobjectArray infoArray))1150// Check if threads is null1151if (ids == NULL || infoArray == NULL) {1152THROW_(vmSymbols::java_lang_NullPointerException(), -1);1153}11541155if (maxDepth < -1) {1156THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),1157"Invalid maxDepth", -1);1158}11591160ResourceMark rm(THREAD);1161typeArrayOop ta = typeArrayOop(JNIHandles::resolve_non_null(ids));1162typeArrayHandle ids_ah(THREAD, ta);11631164oop infoArray_obj = JNIHandles::resolve_non_null(infoArray);1165objArrayOop oa = objArrayOop(infoArray_obj);1166objArrayHandle infoArray_h(THREAD, oa);11671168// validate the thread id array1169validate_thread_id_array(ids_ah, CHECK_0);11701171// validate the ThreadInfo[] parameters1172validate_thread_info_array(infoArray_h, CHECK_0);11731174// infoArray must be of the same length as the given array of thread IDs1175int num_threads = ids_ah->length();1176if (num_threads != infoArray_h->length()) {1177THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),1178"The length of the given ThreadInfo array does not match the length of the given array of thread IDs", -1);1179}11801181if (JDK_Version::is_gte_jdk16x_version()) {1182// make sure the AbstractOwnableSynchronizer klass is loaded before taking thread snapshots1183java_util_concurrent_locks_AbstractOwnableSynchronizer::initialize(CHECK_0);1184}11851186// Must use ThreadDumpResult to store the ThreadSnapshot.1187// GC may occur after the thread snapshots are taken but before1188// this function returns. The threadObj and other oops kept1189// in the ThreadSnapshot are marked and adjusted during GC.1190ThreadDumpResult dump_result(num_threads);11911192if (maxDepth == 0) {1193// no stack trace dumped - do not need to stop the world1194{1195MutexLockerEx ml(Threads_lock);1196for (int i = 0; i < num_threads; i++) {1197jlong tid = ids_ah->long_at(i);1198JavaThread* jt = Threads::find_java_thread_from_java_tid(tid);1199ThreadSnapshot* ts;1200if (jt == NULL) {1201// if the thread does not exist or now it is terminated,1202// create dummy snapshot1203ts = new ThreadSnapshot();1204} else {1205ts = new ThreadSnapshot(jt);1206}1207dump_result.add_thread_snapshot(ts);1208}1209}1210} else {1211// obtain thread dump with the specific list of threads with stack trace1212do_thread_dump(&dump_result,1213ids_ah,1214num_threads,1215maxDepth,1216false, /* no locked monitor */1217false, /* no locked synchronizers */1218CHECK_0);1219}12201221int num_snapshots = dump_result.num_snapshots();1222assert(num_snapshots == num_threads, "Must match the number of thread snapshots");1223int index = 0;1224for (ThreadSnapshot* ts = dump_result.snapshots(); ts != NULL; index++, ts = ts->next()) {1225// For each thread, create an java/lang/management/ThreadInfo object1226// and fill with the thread information12271228if (ts->threadObj() == NULL) {1229// if the thread does not exist or now it is terminated, set threadinfo to NULL1230infoArray_h->obj_at_put(index, NULL);1231continue;1232}12331234// Create java.lang.management.ThreadInfo object1235instanceOop info_obj = Management::create_thread_info_instance(ts, CHECK_0);1236infoArray_h->obj_at_put(index, info_obj);1237}1238return 0;1239JVM_END12401241// Dump thread info for the specified threads.1242// It returns an array of ThreadInfo objects. Each element is the ThreadInfo1243// for the thread ID specified in the corresponding entry in1244// the given array of thread IDs; or NULL if the thread does not exist1245// or has terminated.1246//1247// Input parameter:1248// ids - array of thread IDs; NULL indicates all live threads1249// locked_monitors - if true, dump locked object monitors1250// locked_synchronizers - if true, dump locked JSR-166 synchronizers1251// maxDepth - the maximum depth of stack traces to be dumped:1252// maxDepth == -1 requests to dump entire stack trace.1253// maxDepth == 0 requests no stack trace.1254//1255JVM_ENTRY(jobjectArray, jmm_DumpThreadsMaxDepth(JNIEnv *env, jlongArray thread_ids, jboolean locked_monitors,1256jboolean locked_synchronizers, jint maxDepth))1257ResourceMark rm(THREAD);12581259if (JDK_Version::is_gte_jdk16x_version()) {1260// make sure the AbstractOwnableSynchronizer klass is loaded before taking thread snapshots1261java_util_concurrent_locks_AbstractOwnableSynchronizer::initialize(CHECK_NULL);1262}12631264typeArrayOop ta = typeArrayOop(JNIHandles::resolve(thread_ids));1265int num_threads = (ta != NULL ? ta->length() : 0);1266typeArrayHandle ids_ah(THREAD, ta);12671268ThreadDumpResult dump_result(num_threads); // can safepoint12691270if (ids_ah() != NULL) {12711272// validate the thread id array1273validate_thread_id_array(ids_ah, CHECK_NULL);12741275// obtain thread dump of a specific list of threads1276do_thread_dump(&dump_result,1277ids_ah,1278num_threads,1279maxDepth, /* stack depth */1280(locked_monitors ? true : false), /* with locked monitors */1281(locked_synchronizers ? true : false), /* with locked synchronizers */1282CHECK_NULL);1283} else {1284// obtain thread dump of all threads1285VM_ThreadDump op(&dump_result,1286maxDepth, /* stack depth */1287(locked_monitors ? true : false), /* with locked monitors */1288(locked_synchronizers ? true : false) /* with locked synchronizers */);1289VMThread::execute(&op);1290}12911292int num_snapshots = dump_result.num_snapshots();12931294// create the result ThreadInfo[] object1295Klass* k = Management::java_lang_management_ThreadInfo_klass(CHECK_NULL);1296instanceKlassHandle ik (THREAD, k);1297objArrayOop r = oopFactory::new_objArray(ik(), num_snapshots, CHECK_NULL);1298objArrayHandle result_h(THREAD, r);12991300int index = 0;1301for (ThreadSnapshot* ts = dump_result.snapshots(); ts != NULL; ts = ts->next(), index++) {1302if (ts->threadObj() == NULL) {1303// if the thread does not exist or now it is terminated, set threadinfo to NULL1304result_h->obj_at_put(index, NULL);1305continue;1306}13071308ThreadStackTrace* stacktrace = ts->get_stack_trace();1309assert(stacktrace != NULL, "Must have a stack trace dumped");13101311// Create Object[] filled with locked monitors1312// Create int[] filled with the stack depth where a monitor was locked1313int num_frames = stacktrace->get_stack_depth();1314int num_locked_monitors = stacktrace->num_jni_locked_monitors();13151316// Count the total number of locked monitors1317for (int i = 0; i < num_frames; i++) {1318StackFrameInfo* frame = stacktrace->stack_frame_at(i);1319num_locked_monitors += frame->num_locked_monitors();1320}13211322objArrayHandle monitors_array;1323typeArrayHandle depths_array;1324objArrayHandle synchronizers_array;13251326if (locked_monitors) {1327// Constructs Object[] and int[] to contain the object monitor and the stack depth1328// where the thread locked it1329objArrayOop array = oopFactory::new_objArray(SystemDictionary::Object_klass(), num_locked_monitors, CHECK_NULL);1330objArrayHandle mh(THREAD, array);1331monitors_array = mh;13321333typeArrayOop tarray = oopFactory::new_typeArray(T_INT, num_locked_monitors, CHECK_NULL);1334typeArrayHandle dh(THREAD, tarray);1335depths_array = dh;13361337int count = 0;1338int j = 0;1339for (int depth = 0; depth < num_frames; depth++) {1340StackFrameInfo* frame = stacktrace->stack_frame_at(depth);1341int len = frame->num_locked_monitors();1342GrowableArray<oop>* locked_monitors = frame->locked_monitors();1343for (j = 0; j < len; j++) {1344oop monitor = locked_monitors->at(j);1345assert(monitor != NULL && monitor->is_instance(), "must be a Java object");1346monitors_array->obj_at_put(count, monitor);1347depths_array->int_at_put(count, depth);1348count++;1349}1350}13511352GrowableArray<oop>* jni_locked_monitors = stacktrace->jni_locked_monitors();1353for (j = 0; j < jni_locked_monitors->length(); j++) {1354oop object = jni_locked_monitors->at(j);1355assert(object != NULL && object->is_instance(), "must be a Java object");1356monitors_array->obj_at_put(count, object);1357// Monitor locked via JNI MonitorEnter call doesn't have stack depth info1358depths_array->int_at_put(count, -1);1359count++;1360}1361assert(count == num_locked_monitors, "number of locked monitors doesn't match");1362}13631364if (locked_synchronizers) {1365// Create Object[] filled with locked JSR-166 synchronizers1366assert(ts->threadObj() != NULL, "Must be a valid JavaThread");1367ThreadConcurrentLocks* tcl = ts->get_concurrent_locks();1368GrowableArray<instanceOop>* locks = (tcl != NULL ? tcl->owned_locks() : NULL);1369int num_locked_synchronizers = (locks != NULL ? locks->length() : 0);13701371objArrayOop array = oopFactory::new_objArray(SystemDictionary::Object_klass(), num_locked_synchronizers, CHECK_NULL);1372objArrayHandle sh(THREAD, array);1373synchronizers_array = sh;13741375for (int k = 0; k < num_locked_synchronizers; k++) {1376synchronizers_array->obj_at_put(k, locks->at(k));1377}1378}13791380// Create java.lang.management.ThreadInfo object1381instanceOop info_obj = Management::create_thread_info_instance(ts,1382monitors_array,1383depths_array,1384synchronizers_array,1385CHECK_NULL);1386result_h->obj_at_put(index, info_obj);1387}13881389return (jobjectArray) JNIHandles::make_local(env, result_h());1390JVM_END13911392// Dump thread info for the specified threads.1393// It returns an array of ThreadInfo objects. Each element is the ThreadInfo1394// for the thread ID specified in the corresponding entry in1395// the given array of thread IDs; or NULL if the thread does not exist1396// or has terminated.1397//1398// Input parameter:1399// ids - array of thread IDs; NULL indicates all live threads1400// locked_monitors - if true, dump locked object monitors1401// locked_synchronizers - if true, dump locked JSR-166 synchronizers1402//1403// This method exists only for compatbility with compiled binaries that call it.1404// The JDK library uses jmm_DumpThreadsMaxDepth.1405//1406JVM_ENTRY(jobjectArray, jmm_DumpThreads(JNIEnv *env, jlongArray thread_ids, jboolean locked_monitors,1407jboolean locked_synchronizers))1408return jmm_DumpThreadsMaxDepth(env, thread_ids, locked_monitors, locked_synchronizers, INT_MAX);1409JVM_END14101411// Returns an array of Class objects.1412JVM_ENTRY(jobjectArray, jmm_GetLoadedClasses(JNIEnv *env))1413ResourceMark rm(THREAD);14141415LoadedClassesEnumerator lce(THREAD); // Pass current Thread as parameter14161417int num_classes = lce.num_loaded_classes();1418objArrayOop r = oopFactory::new_objArray(SystemDictionary::Class_klass(), num_classes, CHECK_0);1419objArrayHandle classes_ah(THREAD, r);14201421for (int i = 0; i < num_classes; i++) {1422KlassHandle kh = lce.get_klass(i);1423oop mirror = kh()->java_mirror();1424classes_ah->obj_at_put(i, mirror);1425}14261427return (jobjectArray) JNIHandles::make_local(env, classes_ah());1428JVM_END14291430// Reset statistic. Return true if the requested statistic is reset.1431// Otherwise, return false.1432//1433// Input parameters:1434// obj - specify which instance the statistic associated with to be reset1435// For PEAK_POOL_USAGE stat, obj is required to be a memory pool object.1436// For THREAD_CONTENTION_COUNT and TIME stat, obj is required to be a thread ID.1437// type - the type of statistic to be reset1438//1439JVM_ENTRY(jboolean, jmm_ResetStatistic(JNIEnv *env, jvalue obj, jmmStatisticType type))1440ResourceMark rm(THREAD);14411442switch (type) {1443case JMM_STAT_PEAK_THREAD_COUNT:1444ThreadService::reset_peak_thread_count();1445return true;14461447case JMM_STAT_THREAD_CONTENTION_COUNT:1448case JMM_STAT_THREAD_CONTENTION_TIME: {1449jlong tid = obj.j;1450if (tid < 0) {1451THROW_(vmSymbols::java_lang_IllegalArgumentException(), JNI_FALSE);1452}14531454// Look for the JavaThread of this given tid1455MutexLockerEx ml(Threads_lock);1456if (tid == 0) {1457// reset contention statistics for all threads if tid == 01458for (JavaThread* java_thread = Threads::first(); java_thread != NULL; java_thread = java_thread->next()) {1459if (type == JMM_STAT_THREAD_CONTENTION_COUNT) {1460ThreadService::reset_contention_count_stat(java_thread);1461} else {1462ThreadService::reset_contention_time_stat(java_thread);1463}1464}1465} else {1466// reset contention statistics for a given thread1467JavaThread* java_thread = Threads::find_java_thread_from_java_tid(tid);1468if (java_thread == NULL) {1469return false;1470}14711472if (type == JMM_STAT_THREAD_CONTENTION_COUNT) {1473ThreadService::reset_contention_count_stat(java_thread);1474} else {1475ThreadService::reset_contention_time_stat(java_thread);1476}1477}1478return true;1479break;1480}1481case JMM_STAT_PEAK_POOL_USAGE: {1482jobject o = obj.l;1483if (o == NULL) {1484THROW_(vmSymbols::java_lang_NullPointerException(), JNI_FALSE);1485}14861487oop pool_obj = JNIHandles::resolve(o);1488assert(pool_obj->is_instance(), "Should be an instanceOop");1489instanceHandle ph(THREAD, (instanceOop) pool_obj);14901491MemoryPool* pool = MemoryService::get_memory_pool(ph);1492if (pool != NULL) {1493pool->reset_peak_memory_usage();1494return true;1495}1496break;1497}1498case JMM_STAT_GC_STAT: {1499jobject o = obj.l;1500if (o == NULL) {1501THROW_(vmSymbols::java_lang_NullPointerException(), JNI_FALSE);1502}15031504GCMemoryManager* mgr = get_gc_memory_manager_from_jobject(o, CHECK_0);1505if (mgr != NULL) {1506mgr->reset_gc_stat();1507return true;1508}1509break;1510}1511default:1512assert(0, "Unknown Statistic Type");1513}1514return false;1515JVM_END15161517// Returns the fast estimate of CPU time consumed by1518// a given thread (in nanoseconds).1519// If thread_id == 0, return CPU time for the current thread.1520JVM_ENTRY(jlong, jmm_GetThreadCpuTime(JNIEnv *env, jlong thread_id))1521if (!os::is_thread_cpu_time_supported()) {1522return -1;1523}15241525if (thread_id < 0) {1526THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),1527"Invalid thread ID", -1);1528}15291530JavaThread* java_thread = NULL;1531if (thread_id == 0) {1532// current thread1533return os::current_thread_cpu_time();1534} else {1535MutexLockerEx ml(Threads_lock);1536java_thread = Threads::find_java_thread_from_java_tid(thread_id);1537if (java_thread != NULL) {1538return os::thread_cpu_time((Thread*) java_thread);1539}1540}1541return -1;1542JVM_END15431544// Returns a String array of all VM global flag names1545JVM_ENTRY(jobjectArray, jmm_GetVMGlobalNames(JNIEnv *env))1546// last flag entry is always NULL, so subtract 11547int nFlags = (int) Flag::numFlags - 1;1548// allocate a temp array1549objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),1550nFlags, CHECK_0);1551objArrayHandle flags_ah(THREAD, r);1552int num_entries = 0;1553for (int i = 0; i < nFlags; i++) {1554Flag* flag = &Flag::flags[i];1555// Exclude notproduct and develop flags in product builds.1556if (flag->is_constant_in_binary()) {1557continue;1558}1559// Exclude the locked (experimental, diagnostic) flags1560if (flag->is_unlocked() || flag->is_unlocker()) {1561Handle s = java_lang_String::create_from_str(flag->_name, CHECK_0);1562flags_ah->obj_at_put(num_entries, s());1563num_entries++;1564}1565}15661567if (num_entries < nFlags) {1568// Return array of right length1569objArrayOop res = oopFactory::new_objArray(SystemDictionary::String_klass(), num_entries, CHECK_0);1570for(int i = 0; i < num_entries; i++) {1571res->obj_at_put(i, flags_ah->obj_at(i));1572}1573return (jobjectArray)JNIHandles::make_local(env, res);1574}15751576return (jobjectArray)JNIHandles::make_local(env, flags_ah());1577JVM_END15781579// Utility function used by jmm_GetVMGlobals. Returns false if flag type1580// can't be determined, true otherwise. If false is returned, then *global1581// will be incomplete and invalid.1582bool add_global_entry(JNIEnv* env, Handle name, jmmVMGlobal *global, Flag *flag, TRAPS) {1583Handle flag_name;1584if (name() == NULL) {1585flag_name = java_lang_String::create_from_str(flag->_name, CHECK_false);1586} else {1587flag_name = name;1588}1589global->name = (jstring)JNIHandles::make_local(env, flag_name());15901591if (flag->is_bool()) {1592global->value.z = flag->get_bool() ? JNI_TRUE : JNI_FALSE;1593global->type = JMM_VMGLOBAL_TYPE_JBOOLEAN;1594} else if (flag->is_intx()) {1595global->value.j = (jlong)flag->get_intx();1596global->type = JMM_VMGLOBAL_TYPE_JLONG;1597} else if (flag->is_uintx()) {1598global->value.j = (jlong)flag->get_uintx();1599global->type = JMM_VMGLOBAL_TYPE_JLONG;1600} else if (flag->is_uint64_t()) {1601global->value.j = (jlong)flag->get_uint64_t();1602global->type = JMM_VMGLOBAL_TYPE_JLONG;1603} else if (flag->is_double()) {1604global->value.d = (jdouble)flag->get_double();1605global->type = JMM_VMGLOBAL_TYPE_JDOUBLE;1606} else if (flag->is_ccstr()) {1607Handle str = java_lang_String::create_from_str(flag->get_ccstr(), CHECK_false);1608global->value.l = (jobject)JNIHandles::make_local(env, str());1609global->type = JMM_VMGLOBAL_TYPE_JSTRING;1610} else {1611global->type = JMM_VMGLOBAL_TYPE_UNKNOWN;1612return false;1613}16141615global->writeable = flag->is_writeable();1616global->external = flag->is_external();1617switch (flag->get_origin()) {1618case Flag::DEFAULT:1619global->origin = JMM_VMGLOBAL_ORIGIN_DEFAULT;1620break;1621case Flag::COMMAND_LINE:1622global->origin = JMM_VMGLOBAL_ORIGIN_COMMAND_LINE;1623break;1624case Flag::ENVIRON_VAR:1625global->origin = JMM_VMGLOBAL_ORIGIN_ENVIRON_VAR;1626break;1627case Flag::CONFIG_FILE:1628global->origin = JMM_VMGLOBAL_ORIGIN_CONFIG_FILE;1629break;1630case Flag::MANAGEMENT:1631global->origin = JMM_VMGLOBAL_ORIGIN_MANAGEMENT;1632break;1633case Flag::ERGONOMIC:1634global->origin = JMM_VMGLOBAL_ORIGIN_ERGONOMIC;1635break;1636default:1637global->origin = JMM_VMGLOBAL_ORIGIN_OTHER;1638}16391640return true;1641}16421643// Fill globals array of count length with jmmVMGlobal entries1644// specified by names. If names == NULL, fill globals array1645// with all Flags. Return value is number of entries1646// created in globals.1647// If a Flag with a given name in an array element does not1648// exist, globals[i].name will be set to NULL.1649JVM_ENTRY(jint, jmm_GetVMGlobals(JNIEnv *env,1650jobjectArray names,1651jmmVMGlobal *globals,1652jint count))165316541655if (globals == NULL) {1656THROW_(vmSymbols::java_lang_NullPointerException(), 0);1657}16581659ResourceMark rm(THREAD);16601661if (names != NULL) {1662// return the requested globals1663objArrayOop ta = objArrayOop(JNIHandles::resolve_non_null(names));1664objArrayHandle names_ah(THREAD, ta);1665// Make sure we have a String array1666Klass* element_klass = ObjArrayKlass::cast(names_ah->klass())->element_klass();1667if (element_klass != SystemDictionary::String_klass()) {1668THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),1669"Array element type is not String class", 0);1670}16711672int names_length = names_ah->length();1673int num_entries = 0;1674for (int i = 0; i < names_length && i < count; i++) {1675oop s = names_ah->obj_at(i);1676if (s == NULL) {1677THROW_(vmSymbols::java_lang_NullPointerException(), 0);1678}16791680Handle sh(THREAD, s);1681char* str = java_lang_String::as_utf8_string(s);1682Flag* flag = Flag::find_flag(str, strlen(str));1683if (flag != NULL &&1684add_global_entry(env, sh, &globals[i], flag, THREAD)) {1685num_entries++;1686} else {1687globals[i].name = NULL;1688}1689}1690return num_entries;1691} else {1692// return all globals if names == NULL16931694// last flag entry is always NULL, so subtract 11695int nFlags = (int) Flag::numFlags - 1;1696Handle null_h;1697int num_entries = 0;1698for (int i = 0; i < nFlags && num_entries < count; i++) {1699Flag* flag = &Flag::flags[i];1700// Exclude notproduct and develop flags in product builds.1701if (flag->is_constant_in_binary()) {1702continue;1703}1704// Exclude the locked (diagnostic, experimental) flags1705if ((flag->is_unlocked() || flag->is_unlocker()) &&1706add_global_entry(env, null_h, &globals[num_entries], flag, THREAD)) {1707num_entries++;1708}1709}1710return num_entries;1711}1712JVM_END17131714JVM_ENTRY(void, jmm_SetVMGlobal(JNIEnv *env, jstring flag_name, jvalue new_value))1715ResourceMark rm(THREAD);17161717oop fn = JNIHandles::resolve_external_guard(flag_name);1718if (fn == NULL) {1719THROW_MSG(vmSymbols::java_lang_NullPointerException(),1720"The flag name cannot be null.");1721}1722char* name = java_lang_String::as_utf8_string(fn);1723Flag* flag = Flag::find_flag(name, strlen(name));1724if (flag == NULL) {1725THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),1726"Flag does not exist.");1727}1728if (!flag->is_writeable()) {1729THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),1730"This flag is not writeable.");1731}17321733bool succeed = false;1734if (flag->is_bool()) {1735bool bvalue = (new_value.z == JNI_TRUE ? true : false);1736succeed = CommandLineFlags::boolAtPut(name, &bvalue, Flag::MANAGEMENT);1737} else if (flag->is_intx()) {1738intx ivalue = (intx)new_value.j;1739succeed = CommandLineFlags::intxAtPut(name, &ivalue, Flag::MANAGEMENT);1740} else if (flag->is_uintx()) {1741uintx uvalue = (uintx)new_value.j;17421743if (strncmp(name, "MaxHeapFreeRatio", 17) == 0) {1744FormatBuffer<80> err_msg("%s", "");1745if (!Arguments::verify_MaxHeapFreeRatio(err_msg, uvalue)) {1746THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), err_msg.buffer());1747}1748} else if (strncmp(name, "MinHeapFreeRatio", 17) == 0) {1749FormatBuffer<80> err_msg("%s", "");1750if (!Arguments::verify_MinHeapFreeRatio(err_msg, uvalue)) {1751THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), err_msg.buffer());1752}1753}1754succeed = CommandLineFlags::uintxAtPut(name, &uvalue, Flag::MANAGEMENT);1755} else if (flag->is_uint64_t()) {1756uint64_t uvalue = (uint64_t)new_value.j;1757succeed = CommandLineFlags::uint64_tAtPut(name, &uvalue, Flag::MANAGEMENT);1758} else if (flag->is_ccstr()) {1759oop str = JNIHandles::resolve_external_guard(new_value.l);1760if (str == NULL) {1761THROW(vmSymbols::java_lang_NullPointerException());1762}1763ccstr svalue = java_lang_String::as_utf8_string(str);1764succeed = CommandLineFlags::ccstrAtPut(name, &svalue, Flag::MANAGEMENT);1765if (succeed) {1766FREE_C_HEAP_ARRAY(char, svalue, mtInternal);1767}1768}1769assert(succeed, "Setting flag should succeed");1770JVM_END17711772class ThreadTimesClosure: public ThreadClosure {1773private:1774objArrayHandle _names_strings;1775char **_names_chars;1776typeArrayHandle _times;1777int _names_len;1778int _times_len;1779int _count;17801781public:1782ThreadTimesClosure(objArrayHandle names, typeArrayHandle times);1783~ThreadTimesClosure();1784virtual void do_thread(Thread* thread);1785void do_unlocked();1786int count() { return _count; }1787};17881789ThreadTimesClosure::ThreadTimesClosure(objArrayHandle names,1790typeArrayHandle times) {1791assert(names() != NULL, "names was NULL");1792assert(times() != NULL, "times was NULL");1793_names_strings = names;1794_names_len = names->length();1795_names_chars = NEW_C_HEAP_ARRAY(char*, _names_len, mtInternal);1796_times = times;1797_times_len = times->length();1798_count = 0;1799}18001801//1802// Called with Threads_lock held1803//1804void ThreadTimesClosure::do_thread(Thread* thread) {1805assert(thread != NULL, "thread was NULL");18061807// exclude externally visible JavaThreads1808if (thread->is_Java_thread() && !thread->is_hidden_from_external_view()) {1809return;1810}18111812if (_count >= _names_len || _count >= _times_len) {1813// skip if the result array is not big enough1814return;1815}18161817EXCEPTION_MARK;1818ResourceMark rm(THREAD); // thread->name() uses ResourceArea18191820assert(thread->name() != NULL, "All threads should have a name");1821_names_chars[_count] = strdup(thread->name());1822_times->long_at_put(_count, os::is_thread_cpu_time_supported() ?1823os::thread_cpu_time(thread) : -1);1824_count++;1825}18261827// Called without Threads_lock, we can allocate String objects.1828void ThreadTimesClosure::do_unlocked() {18291830EXCEPTION_MARK;1831for (int i = 0; i < _count; i++) {1832Handle s = java_lang_String::create_from_str(_names_chars[i], CHECK);1833_names_strings->obj_at_put(i, s());1834}1835}18361837ThreadTimesClosure::~ThreadTimesClosure() {1838for (int i = 0; i < _count; i++) {1839free(_names_chars[i]);1840}1841FREE_C_HEAP_ARRAY(char *, _names_chars, mtInternal);1842}18431844// Fills names with VM internal thread names and times with the corresponding1845// CPU times. If names or times is NULL, a NullPointerException is thrown.1846// If the element type of names is not String, an IllegalArgumentException is1847// thrown.1848// If an array is not large enough to hold all the entries, only the entries1849// that fit will be returned. Return value is the number of VM internal1850// threads entries.1851JVM_ENTRY(jint, jmm_GetInternalThreadTimes(JNIEnv *env,1852jobjectArray names,1853jlongArray times))1854if (names == NULL || times == NULL) {1855THROW_(vmSymbols::java_lang_NullPointerException(), 0);1856}1857objArrayOop na = objArrayOop(JNIHandles::resolve_non_null(names));1858objArrayHandle names_ah(THREAD, na);18591860// Make sure we have a String array1861Klass* element_klass = ObjArrayKlass::cast(names_ah->klass())->element_klass();1862if (element_klass != SystemDictionary::String_klass()) {1863THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),1864"Array element type is not String class", 0);1865}18661867typeArrayOop ta = typeArrayOop(JNIHandles::resolve_non_null(times));1868typeArrayHandle times_ah(THREAD, ta);18691870ThreadTimesClosure ttc(names_ah, times_ah);1871{1872MutexLockerEx ml(Threads_lock);1873Threads::threads_do(&ttc);1874}1875ttc.do_unlocked();1876return ttc.count();1877JVM_END18781879static Handle find_deadlocks(bool object_monitors_only, TRAPS) {1880ResourceMark rm(THREAD);18811882VM_FindDeadlocks op(!object_monitors_only /* also check concurrent locks? */);1883VMThread::execute(&op);18841885DeadlockCycle* deadlocks = op.result();1886if (deadlocks == NULL) {1887// no deadlock found and return1888return Handle();1889}18901891int num_threads = 0;1892DeadlockCycle* cycle;1893for (cycle = deadlocks; cycle != NULL; cycle = cycle->next()) {1894num_threads += cycle->num_threads();1895}18961897objArrayOop r = oopFactory::new_objArray(SystemDictionary::Thread_klass(), num_threads, CHECK_NH);1898objArrayHandle threads_ah(THREAD, r);18991900int index = 0;1901for (cycle = deadlocks; cycle != NULL; cycle = cycle->next()) {1902GrowableArray<JavaThread*>* deadlock_threads = cycle->threads();1903int len = deadlock_threads->length();1904for (int i = 0; i < len; i++) {1905threads_ah->obj_at_put(index, deadlock_threads->at(i)->threadObj());1906index++;1907}1908}1909return threads_ah;1910}19111912// Finds cycles of threads that are deadlocked involved in object monitors1913// and JSR-166 synchronizers.1914// Returns an array of Thread objects which are in deadlock, if any.1915// Otherwise, returns NULL.1916//1917// Input parameter:1918// object_monitors_only - if true, only check object monitors1919//1920JVM_ENTRY(jobjectArray, jmm_FindDeadlockedThreads(JNIEnv *env, jboolean object_monitors_only))1921Handle result = find_deadlocks(object_monitors_only != 0, CHECK_0);1922return (jobjectArray) JNIHandles::make_local(env, result());1923JVM_END19241925// Finds cycles of threads that are deadlocked on monitor locks1926// Returns an array of Thread objects which are in deadlock, if any.1927// Otherwise, returns NULL.1928JVM_ENTRY(jobjectArray, jmm_FindMonitorDeadlockedThreads(JNIEnv *env))1929Handle result = find_deadlocks(true, CHECK_0);1930return (jobjectArray) JNIHandles::make_local(env, result());1931JVM_END19321933// Gets the information about GC extension attributes including1934// the name of the attribute, its type, and a short description.1935//1936// Input parameters:1937// mgr - GC memory manager1938// info - caller allocated array of jmmExtAttributeInfo1939// count - number of elements of the info array1940//1941// Returns the number of GC extension attributes filled in the info array; or1942// -1 if info is not big enough1943//1944JVM_ENTRY(jint, jmm_GetGCExtAttributeInfo(JNIEnv *env, jobject mgr, jmmExtAttributeInfo* info, jint count))1945// All GC memory managers have 1 attribute (number of GC threads)1946if (count == 0) {1947return 0;1948}19491950if (info == NULL) {1951THROW_(vmSymbols::java_lang_NullPointerException(), 0);1952}19531954info[0].name = "GcThreadCount";1955info[0].type = 'I';1956info[0].description = "Number of GC threads";1957return 1;1958JVM_END19591960// verify the given array is an array of java/lang/management/MemoryUsage objects1961// of a given length and return the objArrayOop1962static objArrayOop get_memory_usage_objArray(jobjectArray array, int length, TRAPS) {1963if (array == NULL) {1964THROW_(vmSymbols::java_lang_NullPointerException(), 0);1965}19661967objArrayOop oa = objArrayOop(JNIHandles::resolve_non_null(array));1968objArrayHandle array_h(THREAD, oa);19691970// array must be of the given length1971if (length != array_h->length()) {1972THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),1973"The length of the given MemoryUsage array does not match the number of memory pools.", 0);1974}19751976// check if the element of array is of type MemoryUsage class1977Klass* usage_klass = Management::java_lang_management_MemoryUsage_klass(CHECK_0);1978Klass* element_klass = ObjArrayKlass::cast(array_h->klass())->element_klass();1979if (element_klass != usage_klass) {1980THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),1981"The element type is not MemoryUsage class", 0);1982}19831984return array_h();1985}19861987// Gets the statistics of the last GC of a given GC memory manager.1988// Input parameters:1989// obj - GarbageCollectorMXBean object1990// gc_stat - caller allocated jmmGCStat where:1991// a. before_gc_usage - array of MemoryUsage objects1992// b. after_gc_usage - array of MemoryUsage objects1993// c. gc_ext_attributes_values_size is set to the1994// gc_ext_attribute_values array allocated1995// d. gc_ext_attribute_values is a caller allocated array of jvalue.1996//1997// On return,1998// gc_index == 0 indicates no GC statistics available1999//2000// before_gc_usage and after_gc_usage - filled with per memory pool2001// before and after GC usage in the same order as the memory pools2002// returned by GetMemoryPools for a given GC memory manager.2003// num_gc_ext_attributes indicates the number of elements in2004// the gc_ext_attribute_values array is filled; or2005// -1 if the gc_ext_attributes_values array is not big enough2006//2007JVM_ENTRY(void, jmm_GetLastGCStat(JNIEnv *env, jobject obj, jmmGCStat *gc_stat))2008ResourceMark rm(THREAD);20092010if (gc_stat->gc_ext_attribute_values_size > 0 && gc_stat->gc_ext_attribute_values == NULL) {2011THROW(vmSymbols::java_lang_NullPointerException());2012}20132014// Get the GCMemoryManager2015GCMemoryManager* mgr = get_gc_memory_manager_from_jobject(obj, CHECK);20162017// Make a copy of the last GC statistics2018// GC may occur while constructing the last GC information2019int num_pools = MemoryService::num_memory_pools();2020GCStatInfo stat(num_pools);2021if (mgr->get_last_gc_stat(&stat) == 0) {2022gc_stat->gc_index = 0;2023return;2024}20252026gc_stat->gc_index = stat.gc_index();2027gc_stat->start_time = Management::ticks_to_ms(stat.start_time());2028gc_stat->end_time = Management::ticks_to_ms(stat.end_time());20292030// Current implementation does not have GC extension attributes2031gc_stat->num_gc_ext_attributes = 0;20322033// Fill the arrays of MemoryUsage objects with before and after GC2034// per pool memory usage2035objArrayOop bu = get_memory_usage_objArray(gc_stat->usage_before_gc,2036num_pools,2037CHECK);2038objArrayHandle usage_before_gc_ah(THREAD, bu);20392040objArrayOop au = get_memory_usage_objArray(gc_stat->usage_after_gc,2041num_pools,2042CHECK);2043objArrayHandle usage_after_gc_ah(THREAD, au);20442045for (int i = 0; i < num_pools; i++) {2046Handle before_usage = MemoryService::create_MemoryUsage_obj(stat.before_gc_usage_for_pool(i), CHECK);2047Handle after_usage;20482049MemoryUsage u = stat.after_gc_usage_for_pool(i);2050if (u.max_size() == 0 && u.used() > 0) {2051// If max size == 0, this pool is a survivor space.2052// Set max size = -1 since the pools will be swapped after GC.2053MemoryUsage usage(u.init_size(), u.used(), u.committed(), (size_t)-1);2054after_usage = MemoryService::create_MemoryUsage_obj(usage, CHECK);2055} else {2056after_usage = MemoryService::create_MemoryUsage_obj(stat.after_gc_usage_for_pool(i), CHECK);2057}2058usage_before_gc_ah->obj_at_put(i, before_usage());2059usage_after_gc_ah->obj_at_put(i, after_usage());2060}20612062if (gc_stat->gc_ext_attribute_values_size > 0) {2063// Current implementation only has 1 attribute (number of GC threads)2064// The type is 'I'2065gc_stat->gc_ext_attribute_values[0].i = mgr->num_gc_threads();2066}2067JVM_END20682069JVM_ENTRY(void, jmm_SetGCNotificationEnabled(JNIEnv *env, jobject obj, jboolean enabled))2070ResourceMark rm(THREAD);2071// Get the GCMemoryManager2072GCMemoryManager* mgr = get_gc_memory_manager_from_jobject(obj, CHECK);2073mgr->set_notification_enabled(enabled?true:false);2074JVM_END20752076// Dump heap - Returns 0 if succeeds.2077JVM_ENTRY(jint, jmm_DumpHeap0(JNIEnv *env, jstring outputfile, jboolean live))2078#if INCLUDE_SERVICES2079ResourceMark rm(THREAD);2080oop on = JNIHandles::resolve_external_guard(outputfile);2081if (on == NULL) {2082THROW_MSG_(vmSymbols::java_lang_NullPointerException(),2083"Output file name cannot be null.", -1);2084}2085char* name = java_lang_String::as_platform_dependent_str(on, CHECK_(-1));2086if (name == NULL) {2087THROW_MSG_(vmSymbols::java_lang_NullPointerException(),2088"Output file name cannot be null.", -1);2089}2090HeapDumper dumper(live ? true : false);2091if (dumper.dump(name) != 0) {2092const char* errmsg = dumper.error_as_C_string();2093THROW_MSG_(vmSymbols::java_io_IOException(), errmsg, -1);2094}2095return 0;2096#else // INCLUDE_SERVICES2097return -1;2098#endif // INCLUDE_SERVICES2099JVM_END21002101JVM_ENTRY(jobjectArray, jmm_GetDiagnosticCommands(JNIEnv *env))2102ResourceMark rm(THREAD);2103GrowableArray<const char *>* dcmd_list = DCmdFactory::DCmd_list(DCmd_Source_MBean);2104objArrayOop cmd_array_oop = oopFactory::new_objArray(SystemDictionary::String_klass(),2105dcmd_list->length(), CHECK_NULL);2106objArrayHandle cmd_array(THREAD, cmd_array_oop);2107for (int i = 0; i < dcmd_list->length(); i++) {2108oop cmd_name = java_lang_String::create_oop_from_str(dcmd_list->at(i), CHECK_NULL);2109cmd_array->obj_at_put(i, cmd_name);2110}2111return (jobjectArray) JNIHandles::make_local(env, cmd_array());2112JVM_END21132114JVM_ENTRY(void, jmm_GetDiagnosticCommandInfo(JNIEnv *env, jobjectArray cmds,2115dcmdInfo* infoArray))2116if (cmds == NULL || infoArray == NULL) {2117THROW(vmSymbols::java_lang_NullPointerException());2118}21192120ResourceMark rm(THREAD);21212122objArrayOop ca = objArrayOop(JNIHandles::resolve_non_null(cmds));2123objArrayHandle cmds_ah(THREAD, ca);21242125// Make sure we have a String array2126Klass* element_klass = ObjArrayKlass::cast(cmds_ah->klass())->element_klass();2127if (element_klass != SystemDictionary::String_klass()) {2128THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),2129"Array element type is not String class");2130}21312132GrowableArray<DCmdInfo *>* info_list = DCmdFactory::DCmdInfo_list(DCmd_Source_MBean);21332134int num_cmds = cmds_ah->length();2135for (int i = 0; i < num_cmds; i++) {2136oop cmd = cmds_ah->obj_at(i);2137if (cmd == NULL) {2138THROW_MSG(vmSymbols::java_lang_NullPointerException(),2139"Command name cannot be null.");2140}2141char* cmd_name = java_lang_String::as_utf8_string(cmd);2142if (cmd_name == NULL) {2143THROW_MSG(vmSymbols::java_lang_NullPointerException(),2144"Command name cannot be null.");2145}2146int pos = info_list->find((void*)cmd_name,DCmdInfo::by_name);2147if (pos == -1) {2148THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),2149"Unknown diagnostic command");2150}2151DCmdInfo* info = info_list->at(pos);2152infoArray[i].name = info->name();2153infoArray[i].description = info->description();2154infoArray[i].impact = info->impact();2155JavaPermission p = info->permission();2156infoArray[i].permission_class = p._class;2157infoArray[i].permission_name = p._name;2158infoArray[i].permission_action = p._action;2159infoArray[i].num_arguments = info->num_arguments();2160infoArray[i].enabled = info->is_enabled();2161}2162JVM_END21632164JVM_ENTRY(void, jmm_GetDiagnosticCommandArgumentsInfo(JNIEnv *env,2165jstring command, dcmdArgInfo* infoArray))2166ResourceMark rm(THREAD);2167oop cmd = JNIHandles::resolve_external_guard(command);2168if (cmd == NULL) {2169THROW_MSG(vmSymbols::java_lang_NullPointerException(),2170"Command line cannot be null.");2171}2172char* cmd_name = java_lang_String::as_utf8_string(cmd);2173if (cmd_name == NULL) {2174THROW_MSG(vmSymbols::java_lang_NullPointerException(),2175"Command line content cannot be null.");2176}2177DCmd* dcmd = NULL;2178DCmdFactory*factory = DCmdFactory::factory(DCmd_Source_MBean, cmd_name,2179strlen(cmd_name));2180if (factory != NULL) {2181dcmd = factory->create_resource_instance(NULL);2182}2183if (dcmd == NULL) {2184THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),2185"Unknown diagnostic command");2186}2187DCmdMark mark(dcmd);2188GrowableArray<DCmdArgumentInfo*>* array = dcmd->argument_info_array();2189if (array->length() == 0) {2190return;2191}2192for (int i = 0; i < array->length(); i++) {2193infoArray[i].name = array->at(i)->name();2194infoArray[i].description = array->at(i)->description();2195infoArray[i].type = array->at(i)->type();2196infoArray[i].default_string = array->at(i)->default_string();2197infoArray[i].mandatory = array->at(i)->is_mandatory();2198infoArray[i].option = array->at(i)->is_option();2199infoArray[i].multiple = array->at(i)->is_multiple();2200infoArray[i].position = array->at(i)->position();2201}2202return;2203JVM_END22042205JVM_ENTRY(jstring, jmm_ExecuteDiagnosticCommand(JNIEnv *env, jstring commandline))2206ResourceMark rm(THREAD);2207oop cmd = JNIHandles::resolve_external_guard(commandline);2208if (cmd == NULL) {2209THROW_MSG_NULL(vmSymbols::java_lang_NullPointerException(),2210"Command line cannot be null.");2211}2212char* cmdline = java_lang_String::as_utf8_string(cmd);2213if (cmdline == NULL) {2214THROW_MSG_NULL(vmSymbols::java_lang_NullPointerException(),2215"Command line content cannot be null.");2216}2217bufferedStream output;2218DCmd::parse_and_execute(DCmd_Source_MBean, &output, cmdline, ' ', CHECK_NULL);2219oop result = java_lang_String::create_oop_from_str(output.as_string(), CHECK_NULL);2220return (jstring) JNIHandles::make_local(env, result);2221JVM_END22222223JVM_ENTRY(void, jmm_SetDiagnosticFrameworkNotificationEnabled(JNIEnv *env, jboolean enabled))2224DCmdFactory::set_jmx_notification_enabled(enabled?true:false);2225JVM_END22262227jlong Management::ticks_to_ms(jlong ticks) {2228assert(os::elapsed_frequency() > 0, "Must be non-zero");2229return (jlong)(((double)ticks / (double)os::elapsed_frequency())2230* (double)1000.0);2231}2232#endif // INCLUDE_MANAGEMENT22332234// Gets the amount of memory allocated on the Java heap for a single thread.2235// Returns -1 if the thread does not exist or has terminated.2236JVM_ENTRY(jlong, jmm_GetOneThreadAllocatedMemory(JNIEnv *env, jlong thread_id))2237if (thread_id < 0) {2238THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),2239"Invalid thread ID", -1);2240}22412242if (thread_id == 0) {2243// current thread2244if (THREAD->is_Java_thread()) {2245return ((JavaThread*)THREAD)->cooked_allocated_bytes();2246}2247return -1;2248}22492250MutexLockerEx ml(Threads_lock);2251JavaThread* java_thread = Threads::find_java_thread_from_java_tid(thread_id);22522253if (java_thread != NULL) {2254return java_thread->cooked_allocated_bytes();2255}2256return -1;2257JVM_END22582259// Gets an array containing the amount of memory allocated on the Java2260// heap for a set of threads (in bytes). Each element of the array is2261// the amount of memory allocated for the thread ID specified in the2262// corresponding entry in the given array of thread IDs; or -1 if the2263// thread does not exist or has terminated.2264JVM_ENTRY(void, jmm_GetThreadAllocatedMemory(JNIEnv *env, jlongArray ids,2265jlongArray sizeArray))2266// Check if threads is null2267if (ids == NULL || sizeArray == NULL) {2268THROW(vmSymbols::java_lang_NullPointerException());2269}22702271ResourceMark rm(THREAD);2272typeArrayOop ta = typeArrayOop(JNIHandles::resolve_non_null(ids));2273typeArrayHandle ids_ah(THREAD, ta);22742275typeArrayOop sa = typeArrayOop(JNIHandles::resolve_non_null(sizeArray));2276typeArrayHandle sizeArray_h(THREAD, sa);22772278// validate the thread id array2279validate_thread_id_array(ids_ah, CHECK);22802281// sizeArray must be of the same length as the given array of thread IDs2282int num_threads = ids_ah->length();2283if (num_threads != sizeArray_h->length()) {2284THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),2285"The length of the given long array does not match the length of "2286"the given array of thread IDs");2287}22882289MutexLockerEx ml(Threads_lock);2290for (int i = 0; i < num_threads; i++) {2291JavaThread* java_thread = Threads::find_java_thread_from_java_tid(ids_ah->long_at(i));2292if (java_thread != NULL) {2293sizeArray_h->long_at_put(i, java_thread->cooked_allocated_bytes());2294}2295}2296JVM_END22972298// Returns the CPU time consumed by a given thread (in nanoseconds).2299// If thread_id == 0, CPU time for the current thread is returned.2300// If user_sys_cpu_time = true, user level and system CPU time of2301// a given thread is returned; otherwise, only user level CPU time2302// is returned.2303JVM_ENTRY(jlong, jmm_GetThreadCpuTimeWithKind(JNIEnv *env, jlong thread_id, jboolean user_sys_cpu_time))2304if (!os::is_thread_cpu_time_supported()) {2305return -1;2306}23072308if (thread_id < 0) {2309THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),2310"Invalid thread ID", -1);2311}23122313JavaThread* java_thread = NULL;2314if (thread_id == 0) {2315// current thread2316return os::current_thread_cpu_time(user_sys_cpu_time != 0);2317} else {2318MutexLockerEx ml(Threads_lock);2319java_thread = Threads::find_java_thread_from_java_tid(thread_id);2320if (java_thread != NULL) {2321return os::thread_cpu_time((Thread*) java_thread, user_sys_cpu_time != 0);2322}2323}2324return -1;2325JVM_END23262327// Gets an array containing the CPU times consumed by a set of threads2328// (in nanoseconds). Each element of the array is the CPU time for the2329// thread ID specified in the corresponding entry in the given array2330// of thread IDs; or -1 if the thread does not exist or has terminated.2331// If user_sys_cpu_time = true, the sum of user level and system CPU time2332// for the given thread is returned; otherwise, only user level CPU time2333// is returned.2334JVM_ENTRY(void, jmm_GetThreadCpuTimesWithKind(JNIEnv *env, jlongArray ids,2335jlongArray timeArray,2336jboolean user_sys_cpu_time))2337// Check if threads is null2338if (ids == NULL || timeArray == NULL) {2339THROW(vmSymbols::java_lang_NullPointerException());2340}23412342ResourceMark rm(THREAD);2343typeArrayOop ta = typeArrayOop(JNIHandles::resolve_non_null(ids));2344typeArrayHandle ids_ah(THREAD, ta);23452346typeArrayOop tia = typeArrayOop(JNIHandles::resolve_non_null(timeArray));2347typeArrayHandle timeArray_h(THREAD, tia);23482349// validate the thread id array2350validate_thread_id_array(ids_ah, CHECK);23512352// timeArray must be of the same length as the given array of thread IDs2353int num_threads = ids_ah->length();2354if (num_threads != timeArray_h->length()) {2355THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),2356"The length of the given long array does not match the length of "2357"the given array of thread IDs");2358}23592360MutexLockerEx ml(Threads_lock);2361for (int i = 0; i < num_threads; i++) {2362JavaThread* java_thread = Threads::find_java_thread_from_java_tid(ids_ah->long_at(i));2363if (java_thread != NULL) {2364timeArray_h->long_at_put(i, os::thread_cpu_time((Thread*)java_thread,2365user_sys_cpu_time != 0));2366}2367}2368JVM_END2369237023712372#if INCLUDE_MANAGEMENT2373const struct jmmInterface_1_ jmm_interface = {2374NULL,2375jmm_GetOneThreadAllocatedMemory,2376jmm_GetVersion,2377jmm_GetOptionalSupport,2378jmm_GetInputArguments,2379jmm_GetThreadInfo,2380jmm_GetInputArgumentArray,2381jmm_GetMemoryPools,2382jmm_GetMemoryManagers,2383jmm_GetMemoryPoolUsage,2384jmm_GetPeakMemoryPoolUsage,2385jmm_GetThreadAllocatedMemory,2386jmm_GetMemoryUsage,2387jmm_GetLongAttribute,2388jmm_GetBoolAttribute,2389jmm_SetBoolAttribute,2390jmm_GetLongAttributes,2391jmm_FindMonitorDeadlockedThreads,2392jmm_GetThreadCpuTime,2393jmm_GetVMGlobalNames,2394jmm_GetVMGlobals,2395jmm_GetInternalThreadTimes,2396jmm_ResetStatistic,2397jmm_SetPoolSensor,2398jmm_SetPoolThreshold,2399jmm_GetPoolCollectionUsage,2400jmm_GetGCExtAttributeInfo,2401jmm_GetLastGCStat,2402jmm_GetThreadCpuTimeWithKind,2403jmm_GetThreadCpuTimesWithKind,2404jmm_DumpHeap0,2405jmm_FindDeadlockedThreads,2406jmm_SetVMGlobal,2407jmm_DumpThreadsMaxDepth,2408jmm_DumpThreads,2409jmm_SetGCNotificationEnabled,2410jmm_GetDiagnosticCommands,2411jmm_GetDiagnosticCommandInfo,2412jmm_GetDiagnosticCommandArgumentsInfo,2413jmm_ExecuteDiagnosticCommand,2414jmm_SetDiagnosticFrameworkNotificationEnabled2415};2416#endif // INCLUDE_MANAGEMENT24172418void* Management::get_jmm_interface(int version) {2419#if INCLUDE_MANAGEMENT2420if (version == JMM_VERSION_1_0) {2421return (void*) &jmm_interface;2422}2423#endif // INCLUDE_MANAGEMENT2424return NULL;2425}242624272428