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