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