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