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