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