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