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