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, 1164 jboolean locked_synchronizers, jint maxDepth)) 1165 ResourceMark rm(THREAD); 1166 1167 // make sure the AbstractOwnableSynchronizer klass is loaded before taking thread snapshots 1168 java_util_concurrent_locks_AbstractOwnableSynchronizer::initialize(CHECK_NULL); 1169 1170 typeArrayOop ta = typeArrayOop(JNIHandles::resolve(thread_ids)); 1171 int num_threads = (ta != NULL ? ta->length() : 0); 1172 typeArrayHandle ids_ah(THREAD, ta); 1173 1174 ThreadDumpResult dump_result(num_threads); // can safepoint 1175 1176 if (ids_ah() != NULL) { 1177 1178 // validate the thread id array 1179 validate_thread_id_array(ids_ah, CHECK_NULL); 1180 1181 // obtain thread dump of a specific list of threads 1182 do_thread_dump(&dump_result, 1183 ids_ah, 1184 num_threads, 1185 maxDepth, /* stack depth */ 1186 (locked_monitors ? true : false), /* with locked monitors */ 1187 (locked_synchronizers ? true : false), /* with locked synchronizers */ 1188 CHECK_NULL); 1189 } else { 1190 // obtain thread dump of all threads 1191 VM_ThreadDump op(&dump_result, 1192 maxDepth, /* stack depth */ 1193 (locked_monitors ? true : false), /* with locked monitors */ 1194 (locked_synchronizers ? true : false) /* with locked synchronizers */); 1195 VMThread::execute(&op); 1196 } 1197 1198 int num_snapshots = dump_result.num_snapshots(); 1199 1200 // create the result ThreadInfo[] object 1201 InstanceKlass* ik = Management::java_lang_management_ThreadInfo_klass(CHECK_NULL); 1202 objArrayOop r = oopFactory::new_objArray(ik, num_snapshots, CHECK_NULL); 1203 objArrayHandle result_h(THREAD, r); 1204 1205 int index = 0; 1206 for (ThreadSnapshot* ts = dump_result.snapshots(); ts != NULL; ts = ts->next(), index++) { 1207 if (ts->threadObj() == NULL) { 1208 // if the thread does not exist or now it is terminated, set threadinfo to NULL 1209 result_h->obj_at_put(index, NULL); 1210 continue; 1211 } 1212 1213 ThreadStackTrace* stacktrace = ts->get_stack_trace(); 1214 assert(stacktrace != NULL, "Must have a stack trace dumped"); 1215 1216 // Create Object[] filled with locked monitors 1217 // Create int[] filled with the stack depth where a monitor was locked 1218 int num_frames = stacktrace->get_stack_depth(); 1219 int num_locked_monitors = stacktrace->num_jni_locked_monitors(); 1220 1221 // Count the total number of locked monitors 1222 for (int i = 0; i < num_frames; i++) { 1223 StackFrameInfo* frame = stacktrace->stack_frame_at(i); 1224 num_locked_monitors += frame->num_locked_monitors(); 1225 } 1226 1227 objArrayHandle monitors_array; 1228 typeArrayHandle depths_array; 1229 objArrayHandle synchronizers_array; 1230 1231 if (locked_monitors) { 1232 // Constructs Object[] and int[] to contain the object monitor and the stack depth 1233 // where the thread locked it 1234 objArrayOop array = oopFactory::new_objArray(SystemDictionary::Object_klass(), num_locked_monitors, CHECK_NULL); 1235 objArrayHandle mh(THREAD, array); 1236 monitors_array = mh; 1237 1238 typeArrayOop tarray = oopFactory::new_typeArray(T_INT, num_locked_monitors, CHECK_NULL); 1239 typeArrayHandle dh(THREAD, tarray); 1240 depths_array = dh; 1241 1242 int count = 0; 1243 int j = 0; 1244 for (int depth = 0; depth < num_frames; depth++) { 1245 StackFrameInfo* frame = stacktrace->stack_frame_at(depth); 1246 int len = frame->num_locked_monitors(); 1247 GrowableArray<oop>* locked_monitors = frame->locked_monitors(); 1248 for (j = 0; j < len; j++) { 1249 oop monitor = locked_monitors->at(j); 1250 assert(monitor != NULL, "must be a Java object"); 1251 monitors_array->obj_at_put(count, monitor); 1252 depths_array->int_at_put(count, depth); 1253 count++; 1254 } 1255 } 1256 1257 GrowableArray<oop>* jni_locked_monitors = stacktrace->jni_locked_monitors(); 1258 for (j = 0; j < jni_locked_monitors->length(); j++) { 1259 oop object = jni_locked_monitors->at(j); 1260 assert(object != NULL, "must be a Java object"); 1261 monitors_array->obj_at_put(count, object); 1262 // Monitor locked via JNI MonitorEnter call doesn't have stack depth info 1263 depths_array->int_at_put(count, -1); 1264 count++; 1265 } 1266 assert(count == num_locked_monitors, "number of locked monitors doesn't match"); 1267 } 1268 1269 if (locked_synchronizers) { 1270 // Create Object[] filled with locked JSR-166 synchronizers 1271 assert(ts->threadObj() != NULL, "Must be a valid JavaThread"); 1272 ThreadConcurrentLocks* tcl = ts->get_concurrent_locks(); 1273 GrowableArray<instanceOop>* locks = (tcl != NULL ? tcl->owned_locks() : NULL); 1274 int num_locked_synchronizers = (locks != NULL ? locks->length() : 0); 1275 1276 objArrayOop array = oopFactory::new_objArray(SystemDictionary::Object_klass(), num_locked_synchronizers, CHECK_NULL); 1277 objArrayHandle sh(THREAD, array); 1278 synchronizers_array = sh; 1279 1280 for (int k = 0; k < num_locked_synchronizers; k++) { 1281 synchronizers_array->obj_at_put(k, locks->at(k)); 1282 } 1283 } 1284 1285 // Create java.lang.management.ThreadInfo object 1286 instanceOop info_obj = Management::create_thread_info_instance(ts, 1287 monitors_array, 1288 depths_array, 1289 synchronizers_array, 1290 CHECK_NULL); 1291 result_h->obj_at_put(index, info_obj); 1292 } 1293 1294 return (jobjectArray) JNIHandles::make_local(env, result_h()); 1295 JVM_END 1296 1297 // Reset statistic. Return true if the requested statistic is reset. 1298 // Otherwise, return false. 1299 // 1300 // Input parameters: 1301 // obj - specify which instance the statistic associated with to be reset 1302 // For PEAK_POOL_USAGE stat, obj is required to be a memory pool object. 1303 // For THREAD_CONTENTION_COUNT and TIME stat, obj is required to be a thread ID. 1304 // type - the type of statistic to be reset 1305 // 1306 JVM_ENTRY(jboolean, jmm_ResetStatistic(JNIEnv *env, jvalue obj, jmmStatisticType type)) 1307 ResourceMark rm(THREAD); 1308 1309 switch (type) { 1310 case JMM_STAT_PEAK_THREAD_COUNT: 1311 ThreadService::reset_peak_thread_count(); 1312 return true; 1313 1314 case JMM_STAT_THREAD_CONTENTION_COUNT: 1315 case JMM_STAT_THREAD_CONTENTION_TIME: { 1316 jlong tid = obj.j; 1317 if (tid < 0) { 1318 THROW_(vmSymbols::java_lang_IllegalArgumentException(), JNI_FALSE); 1319 } 1320 1321 // Look for the JavaThread of this given tid 1322 MutexLockerEx ml(Threads_lock); 1323 if (tid == 0) { 1324 // reset contention statistics for all threads if tid == 0 1325 for (JavaThread* java_thread = Threads::first(); java_thread != NULL; java_thread = java_thread->next()) { 1326 if (type == JMM_STAT_THREAD_CONTENTION_COUNT) { 1327 ThreadService::reset_contention_count_stat(java_thread); 1328 } else { 1329 ThreadService::reset_contention_time_stat(java_thread); 1330 } 1331 } 1332 } else { 1333 // reset contention statistics for a given thread 1334 JavaThread* java_thread = Threads::find_java_thread_from_java_tid(tid); 1335 if (java_thread == NULL) { 1336 return false; 1337 } 1338 1339 if (type == JMM_STAT_THREAD_CONTENTION_COUNT) { 1340 ThreadService::reset_contention_count_stat(java_thread); 1341 } else { 1342 ThreadService::reset_contention_time_stat(java_thread); 1343 } 1344 } 1345 return true; 1346 break; 1347 } 1348 case JMM_STAT_PEAK_POOL_USAGE: { 1349 jobject o = obj.l; 1350 if (o == NULL) { 1351 THROW_(vmSymbols::java_lang_NullPointerException(), JNI_FALSE); 1352 } 1353 1354 oop pool_obj = JNIHandles::resolve(o); 1355 assert(pool_obj->is_instance(), "Should be an instanceOop"); 1356 instanceHandle ph(THREAD, (instanceOop) pool_obj); 1357 1358 MemoryPool* pool = MemoryService::get_memory_pool(ph); 1359 if (pool != NULL) { 1360 pool->reset_peak_memory_usage(); 1361 return true; 1362 } 1363 break; 1364 } 1365 case JMM_STAT_GC_STAT: { 1366 jobject o = obj.l; 1367 if (o == NULL) { 1368 THROW_(vmSymbols::java_lang_NullPointerException(), JNI_FALSE); 1369 } 1370 1371 GCMemoryManager* mgr = get_gc_memory_manager_from_jobject(o, CHECK_0); 1372 if (mgr != NULL) { 1373 mgr->reset_gc_stat(); 1374 return true; 1375 } 1376 break; 1377 } 1378 default: 1379 assert(0, "Unknown Statistic Type"); 1380 } 1381 return false; 1382 JVM_END 1383 1384 // Returns the fast estimate of CPU time consumed by 1385 // a given thread (in nanoseconds). 1386 // If thread_id == 0, return CPU time for the current thread. 1387 JVM_ENTRY(jlong, jmm_GetThreadCpuTime(JNIEnv *env, jlong thread_id)) 1388 if (!os::is_thread_cpu_time_supported()) { 1389 return -1; 1390 } 1391 1392 if (thread_id < 0) { 1393 THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(), 1394 "Invalid thread ID", -1); 1395 } 1396 1397 JavaThread* java_thread = NULL; 1398 if (thread_id == 0) { 1399 // current thread 1400 return os::current_thread_cpu_time(); 1401 } else { 1402 MutexLockerEx ml(Threads_lock); 1403 java_thread = Threads::find_java_thread_from_java_tid(thread_id); 1404 if (java_thread != NULL) { 1405 return os::thread_cpu_time((Thread*) java_thread); 1406 } 1407 } 1408 return -1; 1409 JVM_END 1410 1411 // Returns a String array of all VM global flag names 1412 JVM_ENTRY(jobjectArray, jmm_GetVMGlobalNames(JNIEnv *env)) 1413 // last flag entry is always NULL, so subtract 1 1414 int nFlags = (int) Flag::numFlags - 1; 1415 // allocate a temp array 1416 objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(), 1417 nFlags, CHECK_0); 1418 objArrayHandle flags_ah(THREAD, r); 1419 int num_entries = 0; 1420 for (int i = 0; i < nFlags; i++) { 1421 Flag* flag = &Flag::flags[i]; 1422 // Exclude notproduct and develop flags in product builds. 1423 if (flag->is_constant_in_binary()) { 1424 continue; 1425 } 1426 // Exclude the locked (experimental, diagnostic) flags 1427 if (flag->is_unlocked() || flag->is_unlocker()) { 1428 Handle s = java_lang_String::create_from_str(flag->_name, CHECK_0); 1429 flags_ah->obj_at_put(num_entries, s()); 1430 num_entries++; 1431 } 1432 } 1433 1434 if (num_entries < nFlags) { 1435 // Return array of right length 1436 objArrayOop res = oopFactory::new_objArray(SystemDictionary::String_klass(), num_entries, CHECK_0); 1437 for(int i = 0; i < num_entries; i++) { 1438 res->obj_at_put(i, flags_ah->obj_at(i)); 1439 } 1440 return (jobjectArray)JNIHandles::make_local(env, res); 1441 } 1442 1443 return (jobjectArray)JNIHandles::make_local(env, flags_ah()); 1444 JVM_END 1445 1446 // Utility function used by jmm_GetVMGlobals. Returns false if flag type 1447 // can't be determined, true otherwise. If false is returned, then *global 1448 // will be incomplete and invalid. 1449 bool add_global_entry(JNIEnv* env, Handle name, jmmVMGlobal *global, Flag *flag, TRAPS) { 1450 Handle flag_name; 1451 if (name() == NULL) { 1452 flag_name = java_lang_String::create_from_str(flag->_name, CHECK_false); 1453 } else { 1454 flag_name = name; 1455 } 1456 global->name = (jstring)JNIHandles::make_local(env, flag_name()); 1457 1458 if (flag->is_bool()) { 1459 global->value.z = flag->get_bool() ? JNI_TRUE : JNI_FALSE; 1460 global->type = JMM_VMGLOBAL_TYPE_JBOOLEAN; 1461 } else if (flag->is_int()) { 1462 global->value.j = (jlong)flag->get_int(); 1463 global->type = JMM_VMGLOBAL_TYPE_JLONG; 1464 } else if (flag->is_uint()) { 1465 global->value.j = (jlong)flag->get_uint(); 1466 global->type = JMM_VMGLOBAL_TYPE_JLONG; 1467 } else if (flag->is_intx()) { 1468 global->value.j = (jlong)flag->get_intx(); 1469 global->type = JMM_VMGLOBAL_TYPE_JLONG; 1470 } else if (flag->is_uintx()) { 1471 global->value.j = (jlong)flag->get_uintx(); 1472 global->type = JMM_VMGLOBAL_TYPE_JLONG; 1473 } else if (flag->is_uint64_t()) { 1474 global->value.j = (jlong)flag->get_uint64_t(); 1475 global->type = JMM_VMGLOBAL_TYPE_JLONG; 1476 } else if (flag->is_double()) { 1477 global->value.d = (jdouble)flag->get_double(); 1478 global->type = JMM_VMGLOBAL_TYPE_JDOUBLE; 1479 } else if (flag->is_size_t()) { 1480 global->value.j = (jlong)flag->get_size_t(); 1481 global->type = JMM_VMGLOBAL_TYPE_JLONG; 1482 } else if (flag->is_ccstr()) { 1483 Handle str = java_lang_String::create_from_str(flag->get_ccstr(), CHECK_false); 1484 global->value.l = (jobject)JNIHandles::make_local(env, str()); 1485 global->type = JMM_VMGLOBAL_TYPE_JSTRING; 1486 } else { 1487 global->type = JMM_VMGLOBAL_TYPE_UNKNOWN; 1488 return false; 1489 } 1490 1491 global->writeable = flag->is_writeable(); 1492 global->external = flag->is_external(); 1493 switch (flag->get_origin()) { 1494 case Flag::DEFAULT: 1495 global->origin = JMM_VMGLOBAL_ORIGIN_DEFAULT; 1496 break; 1497 case Flag::COMMAND_LINE: 1498 global->origin = JMM_VMGLOBAL_ORIGIN_COMMAND_LINE; 1499 break; 1500 case Flag::ENVIRON_VAR: 1501 global->origin = JMM_VMGLOBAL_ORIGIN_ENVIRON_VAR; 1502 break; 1503 case Flag::CONFIG_FILE: 1504 global->origin = JMM_VMGLOBAL_ORIGIN_CONFIG_FILE; 1505 break; 1506 case Flag::MANAGEMENT: 1507 global->origin = JMM_VMGLOBAL_ORIGIN_MANAGEMENT; 1508 break; 1509 case Flag::ERGONOMIC: 1510 global->origin = JMM_VMGLOBAL_ORIGIN_ERGONOMIC; 1511 break; 1512 case Flag::ATTACH_ON_DEMAND: 1513 global->origin = JMM_VMGLOBAL_ORIGIN_ATTACH_ON_DEMAND; 1514 break; 1515 default: 1516 global->origin = JMM_VMGLOBAL_ORIGIN_OTHER; 1517 } 1518 1519 return true; 1520 } 1521 1522 // Fill globals array of count length with jmmVMGlobal entries 1523 // specified by names. If names == NULL, fill globals array 1524 // with all Flags. Return value is number of entries 1525 // created in globals. 1526 // If a Flag with a given name in an array element does not 1527 // exist, globals[i].name will be set to NULL. 1528 JVM_ENTRY(jint, jmm_GetVMGlobals(JNIEnv *env, 1529 jobjectArray names, 1530 jmmVMGlobal *globals, 1531 jint count)) 1532 1533 1534 if (globals == NULL) { 1535 THROW_(vmSymbols::java_lang_NullPointerException(), 0); 1536 } 1537 1538 ResourceMark rm(THREAD); 1539 1540 if (names != NULL) { 1541 // return the requested globals 1542 objArrayOop ta = objArrayOop(JNIHandles::resolve_non_null(names)); 1543 objArrayHandle names_ah(THREAD, ta); 1544 // Make sure we have a String array 1545 Klass* element_klass = ObjArrayKlass::cast(names_ah->klass())->element_klass(); 1546 if (element_klass != SystemDictionary::String_klass()) { 1547 THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(), 1548 "Array element type is not String class", 0); 1549 } 1550 1551 int names_length = names_ah->length(); 1552 int num_entries = 0; 1553 for (int i = 0; i < names_length && i < count; i++) { 1554 oop s = names_ah->obj_at(i); 1555 if (s == NULL) { 1556 THROW_(vmSymbols::java_lang_NullPointerException(), 0); 1557 } 1558 1559 Handle sh(THREAD, s); 1560 char* str = java_lang_String::as_utf8_string(s); 1561 Flag* flag = Flag::find_flag(str, strlen(str)); 1562 if (flag != NULL && 1563 add_global_entry(env, sh, &globals[i], flag, THREAD)) { 1564 num_entries++; 1565 } else { 1566 globals[i].name = NULL; 1567 } 1568 } 1569 return num_entries; 1570 } else { 1571 // return all globals if names == NULL 1572 1573 // last flag entry is always NULL, so subtract 1 1574 int nFlags = (int) Flag::numFlags - 1; 1575 Handle null_h; 1576 int num_entries = 0; 1577 for (int i = 0; i < nFlags && num_entries < count; i++) { 1578 Flag* flag = &Flag::flags[i]; 1579 // Exclude notproduct and develop flags in product builds. 1580 if (flag->is_constant_in_binary()) { 1581 continue; 1582 } 1583 // Exclude the locked (diagnostic, experimental) flags 1584 if ((flag->is_unlocked() || flag->is_unlocker()) && 1585 add_global_entry(env, null_h, &globals[num_entries], flag, THREAD)) { 1586 num_entries++; 1587 } 1588 } 1589 return num_entries; 1590 } 1591 JVM_END 1592 1593 JVM_ENTRY(void, jmm_SetVMGlobal(JNIEnv *env, jstring flag_name, jvalue new_value)) 1594 ResourceMark rm(THREAD); 1595 1596 oop fn = JNIHandles::resolve_external_guard(flag_name); 1597 if (fn == NULL) { 1598 THROW_MSG(vmSymbols::java_lang_NullPointerException(), 1599 "The flag name cannot be null."); 1600 } 1601 char* name = java_lang_String::as_utf8_string(fn); 1602 1603 FormatBuffer<80> error_msg("%s", ""); 1604 int succeed = WriteableFlags::set_flag(name, new_value, Flag::MANAGEMENT, error_msg); 1605 1606 if (succeed != Flag::SUCCESS) { 1607 if (succeed == Flag::MISSING_VALUE) { 1608 // missing value causes NPE to be thrown 1609 THROW(vmSymbols::java_lang_NullPointerException()); 1610 } else { 1611 // all the other errors are reported as IAE with the appropriate error message 1612 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), 1613 error_msg.buffer()); 1614 } 1615 } 1616 assert(succeed == Flag::SUCCESS, "Setting flag should succeed"); 1617 JVM_END 1618 1619 class ThreadTimesClosure: public ThreadClosure { 1620 private: 1621 objArrayHandle _names_strings; 1622 char **_names_chars; 1623 typeArrayHandle _times; 1624 int _names_len; 1625 int _times_len; 1626 int _count; 1627 1628 public: 1629 ThreadTimesClosure(objArrayHandle names, typeArrayHandle times); 1630 ~ThreadTimesClosure(); 1631 virtual void do_thread(Thread* thread); 1632 void do_unlocked(); 1633 int count() { return _count; } 1634 }; 1635 1636 ThreadTimesClosure::ThreadTimesClosure(objArrayHandle names, 1637 typeArrayHandle times) { 1638 assert(names() != NULL, "names was NULL"); 1639 assert(times() != NULL, "times was NULL"); 1640 _names_strings = names; 1641 _names_len = names->length(); 1642 _names_chars = NEW_C_HEAP_ARRAY(char*, _names_len, mtInternal); 1643 _times = times; 1644 _times_len = times->length(); 1645 _count = 0; 1646 } 1647 1648 // 1649 // Called with Threads_lock held 1650 // 1651 void ThreadTimesClosure::do_thread(Thread* thread) { 1652 assert(thread != NULL, "thread was NULL"); 1653 1654 // exclude externally visible JavaThreads 1655 if (thread->is_Java_thread() && !thread->is_hidden_from_external_view()) { 1656 return; 1657 } 1658 1659 if (_count >= _names_len || _count >= _times_len) { 1660 // skip if the result array is not big enough 1661 return; 1662 } 1663 1664 EXCEPTION_MARK; 1665 ResourceMark rm(THREAD); // thread->name() uses ResourceArea 1666 1667 assert(thread->name() != NULL, "All threads should have a name"); 1668 _names_chars[_count] = os::strdup(thread->name()); 1669 _times->long_at_put(_count, os::is_thread_cpu_time_supported() ? 1670 os::thread_cpu_time(thread) : -1); 1671 _count++; 1672 } 1673 1674 // Called without Threads_lock, we can allocate String objects. 1675 void ThreadTimesClosure::do_unlocked() { 1676 1677 EXCEPTION_MARK; 1678 for (int i = 0; i < _count; i++) { 1679 Handle s = java_lang_String::create_from_str(_names_chars[i], CHECK); 1680 _names_strings->obj_at_put(i, s()); 1681 } 1682 } 1683 1684 ThreadTimesClosure::~ThreadTimesClosure() { 1685 for (int i = 0; i < _count; i++) { 1686 os::free(_names_chars[i]); 1687 } 1688 FREE_C_HEAP_ARRAY(char *, _names_chars); 1689 } 1690 1691 // Fills names with VM internal thread names and times with the corresponding 1692 // CPU times. If names or times is NULL, a NullPointerException is thrown. 1693 // If the element type of names is not String, an IllegalArgumentException is 1694 // thrown. 1695 // If an array is not large enough to hold all the entries, only the entries 1696 // that fit will be returned. Return value is the number of VM internal 1697 // threads entries. 1698 JVM_ENTRY(jint, jmm_GetInternalThreadTimes(JNIEnv *env, 1699 jobjectArray names, 1700 jlongArray times)) 1701 if (names == NULL || times == NULL) { 1702 THROW_(vmSymbols::java_lang_NullPointerException(), 0); 1703 } 1704 objArrayOop na = objArrayOop(JNIHandles::resolve_non_null(names)); 1705 objArrayHandle names_ah(THREAD, na); 1706 1707 // Make sure we have a String array 1708 Klass* element_klass = ObjArrayKlass::cast(names_ah->klass())->element_klass(); 1709 if (element_klass != SystemDictionary::String_klass()) { 1710 THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(), 1711 "Array element type is not String class", 0); 1712 } 1713 1714 typeArrayOop ta = typeArrayOop(JNIHandles::resolve_non_null(times)); 1715 typeArrayHandle times_ah(THREAD, ta); 1716 1717 ThreadTimesClosure ttc(names_ah, times_ah); 1718 { 1719 MutexLockerEx ml(Threads_lock); 1720 Threads::threads_do(&ttc); 1721 } 1722 ttc.do_unlocked(); 1723 return ttc.count(); 1724 JVM_END 1725 1726 static Handle find_deadlocks(bool object_monitors_only, TRAPS) { 1727 ResourceMark rm(THREAD); 1728 1729 VM_FindDeadlocks op(!object_monitors_only /* also check concurrent locks? */); 1730 VMThread::execute(&op); 1731 1732 DeadlockCycle* deadlocks = op.result(); 1733 if (deadlocks == NULL) { 1734 // no deadlock found and return 1735 return Handle(); 1736 } 1737 1738 int num_threads = 0; 1739 DeadlockCycle* cycle; 1740 for (cycle = deadlocks; cycle != NULL; cycle = cycle->next()) { 1741 num_threads += cycle->num_threads(); 1742 } 1743 1744 objArrayOop r = oopFactory::new_objArray(SystemDictionary::Thread_klass(), num_threads, CHECK_NH); 1745 objArrayHandle threads_ah(THREAD, r); 1746 1747 int index = 0; 1748 for (cycle = deadlocks; cycle != NULL; cycle = cycle->next()) { 1749 GrowableArray<JavaThread*>* deadlock_threads = cycle->threads(); 1750 int len = deadlock_threads->length(); 1751 for (int i = 0; i < len; i++) { 1752 threads_ah->obj_at_put(index, deadlock_threads->at(i)->threadObj()); 1753 index++; 1754 } 1755 } 1756 return threads_ah; 1757 } 1758 1759 // Finds cycles of threads that are deadlocked involved in object monitors 1760 // and JSR-166 synchronizers. 1761 // Returns an array of Thread objects which are in deadlock, if any. 1762 // Otherwise, returns NULL. 1763 // 1764 // Input parameter: 1765 // object_monitors_only - if true, only check object monitors 1766 // 1767 JVM_ENTRY(jobjectArray, jmm_FindDeadlockedThreads(JNIEnv *env, jboolean object_monitors_only)) 1768 Handle result = find_deadlocks(object_monitors_only != 0, CHECK_0); 1769 return (jobjectArray) JNIHandles::make_local(env, result()); 1770 JVM_END 1771 1772 // Finds cycles of threads that are deadlocked on monitor locks 1773 // Returns an array of Thread objects which are in deadlock, if any. 1774 // Otherwise, returns NULL. 1775 JVM_ENTRY(jobjectArray, jmm_FindMonitorDeadlockedThreads(JNIEnv *env)) 1776 Handle result = find_deadlocks(true, CHECK_0); 1777 return (jobjectArray) JNIHandles::make_local(env, result()); 1778 JVM_END 1779 1780 // Gets the information about GC extension attributes including 1781 // the name of the attribute, its type, and a short description. 1782 // 1783 // Input parameters: 1784 // mgr - GC memory manager 1785 // info - caller allocated array of jmmExtAttributeInfo 1786 // count - number of elements of the info array 1787 // 1788 // Returns the number of GC extension attributes filled in the info array; or 1789 // -1 if info is not big enough 1790 // 1791 JVM_ENTRY(jint, jmm_GetGCExtAttributeInfo(JNIEnv *env, jobject mgr, jmmExtAttributeInfo* info, jint count)) 1792 // All GC memory managers have 1 attribute (number of GC threads) 1793 if (count == 0) { 1794 return 0; 1795 } 1796 1797 if (info == NULL) { 1798 THROW_(vmSymbols::java_lang_NullPointerException(), 0); 1799 } 1800 1801 info[0].name = "GcThreadCount"; 1802 info[0].type = 'I'; 1803 info[0].description = "Number of GC threads"; 1804 return 1; 1805 JVM_END 1806 1807 // verify the given array is an array of java/lang/management/MemoryUsage objects 1808 // of a given length and return the objArrayOop 1809 static objArrayOop get_memory_usage_objArray(jobjectArray array, int length, TRAPS) { 1810 if (array == NULL) { 1811 THROW_(vmSymbols::java_lang_NullPointerException(), 0); 1812 } 1813 1814 objArrayOop oa = objArrayOop(JNIHandles::resolve_non_null(array)); 1815 objArrayHandle array_h(THREAD, oa); 1816 1817 // array must be of the given length 1818 if (length != array_h->length()) { 1819 THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(), 1820 "The length of the given MemoryUsage array does not match the number of memory pools.", 0); 1821 } 1822 1823 // check if the element of array is of type MemoryUsage class 1824 Klass* usage_klass = Management::java_lang_management_MemoryUsage_klass(CHECK_0); 1825 Klass* element_klass = ObjArrayKlass::cast(array_h->klass())->element_klass(); 1826 if (element_klass != usage_klass) { 1827 THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(), 1828 "The element type is not MemoryUsage class", 0); 1829 } 1830 1831 return array_h(); 1832 } 1833 1834 // Gets the statistics of the last GC of a given GC memory manager. 1835 // Input parameters: 1836 // obj - GarbageCollectorMXBean object 1837 // gc_stat - caller allocated jmmGCStat where: 1838 // a. before_gc_usage - array of MemoryUsage objects 1839 // b. after_gc_usage - array of MemoryUsage objects 1840 // c. gc_ext_attributes_values_size is set to the 1841 // gc_ext_attribute_values array allocated 1842 // d. gc_ext_attribute_values is a caller allocated array of jvalue. 1843 // 1844 // On return, 1845 // gc_index == 0 indicates no GC statistics available 1846 // 1847 // before_gc_usage and after_gc_usage - filled with per memory pool 1848 // before and after GC usage in the same order as the memory pools 1849 // returned by GetMemoryPools for a given GC memory manager. 1850 // num_gc_ext_attributes indicates the number of elements in 1851 // the gc_ext_attribute_values array is filled; or 1852 // -1 if the gc_ext_attributes_values array is not big enough 1853 // 1854 JVM_ENTRY(void, jmm_GetLastGCStat(JNIEnv *env, jobject obj, jmmGCStat *gc_stat)) 1855 ResourceMark rm(THREAD); 1856 1857 if (gc_stat->gc_ext_attribute_values_size > 0 && gc_stat->gc_ext_attribute_values == NULL) { 1858 THROW(vmSymbols::java_lang_NullPointerException()); 1859 } 1860 1861 // Get the GCMemoryManager 1862 GCMemoryManager* mgr = get_gc_memory_manager_from_jobject(obj, CHECK); 1863 1864 // Make a copy of the last GC statistics 1865 // GC may occur while constructing the last GC information 1866 int num_pools = MemoryService::num_memory_pools(); 1867 GCStatInfo stat(num_pools); 1868 if (mgr->get_last_gc_stat(&stat) == 0) { 1869 gc_stat->gc_index = 0; 1870 return; 1871 } 1872 1873 gc_stat->gc_index = stat.gc_index(); 1874 gc_stat->start_time = Management::ticks_to_ms(stat.start_time()); 1875 gc_stat->end_time = Management::ticks_to_ms(stat.end_time()); 1876 1877 // Current implementation does not have GC extension attributes 1878 gc_stat->num_gc_ext_attributes = 0; 1879 1880 // Fill the arrays of MemoryUsage objects with before and after GC 1881 // per pool memory usage 1882 objArrayOop bu = get_memory_usage_objArray(gc_stat->usage_before_gc, 1883 num_pools, 1884 CHECK); 1885 objArrayHandle usage_before_gc_ah(THREAD, bu); 1886 1887 objArrayOop au = get_memory_usage_objArray(gc_stat->usage_after_gc, 1888 num_pools, 1889 CHECK); 1890 objArrayHandle usage_after_gc_ah(THREAD, au); 1891 1892 for (int i = 0; i < num_pools; i++) { 1893 Handle before_usage = MemoryService::create_MemoryUsage_obj(stat.before_gc_usage_for_pool(i), CHECK); 1894 Handle after_usage; 1895 1896 MemoryUsage u = stat.after_gc_usage_for_pool(i); 1897 if (u.max_size() == 0 && u.used() > 0) { 1898 // If max size == 0, this pool is a survivor space. 1899 // Set max size = -1 since the pools will be swapped after GC. 1900 MemoryUsage usage(u.init_size(), u.used(), u.committed(), (size_t)-1); 1901 after_usage = MemoryService::create_MemoryUsage_obj(usage, CHECK); 1902 } else { 1903 after_usage = MemoryService::create_MemoryUsage_obj(stat.after_gc_usage_for_pool(i), CHECK); 1904 } 1905 usage_before_gc_ah->obj_at_put(i, before_usage()); 1906 usage_after_gc_ah->obj_at_put(i, after_usage()); 1907 } 1908 1909 if (gc_stat->gc_ext_attribute_values_size > 0) { 1910 // Current implementation only has 1 attribute (number of GC threads) 1911 // The type is 'I' 1912 gc_stat->gc_ext_attribute_values[0].i = mgr->num_gc_threads(); 1913 } 1914 JVM_END 1915 1916 JVM_ENTRY(void, jmm_SetGCNotificationEnabled(JNIEnv *env, jobject obj, jboolean enabled)) 1917 ResourceMark rm(THREAD); 1918 // Get the GCMemoryManager 1919 GCMemoryManager* mgr = get_gc_memory_manager_from_jobject(obj, CHECK); 1920 mgr->set_notification_enabled(enabled?true:false); 1921 JVM_END 1922 1923 // Dump heap - Returns 0 if succeeds. 1924 JVM_ENTRY(jint, jmm_DumpHeap0(JNIEnv *env, jstring outputfile, jboolean live)) 1925 #if INCLUDE_SERVICES 1926 ResourceMark rm(THREAD); 1927 oop on = JNIHandles::resolve_external_guard(outputfile); 1928 if (on == NULL) { 1929 THROW_MSG_(vmSymbols::java_lang_NullPointerException(), 1930 "Output file name cannot be null.", -1); 1931 } 1932 Handle onhandle(THREAD, on); 1933 char* name = java_lang_String::as_platform_dependent_str(onhandle, CHECK_(-1)); 1934 if (name == NULL) { 1935 THROW_MSG_(vmSymbols::java_lang_NullPointerException(), 1936 "Output file name cannot be null.", -1); 1937 } 1938 HeapDumper dumper(live ? true : false); 1939 if (dumper.dump(name) != 0) { 1940 const char* errmsg = dumper.error_as_C_string(); 1941 THROW_MSG_(vmSymbols::java_io_IOException(), errmsg, -1); 1942 } 1943 return 0; 1944 #else // INCLUDE_SERVICES 1945 return -1; 1946 #endif // INCLUDE_SERVICES 1947 JVM_END 1948 1949 JVM_ENTRY(jobjectArray, jmm_GetDiagnosticCommands(JNIEnv *env)) 1950 ResourceMark rm(THREAD); 1951 GrowableArray<const char *>* dcmd_list = DCmdFactory::DCmd_list(DCmd_Source_MBean); 1952 objArrayOop cmd_array_oop = oopFactory::new_objArray(SystemDictionary::String_klass(), 1953 dcmd_list->length(), CHECK_NULL); 1954 objArrayHandle cmd_array(THREAD, cmd_array_oop); 1955 for (int i = 0; i < dcmd_list->length(); i++) { 1956 oop cmd_name = java_lang_String::create_oop_from_str(dcmd_list->at(i), CHECK_NULL); 1957 cmd_array->obj_at_put(i, cmd_name); 1958 } 1959 return (jobjectArray) JNIHandles::make_local(env, cmd_array()); 1960 JVM_END 1961 1962 JVM_ENTRY(void, jmm_GetDiagnosticCommandInfo(JNIEnv *env, jobjectArray cmds, 1963 dcmdInfo* infoArray)) 1964 if (cmds == NULL || infoArray == NULL) { 1965 THROW(vmSymbols::java_lang_NullPointerException()); 1966 } 1967 1968 ResourceMark rm(THREAD); 1969 1970 objArrayOop ca = objArrayOop(JNIHandles::resolve_non_null(cmds)); 1971 objArrayHandle cmds_ah(THREAD, ca); 1972 1973 // Make sure we have a String array 1974 Klass* element_klass = ObjArrayKlass::cast(cmds_ah->klass())->element_klass(); 1975 if (element_klass != SystemDictionary::String_klass()) { 1976 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), 1977 "Array element type is not String class"); 1978 } 1979 1980 GrowableArray<DCmdInfo *>* info_list = DCmdFactory::DCmdInfo_list(DCmd_Source_MBean); 1981 1982 int num_cmds = cmds_ah->length(); 1983 for (int i = 0; i < num_cmds; i++) { 1984 oop cmd = cmds_ah->obj_at(i); 1985 if (cmd == NULL) { 1986 THROW_MSG(vmSymbols::java_lang_NullPointerException(), 1987 "Command name cannot be null."); 1988 } 1989 char* cmd_name = java_lang_String::as_utf8_string(cmd); 1990 if (cmd_name == NULL) { 1991 THROW_MSG(vmSymbols::java_lang_NullPointerException(), 1992 "Command name cannot be null."); 1993 } 1994 int pos = info_list->find((void*)cmd_name,DCmdInfo::by_name); 1995 if (pos == -1) { 1996 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), 1997 "Unknown diagnostic command"); 1998 } 1999 DCmdInfo* info = info_list->at(pos); 2000 infoArray[i].name = info->name(); 2001 infoArray[i].description = info->description(); 2002 infoArray[i].impact = info->impact(); 2003 JavaPermission p = info->permission(); 2004 infoArray[i].permission_class = p._class; 2005 infoArray[i].permission_name = p._name; 2006 infoArray[i].permission_action = p._action; 2007 infoArray[i].num_arguments = info->num_arguments(); 2008 infoArray[i].enabled = info->is_enabled(); 2009 } 2010 JVM_END 2011 2012 JVM_ENTRY(void, jmm_GetDiagnosticCommandArgumentsInfo(JNIEnv *env, 2013 jstring command, dcmdArgInfo* infoArray)) 2014 ResourceMark rm(THREAD); 2015 oop cmd = JNIHandles::resolve_external_guard(command); 2016 if (cmd == NULL) { 2017 THROW_MSG(vmSymbols::java_lang_NullPointerException(), 2018 "Command line cannot be null."); 2019 } 2020 char* cmd_name = java_lang_String::as_utf8_string(cmd); 2021 if (cmd_name == NULL) { 2022 THROW_MSG(vmSymbols::java_lang_NullPointerException(), 2023 "Command line content cannot be null."); 2024 } 2025 DCmd* dcmd = NULL; 2026 DCmdFactory*factory = DCmdFactory::factory(DCmd_Source_MBean, cmd_name, 2027 strlen(cmd_name)); 2028 if (factory != NULL) { 2029 dcmd = factory->create_resource_instance(NULL); 2030 } 2031 if (dcmd == NULL) { 2032 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), 2033 "Unknown diagnostic command"); 2034 } 2035 DCmdMark mark(dcmd); 2036 GrowableArray<DCmdArgumentInfo*>* array = dcmd->argument_info_array(); 2037 if (array->length() == 0) { 2038 return; 2039 } 2040 for (int i = 0; i < array->length(); i++) { 2041 infoArray[i].name = array->at(i)->name(); 2042 infoArray[i].description = array->at(i)->description(); 2043 infoArray[i].type = array->at(i)->type(); 2044 infoArray[i].default_string = array->at(i)->default_string(); 2045 infoArray[i].mandatory = array->at(i)->is_mandatory(); 2046 infoArray[i].option = array->at(i)->is_option(); 2047 infoArray[i].multiple = array->at(i)->is_multiple(); 2048 infoArray[i].position = array->at(i)->position(); 2049 } 2050 return; 2051 JVM_END 2052 2053 JVM_ENTRY(jstring, jmm_ExecuteDiagnosticCommand(JNIEnv *env, jstring commandline)) 2054 ResourceMark rm(THREAD); 2055 oop cmd = JNIHandles::resolve_external_guard(commandline); 2056 if (cmd == NULL) { 2057 THROW_MSG_NULL(vmSymbols::java_lang_NullPointerException(), 2058 "Command line cannot be null."); 2059 } 2060 char* cmdline = java_lang_String::as_utf8_string(cmd); 2061 if (cmdline == NULL) { 2062 THROW_MSG_NULL(vmSymbols::java_lang_NullPointerException(), 2063 "Command line content cannot be null."); 2064 } 2065 bufferedStream output; 2066 DCmd::parse_and_execute(DCmd_Source_MBean, &output, cmdline, ' ', CHECK_NULL); 2067 oop result = java_lang_String::create_oop_from_str(output.as_string(), CHECK_NULL); 2068 return (jstring) JNIHandles::make_local(env, result); 2069 JVM_END 2070 2071 JVM_ENTRY(void, jmm_SetDiagnosticFrameworkNotificationEnabled(JNIEnv *env, jboolean enabled)) 2072 DCmdFactory::set_jmx_notification_enabled(enabled?true:false); 2073 JVM_END 2074 2075 jlong Management::ticks_to_ms(jlong ticks) { 2076 assert(os::elapsed_frequency() > 0, "Must be non-zero"); 2077 return (jlong)(((double)ticks / (double)os::elapsed_frequency()) 2078 * (double)1000.0); 2079 } 2080 #endif // INCLUDE_MANAGEMENT 2081 2082 // Gets an array containing the amount of memory allocated on the Java 2083 // heap for a set of threads (in bytes). Each element of the array is 2084 // the amount of memory allocated for the thread ID specified in the 2085 // corresponding entry in the given array of thread IDs; or -1 if the 2086 // thread does not exist or has terminated. 2087 JVM_ENTRY(void, jmm_GetThreadAllocatedMemory(JNIEnv *env, jlongArray ids, 2088 jlongArray sizeArray)) 2089 // Check if threads is null 2090 if (ids == NULL || sizeArray == NULL) { 2091 THROW(vmSymbols::java_lang_NullPointerException()); 2092 } 2093 2094 ResourceMark rm(THREAD); 2095 typeArrayOop ta = typeArrayOop(JNIHandles::resolve_non_null(ids)); 2096 typeArrayHandle ids_ah(THREAD, ta); 2097 2098 typeArrayOop sa = typeArrayOop(JNIHandles::resolve_non_null(sizeArray)); 2099 typeArrayHandle sizeArray_h(THREAD, sa); 2100 2101 // validate the thread id array 2102 validate_thread_id_array(ids_ah, CHECK); 2103 2104 // sizeArray must be of the same length as the given array of thread IDs 2105 int num_threads = ids_ah->length(); 2106 if (num_threads != sizeArray_h->length()) { 2107 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), 2108 "The length of the given long array does not match the length of " 2109 "the given array of thread IDs"); 2110 } 2111 2112 MutexLockerEx ml(Threads_lock); 2113 for (int i = 0; i < num_threads; i++) { 2114 JavaThread* java_thread = Threads::find_java_thread_from_java_tid(ids_ah->long_at(i)); 2115 if (java_thread != NULL) { 2116 sizeArray_h->long_at_put(i, java_thread->cooked_allocated_bytes()); 2117 } 2118 } 2119 JVM_END 2120 2121 // Returns the CPU time consumed by a given thread (in nanoseconds). 2122 // If thread_id == 0, CPU time for the current thread is returned. 2123 // If user_sys_cpu_time = true, user level and system CPU time of 2124 // a given thread is returned; otherwise, only user level CPU time 2125 // is returned. 2126 JVM_ENTRY(jlong, jmm_GetThreadCpuTimeWithKind(JNIEnv *env, jlong thread_id, jboolean user_sys_cpu_time)) 2127 if (!os::is_thread_cpu_time_supported()) { 2128 return -1; 2129 } 2130 2131 if (thread_id < 0) { 2132 THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(), 2133 "Invalid thread ID", -1); 2134 } 2135 2136 JavaThread* java_thread = NULL; 2137 if (thread_id == 0) { 2138 // current thread 2139 return os::current_thread_cpu_time(user_sys_cpu_time != 0); 2140 } else { 2141 MutexLockerEx ml(Threads_lock); 2142 java_thread = Threads::find_java_thread_from_java_tid(thread_id); 2143 if (java_thread != NULL) { 2144 return os::thread_cpu_time((Thread*) java_thread, user_sys_cpu_time != 0); 2145 } 2146 } 2147 return -1; 2148 JVM_END 2149 2150 // Gets an array containing the CPU times consumed by a set of threads 2151 // (in nanoseconds). Each element of the array is the CPU time for the 2152 // thread ID specified in the corresponding entry in the given array 2153 // of thread IDs; or -1 if the thread does not exist or has terminated. 2154 // If user_sys_cpu_time = true, the sum of user level and system CPU time 2155 // for the given thread is returned; otherwise, only user level CPU time 2156 // is returned. 2157 JVM_ENTRY(void, jmm_GetThreadCpuTimesWithKind(JNIEnv *env, jlongArray ids, 2158 jlongArray timeArray, 2159 jboolean user_sys_cpu_time)) 2160 // Check if threads is null 2161 if (ids == NULL || timeArray == NULL) { 2162 THROW(vmSymbols::java_lang_NullPointerException()); 2163 } 2164 2165 ResourceMark rm(THREAD); 2166 typeArrayOop ta = typeArrayOop(JNIHandles::resolve_non_null(ids)); 2167 typeArrayHandle ids_ah(THREAD, ta); 2168 2169 typeArrayOop tia = typeArrayOop(JNIHandles::resolve_non_null(timeArray)); 2170 typeArrayHandle timeArray_h(THREAD, tia); 2171 2172 // validate the thread id array 2173 validate_thread_id_array(ids_ah, CHECK); 2174 2175 // timeArray must be of the same length as the given array of thread IDs 2176 int num_threads = ids_ah->length(); 2177 if (num_threads != timeArray_h->length()) { 2178 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), 2179 "The length of the given long array does not match the length of " 2180 "the given array of thread IDs"); 2181 } 2182 2183 MutexLockerEx ml(Threads_lock); 2184 for (int i = 0; i < num_threads; i++) { 2185 JavaThread* java_thread = Threads::find_java_thread_from_java_tid(ids_ah->long_at(i)); 2186 if (java_thread != NULL) { 2187 timeArray_h->long_at_put(i, os::thread_cpu_time((Thread*)java_thread, 2188 user_sys_cpu_time != 0)); 2189 } 2190 } 2191 JVM_END 2192 2193 2194 2195 #if INCLUDE_MANAGEMENT 2196 const struct jmmInterface_1_ jmm_interface = { 2197 NULL, 2198 NULL, 2199 jmm_GetVersion, 2200 jmm_GetOptionalSupport, 2201 jmm_GetThreadInfo, 2202 jmm_GetMemoryPools, 2203 jmm_GetMemoryManagers, 2204 jmm_GetMemoryPoolUsage, 2205 jmm_GetPeakMemoryPoolUsage, 2206 jmm_GetThreadAllocatedMemory, 2207 jmm_GetMemoryUsage, 2208 jmm_GetLongAttribute, 2209 jmm_GetBoolAttribute, 2210 jmm_SetBoolAttribute, 2211 jmm_GetLongAttributes, 2212 jmm_FindMonitorDeadlockedThreads, 2213 jmm_GetThreadCpuTime, 2214 jmm_GetVMGlobalNames, 2215 jmm_GetVMGlobals, 2216 jmm_GetInternalThreadTimes, 2217 jmm_ResetStatistic, 2218 jmm_SetPoolSensor, 2219 jmm_SetPoolThreshold, 2220 jmm_GetPoolCollectionUsage, 2221 jmm_GetGCExtAttributeInfo, 2222 jmm_GetLastGCStat, 2223 jmm_GetThreadCpuTimeWithKind, 2224 jmm_GetThreadCpuTimesWithKind, 2225 jmm_DumpHeap0, 2226 jmm_FindDeadlockedThreads, 2227 jmm_SetVMGlobal, 2228 NULL, 2229 jmm_DumpThreads, 2230 jmm_SetGCNotificationEnabled, 2231 jmm_GetDiagnosticCommands, 2232 jmm_GetDiagnosticCommandInfo, 2233 jmm_GetDiagnosticCommandArgumentsInfo, 2234 jmm_ExecuteDiagnosticCommand, 2235 jmm_SetDiagnosticFrameworkNotificationEnabled 2236 }; 2237 #endif // INCLUDE_MANAGEMENT 2238 2239 void* Management::get_jmm_interface(int version) { 2240 #if INCLUDE_MANAGEMENT 2241 if (version == JMM_VERSION) { 2242 return (void*) &jmm_interface; 2243 } 2244 #endif // INCLUDE_MANAGEMENT 2245 return NULL; 2246 }