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