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