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