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