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