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