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