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