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, CHECK_NULL); 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, CHECK_NULL); 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 // Calculate the memory usage 717 size_t total_init = 0; 718 size_t total_used = 0; 719 size_t total_committed = 0; 720 size_t total_max = 0; 721 bool has_undefined_init_size = false; 722 bool has_undefined_max_size = false; 723 724 for (int i = 0; i < MemoryService::num_memory_pools(); i++) { 725 MemoryPool* pool = MemoryService::get_memory_pool(i); 726 if ((heap && pool->is_heap()) || (!heap && pool->is_non_heap())) { 727 MemoryUsage u = pool->get_memory_usage(); 728 total_used += u.used(); 729 total_committed += u.committed(); 730 731 if (u.init_size() == (size_t)-1) { 732 has_undefined_init_size = true; 733 } 734 if (!has_undefined_init_size) { 735 total_init += u.init_size(); 736 } 737 738 if (u.max_size() == (size_t)-1) { 739 has_undefined_max_size = true; 740 } 741 if (!has_undefined_max_size) { 742 total_max += u.max_size(); 743 } 744 } 745 } 746 747 // if any one of the memory pool has undefined init_size or max_size, 748 // set it to -1 749 if (has_undefined_init_size) { 750 total_init = (size_t)-1; 751 } 752 if (has_undefined_max_size) { 753 total_max = (size_t)-1; 754 } 755 756 MemoryUsage usage((heap ? InitialHeapSize : total_init), 757 total_used, 758 total_committed, 759 (heap ? Universe::heap()->max_capacity() : total_max)); 760 761 Handle obj = MemoryService::create_MemoryUsage_obj(usage, CHECK_NULL); 762 return JNIHandles::make_local(env, obj()); 763 JVM_END 764 765 // Returns the boolean value of a given attribute. 766 JVM_LEAF(jboolean, jmm_GetBoolAttribute(JNIEnv *env, jmmBoolAttribute att)) 767 switch (att) { 768 case JMM_VERBOSE_GC: 769 return MemoryService::get_verbose(); 770 case JMM_VERBOSE_CLASS: 771 return ClassLoadingService::get_verbose(); 772 case JMM_THREAD_CONTENTION_MONITORING: 773 return ThreadService::is_thread_monitoring_contention(); 774 case JMM_THREAD_CPU_TIME: 775 return ThreadService::is_thread_cpu_time_enabled(); 776 case JMM_THREAD_ALLOCATED_MEMORY: 777 return ThreadService::is_thread_allocated_memory_enabled(); 778 default: 779 assert(0, "Unrecognized attribute"); 780 return false; 781 } 782 JVM_END 783 784 // Sets the given boolean attribute and returns the previous value. 785 JVM_ENTRY(jboolean, jmm_SetBoolAttribute(JNIEnv *env, jmmBoolAttribute att, jboolean flag)) 786 switch (att) { 787 case JMM_VERBOSE_GC: 788 return MemoryService::set_verbose(flag != 0); 789 case JMM_VERBOSE_CLASS: 790 return ClassLoadingService::set_verbose(flag != 0); 791 case JMM_THREAD_CONTENTION_MONITORING: 792 return ThreadService::set_thread_monitoring_contention(flag != 0); 793 case JMM_THREAD_CPU_TIME: 794 return ThreadService::set_thread_cpu_time_enabled(flag != 0); 795 case JMM_THREAD_ALLOCATED_MEMORY: 796 return ThreadService::set_thread_allocated_memory_enabled(flag != 0); 797 default: 798 assert(0, "Unrecognized attribute"); 799 return false; 800 } 801 JVM_END 802 803 804 static jlong get_gc_attribute(GCMemoryManager* mgr, jmmLongAttribute att) { 805 switch (att) { 806 case JMM_GC_TIME_MS: 807 return mgr->gc_time_ms(); 808 809 case JMM_GC_COUNT: 810 return mgr->gc_count(); 811 812 case JMM_GC_EXT_ATTRIBUTE_INFO_SIZE: 813 // current implementation only has 1 ext attribute 814 return 1; 815 816 default: 817 assert(0, "Unrecognized GC attribute"); 818 return -1; 819 } 820 } 821 822 class VmThreadCountClosure: public ThreadClosure { 823 private: 824 int _count; 825 public: 826 VmThreadCountClosure() : _count(0) {}; 827 void do_thread(Thread* thread); 828 int count() { return _count; } 829 }; 830 831 void VmThreadCountClosure::do_thread(Thread* thread) { 832 // exclude externally visible JavaThreads 833 if (thread->is_Java_thread() && !thread->is_hidden_from_external_view()) { 834 return; 835 } 836 837 _count++; 838 } 839 840 static jint get_vm_thread_count() { 841 VmThreadCountClosure vmtcc; 842 { 843 MutexLockerEx ml(Threads_lock); 844 Threads::threads_do(&vmtcc); 845 } 846 847 return vmtcc.count(); 848 } 849 850 static jint get_num_flags() { 851 // last flag entry is always NULL, so subtract 1 852 int nFlags = (int) JVMFlag::numFlags - 1; 853 int count = 0; 854 for (int i = 0; i < nFlags; i++) { 855 JVMFlag* flag = &JVMFlag::flags[i]; 856 // Exclude the locked (diagnostic, experimental) flags 857 if (flag->is_unlocked() || flag->is_unlocker()) { 858 count++; 859 } 860 } 861 return count; 862 } 863 864 static jlong get_long_attribute(jmmLongAttribute att) { 865 switch (att) { 866 case JMM_CLASS_LOADED_COUNT: 867 return ClassLoadingService::loaded_class_count(); 868 869 case JMM_CLASS_UNLOADED_COUNT: 870 return ClassLoadingService::unloaded_class_count(); 871 872 case JMM_THREAD_TOTAL_COUNT: 873 return ThreadService::get_total_thread_count(); 874 875 case JMM_THREAD_LIVE_COUNT: 876 return ThreadService::get_live_thread_count(); 877 878 case JMM_THREAD_PEAK_COUNT: 879 return ThreadService::get_peak_thread_count(); 880 881 case JMM_THREAD_DAEMON_COUNT: 882 return ThreadService::get_daemon_thread_count(); 883 884 case JMM_JVM_INIT_DONE_TIME_MS: 885 return Management::vm_init_done_time(); 886 887 case JMM_JVM_UPTIME_MS: 888 return Management::ticks_to_ms(os::elapsed_counter()); 889 890 case JMM_COMPILE_TOTAL_TIME_MS: 891 return Management::ticks_to_ms(CompileBroker::total_compilation_ticks()); 892 893 case JMM_OS_PROCESS_ID: 894 return os::current_process_id(); 895 896 // Hotspot-specific counters 897 case JMM_CLASS_LOADED_BYTES: 898 return ClassLoadingService::loaded_class_bytes(); 899 900 case JMM_CLASS_UNLOADED_BYTES: 901 return ClassLoadingService::unloaded_class_bytes(); 902 903 case JMM_SHARED_CLASS_LOADED_COUNT: 904 return ClassLoadingService::loaded_shared_class_count(); 905 906 case JMM_SHARED_CLASS_UNLOADED_COUNT: 907 return ClassLoadingService::unloaded_shared_class_count(); 908 909 910 case JMM_SHARED_CLASS_LOADED_BYTES: 911 return ClassLoadingService::loaded_shared_class_bytes(); 912 913 case JMM_SHARED_CLASS_UNLOADED_BYTES: 914 return ClassLoadingService::unloaded_shared_class_bytes(); 915 916 case JMM_TOTAL_CLASSLOAD_TIME_MS: 917 return ClassLoader::classloader_time_ms(); 918 919 case JMM_VM_GLOBAL_COUNT: 920 return get_num_flags(); 921 922 case JMM_SAFEPOINT_COUNT: 923 return RuntimeService::safepoint_count(); 924 925 case JMM_TOTAL_SAFEPOINTSYNC_TIME_MS: 926 return RuntimeService::safepoint_sync_time_ms(); 927 928 case JMM_TOTAL_STOPPED_TIME_MS: 929 return RuntimeService::safepoint_time_ms(); 930 931 case JMM_TOTAL_APP_TIME_MS: 932 return RuntimeService::application_time_ms(); 933 934 case JMM_VM_THREAD_COUNT: 935 return get_vm_thread_count(); 936 937 case JMM_CLASS_INIT_TOTAL_COUNT: 938 return ClassLoader::class_init_count(); 939 940 case JMM_CLASS_INIT_TOTAL_TIME_MS: 941 return ClassLoader::class_init_time_ms(); 942 943 case JMM_CLASS_VERIFY_TOTAL_TIME_MS: 944 return ClassLoader::class_verify_time_ms(); 945 946 case JMM_METHOD_DATA_SIZE_BYTES: 947 return ClassLoadingService::class_method_data_size(); 948 949 case JMM_OS_MEM_TOTAL_PHYSICAL_BYTES: 950 return os::physical_memory(); 951 952 default: 953 return -1; 954 } 955 } 956 957 958 // Returns the long value of a given attribute. 959 JVM_ENTRY(jlong, jmm_GetLongAttribute(JNIEnv *env, jobject obj, jmmLongAttribute att)) 960 if (obj == NULL) { 961 return get_long_attribute(att); 962 } else { 963 GCMemoryManager* mgr = get_gc_memory_manager_from_jobject(obj, CHECK_(0L)); 964 if (mgr != NULL) { 965 return get_gc_attribute(mgr, att); 966 } 967 } 968 return -1; 969 JVM_END 970 971 // Gets the value of all attributes specified in the given array 972 // and sets the value in the result array. 973 // Returns the number of attributes found. 974 JVM_ENTRY(jint, jmm_GetLongAttributes(JNIEnv *env, 975 jobject obj, 976 jmmLongAttribute* atts, 977 jint count, 978 jlong* result)) 979 980 int num_atts = 0; 981 if (obj == NULL) { 982 for (int i = 0; i < count; i++) { 983 result[i] = get_long_attribute(atts[i]); 984 if (result[i] != -1) { 985 num_atts++; 986 } 987 } 988 } else { 989 GCMemoryManager* mgr = get_gc_memory_manager_from_jobject(obj, CHECK_0); 990 for (int i = 0; i < count; i++) { 991 result[i] = get_gc_attribute(mgr, atts[i]); 992 if (result[i] != -1) { 993 num_atts++; 994 } 995 } 996 } 997 return num_atts; 998 JVM_END 999 1000 // Helper function to do thread dump for a specific list of threads 1001 static void do_thread_dump(ThreadDumpResult* dump_result, 1002 typeArrayHandle ids_ah, // array of thread ID (long[]) 1003 int num_threads, 1004 int max_depth, 1005 bool with_locked_monitors, 1006 bool with_locked_synchronizers, 1007 TRAPS) { 1008 // no need to actually perform thread dump if no TIDs are specified 1009 if (num_threads == 0) return; 1010 1011 // First get an array of threadObj handles. 1012 // A JavaThread may terminate before we get the stack trace. 1013 GrowableArray<instanceHandle>* thread_handle_array = new GrowableArray<instanceHandle>(num_threads); 1014 1015 { 1016 // Need this ThreadsListHandle for converting Java thread IDs into 1017 // threadObj handles; dump_result->set_t_list() is called in the 1018 // VM op below so we can't use it yet. 1019 ThreadsListHandle tlh; 1020 for (int i = 0; i < num_threads; i++) { 1021 jlong tid = ids_ah->long_at(i); 1022 JavaThread* jt = tlh.list()->find_JavaThread_from_java_tid(tid); 1023 oop thread_obj = (jt != NULL ? jt->threadObj() : (oop)NULL); 1024 instanceHandle threadObj_h(THREAD, (instanceOop) thread_obj); 1025 thread_handle_array->append(threadObj_h); 1026 } 1027 } 1028 1029 // Obtain thread dumps and thread snapshot information 1030 VM_ThreadDump op(dump_result, 1031 thread_handle_array, 1032 num_threads, 1033 max_depth, /* stack depth */ 1034 with_locked_monitors, 1035 with_locked_synchronizers); 1036 VMThread::execute(&op); 1037 } 1038 1039 // Gets an array of ThreadInfo objects. Each element is the ThreadInfo 1040 // for the thread ID specified in the corresponding entry in 1041 // the given array of thread IDs; or NULL if the thread does not exist 1042 // or has terminated. 1043 // 1044 // Input parameters: 1045 // ids - array of thread IDs 1046 // maxDepth - the maximum depth of stack traces to be dumped: 1047 // maxDepth == -1 requests to dump entire stack trace. 1048 // maxDepth == 0 requests no stack trace. 1049 // infoArray - array of ThreadInfo objects 1050 // 1051 // QQQ - Why does this method return a value instead of void? 1052 JVM_ENTRY(jint, jmm_GetThreadInfo(JNIEnv *env, jlongArray ids, jint maxDepth, jobjectArray infoArray)) 1053 // Check if threads is null 1054 if (ids == NULL || infoArray == NULL) { 1055 THROW_(vmSymbols::java_lang_NullPointerException(), -1); 1056 } 1057 1058 if (maxDepth < -1) { 1059 THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(), 1060 "Invalid maxDepth", -1); 1061 } 1062 1063 ResourceMark rm(THREAD); 1064 typeArrayOop ta = typeArrayOop(JNIHandles::resolve_non_null(ids)); 1065 typeArrayHandle ids_ah(THREAD, ta); 1066 1067 oop infoArray_obj = JNIHandles::resolve_non_null(infoArray); 1068 objArrayOop oa = objArrayOop(infoArray_obj); 1069 objArrayHandle infoArray_h(THREAD, oa); 1070 1071 // validate the thread id array 1072 validate_thread_id_array(ids_ah, CHECK_0); 1073 1074 // validate the ThreadInfo[] parameters 1075 validate_thread_info_array(infoArray_h, CHECK_0); 1076 1077 // infoArray must be of the same length as the given array of thread IDs 1078 int num_threads = ids_ah->length(); 1079 if (num_threads != infoArray_h->length()) { 1080 THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(), 1081 "The length of the given ThreadInfo array does not match the length of the given array of thread IDs", -1); 1082 } 1083 1084 // make sure the AbstractOwnableSynchronizer klass is loaded before taking thread snapshots 1085 java_util_concurrent_locks_AbstractOwnableSynchronizer::initialize(CHECK_0); 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 // make sure the AbstractOwnableSynchronizer klass is loaded before taking thread snapshots 1158 java_util_concurrent_locks_AbstractOwnableSynchronizer::initialize(CHECK_NULL); 1159 1160 typeArrayOop ta = typeArrayOop(JNIHandles::resolve(thread_ids)); 1161 int num_threads = (ta != NULL ? ta->length() : 0); 1162 typeArrayHandle ids_ah(THREAD, ta); 1163 1164 ThreadDumpResult dump_result(num_threads); // can safepoint 1165 1166 if (ids_ah() != NULL) { 1167 1168 // validate the thread id array 1169 validate_thread_id_array(ids_ah, CHECK_NULL); 1170 1171 // obtain thread dump of a specific list of threads 1172 do_thread_dump(&dump_result, 1173 ids_ah, 1174 num_threads, 1175 maxDepth, /* stack depth */ 1176 (locked_monitors ? true : false), /* with locked monitors */ 1177 (locked_synchronizers ? true : false), /* with locked synchronizers */ 1178 CHECK_NULL); 1179 } else { 1180 // obtain thread dump of all threads 1181 VM_ThreadDump op(&dump_result, 1182 maxDepth, /* stack depth */ 1183 (locked_monitors ? true : false), /* with locked monitors */ 1184 (locked_synchronizers ? true : false) /* with locked synchronizers */); 1185 VMThread::execute(&op); 1186 } 1187 1188 int num_snapshots = dump_result.num_snapshots(); 1189 assert(num_snapshots == 0 || dump_result.t_list_has_been_set(), "ThreadsList must have been set if we have a snapshot"); 1190 1191 // create the result ThreadInfo[] object 1192 InstanceKlass* ik = Management::java_lang_management_ThreadInfo_klass(CHECK_NULL); 1193 objArrayOop r = oopFactory::new_objArray(ik, num_snapshots, CHECK_NULL); 1194 objArrayHandle result_h(THREAD, r); 1195 1196 int index = 0; 1197 for (ThreadSnapshot* ts = dump_result.snapshots(); ts != NULL; ts = ts->next(), index++) { 1198 if (ts->threadObj() == NULL) { 1199 // if the thread does not exist or now it is terminated, set threadinfo to NULL 1200 result_h->obj_at_put(index, NULL); 1201 continue; 1202 } 1203 1204 ThreadStackTrace* stacktrace = ts->get_stack_trace(); 1205 assert(stacktrace != NULL, "Must have a stack trace dumped"); 1206 1207 // Create Object[] filled with locked monitors 1208 // Create int[] filled with the stack depth where a monitor was locked 1209 int num_frames = stacktrace->get_stack_depth(); 1210 int num_locked_monitors = stacktrace->num_jni_locked_monitors(); 1211 1212 // Count the total number of locked monitors 1213 for (int i = 0; i < num_frames; i++) { 1214 StackFrameInfo* frame = stacktrace->stack_frame_at(i); 1215 num_locked_monitors += frame->num_locked_monitors(); 1216 } 1217 1218 objArrayHandle monitors_array; 1219 typeArrayHandle depths_array; 1220 objArrayHandle synchronizers_array; 1221 1222 if (locked_monitors) { 1223 // Constructs Object[] and int[] to contain the object monitor and the stack depth 1224 // where the thread locked it 1225 objArrayOop array = oopFactory::new_objArray(SystemDictionary::Object_klass(), num_locked_monitors, CHECK_NULL); 1226 objArrayHandle mh(THREAD, array); 1227 monitors_array = mh; 1228 1229 typeArrayOop tarray = oopFactory::new_typeArray(T_INT, num_locked_monitors, CHECK_NULL); 1230 typeArrayHandle dh(THREAD, tarray); 1231 depths_array = dh; 1232 1233 int count = 0; 1234 int j = 0; 1235 for (int depth = 0; depth < num_frames; depth++) { 1236 StackFrameInfo* frame = stacktrace->stack_frame_at(depth); 1237 int len = frame->num_locked_monitors(); 1238 GrowableArray<oop>* locked_monitors = frame->locked_monitors(); 1239 for (j = 0; j < len; j++) { 1240 oop monitor = locked_monitors->at(j); 1241 assert(monitor != NULL, "must be a Java object"); 1242 monitors_array->obj_at_put(count, monitor); 1243 depths_array->int_at_put(count, depth); 1244 count++; 1245 } 1246 } 1247 1248 GrowableArray<oop>* jni_locked_monitors = stacktrace->jni_locked_monitors(); 1249 for (j = 0; j < jni_locked_monitors->length(); j++) { 1250 oop object = jni_locked_monitors->at(j); 1251 assert(object != NULL, "must be a Java object"); 1252 monitors_array->obj_at_put(count, object); 1253 // Monitor locked via JNI MonitorEnter call doesn't have stack depth info 1254 depths_array->int_at_put(count, -1); 1255 count++; 1256 } 1257 assert(count == num_locked_monitors, "number of locked monitors doesn't match"); 1258 } 1259 1260 if (locked_synchronizers) { 1261 // Create Object[] filled with locked JSR-166 synchronizers 1262 assert(ts->threadObj() != NULL, "Must be a valid JavaThread"); 1263 ThreadConcurrentLocks* tcl = ts->get_concurrent_locks(); 1264 GrowableArray<instanceOop>* locks = (tcl != NULL ? tcl->owned_locks() : NULL); 1265 int num_locked_synchronizers = (locks != NULL ? locks->length() : 0); 1266 1267 objArrayOop array = oopFactory::new_objArray(SystemDictionary::Object_klass(), num_locked_synchronizers, CHECK_NULL); 1268 objArrayHandle sh(THREAD, array); 1269 synchronizers_array = sh; 1270 1271 for (int k = 0; k < num_locked_synchronizers; k++) { 1272 synchronizers_array->obj_at_put(k, locks->at(k)); 1273 } 1274 } 1275 1276 // Create java.lang.management.ThreadInfo object 1277 instanceOop info_obj = Management::create_thread_info_instance(ts, 1278 monitors_array, 1279 depths_array, 1280 synchronizers_array, 1281 CHECK_NULL); 1282 result_h->obj_at_put(index, info_obj); 1283 } 1284 1285 return (jobjectArray) JNIHandles::make_local(env, result_h()); 1286 JVM_END 1287 1288 // Reset statistic. Return true if the requested statistic is reset. 1289 // Otherwise, return false. 1290 // 1291 // Input parameters: 1292 // obj - specify which instance the statistic associated with to be reset 1293 // For PEAK_POOL_USAGE stat, obj is required to be a memory pool object. 1294 // For THREAD_CONTENTION_COUNT and TIME stat, obj is required to be a thread ID. 1295 // type - the type of statistic to be reset 1296 // 1297 JVM_ENTRY(jboolean, jmm_ResetStatistic(JNIEnv *env, jvalue obj, jmmStatisticType type)) 1298 ResourceMark rm(THREAD); 1299 1300 switch (type) { 1301 case JMM_STAT_PEAK_THREAD_COUNT: 1302 ThreadService::reset_peak_thread_count(); 1303 return true; 1304 1305 case JMM_STAT_THREAD_CONTENTION_COUNT: 1306 case JMM_STAT_THREAD_CONTENTION_TIME: { 1307 jlong tid = obj.j; 1308 if (tid < 0) { 1309 THROW_(vmSymbols::java_lang_IllegalArgumentException(), JNI_FALSE); 1310 } 1311 1312 // Look for the JavaThread of this given tid 1313 JavaThreadIteratorWithHandle jtiwh; 1314 if (tid == 0) { 1315 // reset contention statistics for all threads if tid == 0 1316 for (; JavaThread *java_thread = jtiwh.next(); ) { 1317 if (type == JMM_STAT_THREAD_CONTENTION_COUNT) { 1318 ThreadService::reset_contention_count_stat(java_thread); 1319 } else { 1320 ThreadService::reset_contention_time_stat(java_thread); 1321 } 1322 } 1323 } else { 1324 // reset contention statistics for a given thread 1325 JavaThread* java_thread = jtiwh.list()->find_JavaThread_from_java_tid(tid); 1326 if (java_thread == NULL) { 1327 return false; 1328 } 1329 1330 if (type == JMM_STAT_THREAD_CONTENTION_COUNT) { 1331 ThreadService::reset_contention_count_stat(java_thread); 1332 } else { 1333 ThreadService::reset_contention_time_stat(java_thread); 1334 } 1335 } 1336 return true; 1337 break; 1338 } 1339 case JMM_STAT_PEAK_POOL_USAGE: { 1340 jobject o = obj.l; 1341 if (o == NULL) { 1342 THROW_(vmSymbols::java_lang_NullPointerException(), JNI_FALSE); 1343 } 1344 1345 oop pool_obj = JNIHandles::resolve(o); 1346 assert(pool_obj->is_instance(), "Should be an instanceOop"); 1347 instanceHandle ph(THREAD, (instanceOop) pool_obj); 1348 1349 MemoryPool* pool = MemoryService::get_memory_pool(ph); 1350 if (pool != NULL) { 1351 pool->reset_peak_memory_usage(); 1352 return true; 1353 } 1354 break; 1355 } 1356 case JMM_STAT_GC_STAT: { 1357 jobject o = obj.l; 1358 if (o == NULL) { 1359 THROW_(vmSymbols::java_lang_NullPointerException(), JNI_FALSE); 1360 } 1361 1362 GCMemoryManager* mgr = get_gc_memory_manager_from_jobject(o, CHECK_0); 1363 if (mgr != NULL) { 1364 mgr->reset_gc_stat(); 1365 return true; 1366 } 1367 break; 1368 } 1369 default: 1370 assert(0, "Unknown Statistic Type"); 1371 } 1372 return false; 1373 JVM_END 1374 1375 // Returns the fast estimate of CPU time consumed by 1376 // a given thread (in nanoseconds). 1377 // If thread_id == 0, return CPU time for the current thread. 1378 JVM_ENTRY(jlong, jmm_GetThreadCpuTime(JNIEnv *env, jlong thread_id)) 1379 if (!os::is_thread_cpu_time_supported()) { 1380 return -1; 1381 } 1382 1383 if (thread_id < 0) { 1384 THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(), 1385 "Invalid thread ID", -1); 1386 } 1387 1388 JavaThread* java_thread = NULL; 1389 if (thread_id == 0) { 1390 // current thread 1391 return os::current_thread_cpu_time(); 1392 } else { 1393 ThreadsListHandle tlh; 1394 java_thread = tlh.list()->find_JavaThread_from_java_tid(thread_id); 1395 if (java_thread != NULL) { 1396 return os::thread_cpu_time((Thread*) java_thread); 1397 } 1398 } 1399 return -1; 1400 JVM_END 1401 1402 // Returns a String array of all VM global flag names 1403 JVM_ENTRY(jobjectArray, jmm_GetVMGlobalNames(JNIEnv *env)) 1404 // last flag entry is always NULL, so subtract 1 1405 int nFlags = (int) JVMFlag::numFlags - 1; 1406 // allocate a temp array 1407 objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(), 1408 nFlags, CHECK_0); 1409 objArrayHandle flags_ah(THREAD, r); 1410 int num_entries = 0; 1411 for (int i = 0; i < nFlags; i++) { 1412 JVMFlag* flag = &JVMFlag::flags[i]; 1413 // Exclude notproduct and develop flags in product builds. 1414 if (flag->is_constant_in_binary()) { 1415 continue; 1416 } 1417 // Exclude the locked (experimental, diagnostic) flags 1418 if (flag->is_unlocked() || flag->is_unlocker()) { 1419 Handle s = java_lang_String::create_from_str(flag->_name, CHECK_0); 1420 flags_ah->obj_at_put(num_entries, s()); 1421 num_entries++; 1422 } 1423 } 1424 1425 if (num_entries < nFlags) { 1426 // Return array of right length 1427 objArrayOop res = oopFactory::new_objArray(SystemDictionary::String_klass(), num_entries, CHECK_0); 1428 for(int i = 0; i < num_entries; i++) { 1429 res->obj_at_put(i, flags_ah->obj_at(i)); 1430 } 1431 return (jobjectArray)JNIHandles::make_local(env, res); 1432 } 1433 1434 return (jobjectArray)JNIHandles::make_local(env, flags_ah()); 1435 JVM_END 1436 1437 // Utility function used by jmm_GetVMGlobals. Returns false if flag type 1438 // can't be determined, true otherwise. If false is returned, then *global 1439 // will be incomplete and invalid. 1440 bool add_global_entry(JNIEnv* env, Handle name, jmmVMGlobal *global, JVMFlag *flag, TRAPS) { 1441 Handle flag_name; 1442 if (name() == NULL) { 1443 flag_name = java_lang_String::create_from_str(flag->_name, CHECK_false); 1444 } else { 1445 flag_name = name; 1446 } 1447 global->name = (jstring)JNIHandles::make_local(env, flag_name()); 1448 1449 if (flag->is_bool()) { 1450 global->value.z = flag->get_bool() ? JNI_TRUE : JNI_FALSE; 1451 global->type = JMM_VMGLOBAL_TYPE_JBOOLEAN; 1452 } else if (flag->is_int()) { 1453 global->value.j = (jlong)flag->get_int(); 1454 global->type = JMM_VMGLOBAL_TYPE_JLONG; 1455 } else if (flag->is_uint()) { 1456 global->value.j = (jlong)flag->get_uint(); 1457 global->type = JMM_VMGLOBAL_TYPE_JLONG; 1458 } else if (flag->is_intx()) { 1459 global->value.j = (jlong)flag->get_intx(); 1460 global->type = JMM_VMGLOBAL_TYPE_JLONG; 1461 } else if (flag->is_uintx()) { 1462 global->value.j = (jlong)flag->get_uintx(); 1463 global->type = JMM_VMGLOBAL_TYPE_JLONG; 1464 } else if (flag->is_uint64_t()) { 1465 global->value.j = (jlong)flag->get_uint64_t(); 1466 global->type = JMM_VMGLOBAL_TYPE_JLONG; 1467 } else if (flag->is_double()) { 1468 global->value.d = (jdouble)flag->get_double(); 1469 global->type = JMM_VMGLOBAL_TYPE_JDOUBLE; 1470 } else if (flag->is_size_t()) { 1471 global->value.j = (jlong)flag->get_size_t(); 1472 global->type = JMM_VMGLOBAL_TYPE_JLONG; 1473 } else if (flag->is_ccstr()) { 1474 Handle str = java_lang_String::create_from_str(flag->get_ccstr(), CHECK_false); 1475 global->value.l = (jobject)JNIHandles::make_local(env, str()); 1476 global->type = JMM_VMGLOBAL_TYPE_JSTRING; 1477 } else { 1478 global->type = JMM_VMGLOBAL_TYPE_UNKNOWN; 1479 return false; 1480 } 1481 1482 global->writeable = flag->is_writeable(); 1483 global->external = flag->is_external(); 1484 switch (flag->get_origin()) { 1485 case JVMFlag::DEFAULT: 1486 global->origin = JMM_VMGLOBAL_ORIGIN_DEFAULT; 1487 break; 1488 case JVMFlag::COMMAND_LINE: 1489 global->origin = JMM_VMGLOBAL_ORIGIN_COMMAND_LINE; 1490 break; 1491 case JVMFlag::ENVIRON_VAR: 1492 global->origin = JMM_VMGLOBAL_ORIGIN_ENVIRON_VAR; 1493 break; 1494 case JVMFlag::CONFIG_FILE: 1495 global->origin = JMM_VMGLOBAL_ORIGIN_CONFIG_FILE; 1496 break; 1497 case JVMFlag::MANAGEMENT: 1498 global->origin = JMM_VMGLOBAL_ORIGIN_MANAGEMENT; 1499 break; 1500 case JVMFlag::ERGONOMIC: 1501 global->origin = JMM_VMGLOBAL_ORIGIN_ERGONOMIC; 1502 break; 1503 case JVMFlag::ATTACH_ON_DEMAND: 1504 global->origin = JMM_VMGLOBAL_ORIGIN_ATTACH_ON_DEMAND; 1505 break; 1506 default: 1507 global->origin = JMM_VMGLOBAL_ORIGIN_OTHER; 1508 } 1509 1510 return true; 1511 } 1512 1513 // Fill globals array of count length with jmmVMGlobal entries 1514 // specified by names. If names == NULL, fill globals array 1515 // with all Flags. Return value is number of entries 1516 // created in globals. 1517 // If a JVMFlag with a given name in an array element does not 1518 // exist, globals[i].name will be set to NULL. 1519 JVM_ENTRY(jint, jmm_GetVMGlobals(JNIEnv *env, 1520 jobjectArray names, 1521 jmmVMGlobal *globals, 1522 jint count)) 1523 1524 1525 if (globals == NULL) { 1526 THROW_(vmSymbols::java_lang_NullPointerException(), 0); 1527 } 1528 1529 ResourceMark rm(THREAD); 1530 1531 if (names != NULL) { 1532 // return the requested globals 1533 objArrayOop ta = objArrayOop(JNIHandles::resolve_non_null(names)); 1534 objArrayHandle names_ah(THREAD, ta); 1535 // Make sure we have a String array 1536 Klass* element_klass = ObjArrayKlass::cast(names_ah->klass())->element_klass(); 1537 if (element_klass != SystemDictionary::String_klass()) { 1538 THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(), 1539 "Array element type is not String class", 0); 1540 } 1541 1542 int names_length = names_ah->length(); 1543 int num_entries = 0; 1544 for (int i = 0; i < names_length && i < count; i++) { 1545 oop s = names_ah->obj_at(i); 1546 if (s == NULL) { 1547 THROW_(vmSymbols::java_lang_NullPointerException(), 0); 1548 } 1549 1550 Handle sh(THREAD, s); 1551 char* str = java_lang_String::as_utf8_string(s); 1552 JVMFlag* flag = JVMFlag::find_flag(str, strlen(str)); 1553 if (flag != NULL && 1554 add_global_entry(env, sh, &globals[i], flag, THREAD)) { 1555 num_entries++; 1556 } else { 1557 globals[i].name = NULL; 1558 } 1559 } 1560 return num_entries; 1561 } else { 1562 // return all globals if names == NULL 1563 1564 // last flag entry is always NULL, so subtract 1 1565 int nFlags = (int) JVMFlag::numFlags - 1; 1566 Handle null_h; 1567 int num_entries = 0; 1568 for (int i = 0; i < nFlags && num_entries < count; i++) { 1569 JVMFlag* flag = &JVMFlag::flags[i]; 1570 // Exclude notproduct and develop flags in product builds. 1571 if (flag->is_constant_in_binary()) { 1572 continue; 1573 } 1574 // Exclude the locked (diagnostic, experimental) flags 1575 if ((flag->is_unlocked() || flag->is_unlocker()) && 1576 add_global_entry(env, null_h, &globals[num_entries], flag, THREAD)) { 1577 num_entries++; 1578 } 1579 } 1580 return num_entries; 1581 } 1582 JVM_END 1583 1584 JVM_ENTRY(void, jmm_SetVMGlobal(JNIEnv *env, jstring flag_name, jvalue new_value)) 1585 ResourceMark rm(THREAD); 1586 1587 oop fn = JNIHandles::resolve_external_guard(flag_name); 1588 if (fn == NULL) { 1589 THROW_MSG(vmSymbols::java_lang_NullPointerException(), 1590 "The flag name cannot be null."); 1591 } 1592 char* name = java_lang_String::as_utf8_string(fn); 1593 1594 FormatBuffer<80> error_msg("%s", ""); 1595 int succeed = WriteableFlags::set_flag(name, new_value, JVMFlag::MANAGEMENT, error_msg); 1596 1597 if (succeed != JVMFlag::SUCCESS) { 1598 if (succeed == JVMFlag::MISSING_VALUE) { 1599 // missing value causes NPE to be thrown 1600 THROW(vmSymbols::java_lang_NullPointerException()); 1601 } else { 1602 // all the other errors are reported as IAE with the appropriate error message 1603 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), 1604 error_msg.buffer()); 1605 } 1606 } 1607 assert(succeed == JVMFlag::SUCCESS, "Setting flag should succeed"); 1608 JVM_END 1609 1610 class ThreadTimesClosure: public ThreadClosure { 1611 private: 1612 objArrayHandle _names_strings; 1613 char **_names_chars; 1614 typeArrayHandle _times; 1615 int _names_len; 1616 int _times_len; 1617 int _count; 1618 1619 public: 1620 ThreadTimesClosure(objArrayHandle names, typeArrayHandle times); 1621 ~ThreadTimesClosure(); 1622 virtual void do_thread(Thread* thread); 1623 void do_unlocked(); 1624 int count() { return _count; } 1625 }; 1626 1627 ThreadTimesClosure::ThreadTimesClosure(objArrayHandle names, 1628 typeArrayHandle times) { 1629 assert(names() != NULL, "names was NULL"); 1630 assert(times() != NULL, "times was NULL"); 1631 _names_strings = names; 1632 _names_len = names->length(); 1633 _names_chars = NEW_C_HEAP_ARRAY(char*, _names_len, mtInternal); 1634 _times = times; 1635 _times_len = times->length(); 1636 _count = 0; 1637 } 1638 1639 // 1640 // Called with Threads_lock held 1641 // 1642 void ThreadTimesClosure::do_thread(Thread* thread) { 1643 assert(Threads_lock->owned_by_self(), "Must hold Threads_lock"); 1644 assert(thread != NULL, "thread was NULL"); 1645 1646 // exclude externally visible JavaThreads 1647 if (thread->is_Java_thread() && !thread->is_hidden_from_external_view()) { 1648 return; 1649 } 1650 1651 if (_count >= _names_len || _count >= _times_len) { 1652 // skip if the result array is not big enough 1653 return; 1654 } 1655 1656 EXCEPTION_MARK; 1657 ResourceMark rm(THREAD); // thread->name() uses ResourceArea 1658 1659 assert(thread->name() != NULL, "All threads should have a name"); 1660 _names_chars[_count] = os::strdup(thread->name()); 1661 _times->long_at_put(_count, os::is_thread_cpu_time_supported() ? 1662 os::thread_cpu_time(thread) : -1); 1663 _count++; 1664 } 1665 1666 // Called without Threads_lock, we can allocate String objects. 1667 void ThreadTimesClosure::do_unlocked() { 1668 1669 EXCEPTION_MARK; 1670 for (int i = 0; i < _count; i++) { 1671 Handle s = java_lang_String::create_from_str(_names_chars[i], CHECK); 1672 _names_strings->obj_at_put(i, s()); 1673 } 1674 } 1675 1676 ThreadTimesClosure::~ThreadTimesClosure() { 1677 for (int i = 0; i < _count; i++) { 1678 os::free(_names_chars[i]); 1679 } 1680 FREE_C_HEAP_ARRAY(char *, _names_chars); 1681 } 1682 1683 // Fills names with VM internal thread names and times with the corresponding 1684 // CPU times. If names or times is NULL, a NullPointerException is thrown. 1685 // If the element type of names is not String, an IllegalArgumentException is 1686 // thrown. 1687 // If an array is not large enough to hold all the entries, only the entries 1688 // that fit will be returned. Return value is the number of VM internal 1689 // threads entries. 1690 JVM_ENTRY(jint, jmm_GetInternalThreadTimes(JNIEnv *env, 1691 jobjectArray names, 1692 jlongArray times)) 1693 if (names == NULL || times == NULL) { 1694 THROW_(vmSymbols::java_lang_NullPointerException(), 0); 1695 } 1696 objArrayOop na = objArrayOop(JNIHandles::resolve_non_null(names)); 1697 objArrayHandle names_ah(THREAD, na); 1698 1699 // Make sure we have a String array 1700 Klass* element_klass = ObjArrayKlass::cast(names_ah->klass())->element_klass(); 1701 if (element_klass != SystemDictionary::String_klass()) { 1702 THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(), 1703 "Array element type is not String class", 0); 1704 } 1705 1706 typeArrayOop ta = typeArrayOop(JNIHandles::resolve_non_null(times)); 1707 typeArrayHandle times_ah(THREAD, ta); 1708 1709 ThreadTimesClosure ttc(names_ah, times_ah); 1710 { 1711 MutexLockerEx ml(Threads_lock); 1712 Threads::threads_do(&ttc); 1713 } 1714 ttc.do_unlocked(); 1715 return ttc.count(); 1716 JVM_END 1717 1718 static Handle find_deadlocks(bool object_monitors_only, TRAPS) { 1719 ResourceMark rm(THREAD); 1720 1721 VM_FindDeadlocks op(!object_monitors_only /* also check concurrent locks? */); 1722 VMThread::execute(&op); 1723 1724 DeadlockCycle* deadlocks = op.result(); 1725 if (deadlocks == NULL) { 1726 // no deadlock found and return 1727 return Handle(); 1728 } 1729 1730 int num_threads = 0; 1731 DeadlockCycle* cycle; 1732 for (cycle = deadlocks; cycle != NULL; cycle = cycle->next()) { 1733 num_threads += cycle->num_threads(); 1734 } 1735 1736 objArrayOop r = oopFactory::new_objArray(SystemDictionary::Thread_klass(), num_threads, CHECK_NH); 1737 objArrayHandle threads_ah(THREAD, r); 1738 1739 int index = 0; 1740 for (cycle = deadlocks; cycle != NULL; cycle = cycle->next()) { 1741 GrowableArray<JavaThread*>* deadlock_threads = cycle->threads(); 1742 int len = deadlock_threads->length(); 1743 for (int i = 0; i < len; i++) { 1744 threads_ah->obj_at_put(index, deadlock_threads->at(i)->threadObj()); 1745 index++; 1746 } 1747 } 1748 return threads_ah; 1749 } 1750 1751 // Finds cycles of threads that are deadlocked involved in object monitors 1752 // and JSR-166 synchronizers. 1753 // Returns an array of Thread objects which are in deadlock, if any. 1754 // Otherwise, returns NULL. 1755 // 1756 // Input parameter: 1757 // object_monitors_only - if true, only check object monitors 1758 // 1759 JVM_ENTRY(jobjectArray, jmm_FindDeadlockedThreads(JNIEnv *env, jboolean object_monitors_only)) 1760 Handle result = find_deadlocks(object_monitors_only != 0, CHECK_0); 1761 return (jobjectArray) JNIHandles::make_local(env, result()); 1762 JVM_END 1763 1764 // Finds cycles of threads that are deadlocked on monitor locks 1765 // Returns an array of Thread objects which are in deadlock, if any. 1766 // Otherwise, returns NULL. 1767 JVM_ENTRY(jobjectArray, jmm_FindMonitorDeadlockedThreads(JNIEnv *env)) 1768 Handle result = find_deadlocks(true, CHECK_0); 1769 return (jobjectArray) JNIHandles::make_local(env, result()); 1770 JVM_END 1771 1772 // Gets the information about GC extension attributes including 1773 // the name of the attribute, its type, and a short description. 1774 // 1775 // Input parameters: 1776 // mgr - GC memory manager 1777 // info - caller allocated array of jmmExtAttributeInfo 1778 // count - number of elements of the info array 1779 // 1780 // Returns the number of GC extension attributes filled in the info array; or 1781 // -1 if info is not big enough 1782 // 1783 JVM_ENTRY(jint, jmm_GetGCExtAttributeInfo(JNIEnv *env, jobject mgr, jmmExtAttributeInfo* info, jint count)) 1784 // All GC memory managers have 1 attribute (number of GC threads) 1785 if (count == 0) { 1786 return 0; 1787 } 1788 1789 if (info == NULL) { 1790 THROW_(vmSymbols::java_lang_NullPointerException(), 0); 1791 } 1792 1793 info[0].name = "GcThreadCount"; 1794 info[0].type = 'I'; 1795 info[0].description = "Number of GC threads"; 1796 return 1; 1797 JVM_END 1798 1799 // verify the given array is an array of java/lang/management/MemoryUsage objects 1800 // of a given length and return the objArrayOop 1801 static objArrayOop get_memory_usage_objArray(jobjectArray array, int length, TRAPS) { 1802 if (array == NULL) { 1803 THROW_(vmSymbols::java_lang_NullPointerException(), 0); 1804 } 1805 1806 objArrayOop oa = objArrayOop(JNIHandles::resolve_non_null(array)); 1807 objArrayHandle array_h(THREAD, oa); 1808 1809 // array must be of the given length 1810 if (length != array_h->length()) { 1811 THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(), 1812 "The length of the given MemoryUsage array does not match the number of memory pools.", 0); 1813 } 1814 1815 // check if the element of array is of type MemoryUsage class 1816 Klass* usage_klass = Management::java_lang_management_MemoryUsage_klass(CHECK_0); 1817 Klass* element_klass = ObjArrayKlass::cast(array_h->klass())->element_klass(); 1818 if (element_klass != usage_klass) { 1819 THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(), 1820 "The element type is not MemoryUsage class", 0); 1821 } 1822 1823 return array_h(); 1824 } 1825 1826 // Gets the statistics of the last GC of a given GC memory manager. 1827 // Input parameters: 1828 // obj - GarbageCollectorMXBean object 1829 // gc_stat - caller allocated jmmGCStat where: 1830 // a. before_gc_usage - array of MemoryUsage objects 1831 // b. after_gc_usage - array of MemoryUsage objects 1832 // c. gc_ext_attributes_values_size is set to the 1833 // gc_ext_attribute_values array allocated 1834 // d. gc_ext_attribute_values is a caller allocated array of jvalue. 1835 // 1836 // On return, 1837 // gc_index == 0 indicates no GC statistics available 1838 // 1839 // before_gc_usage and after_gc_usage - filled with per memory pool 1840 // before and after GC usage in the same order as the memory pools 1841 // returned by GetMemoryPools for a given GC memory manager. 1842 // num_gc_ext_attributes indicates the number of elements in 1843 // the gc_ext_attribute_values array is filled; or 1844 // -1 if the gc_ext_attributes_values array is not big enough 1845 // 1846 JVM_ENTRY(void, jmm_GetLastGCStat(JNIEnv *env, jobject obj, jmmGCStat *gc_stat)) 1847 ResourceMark rm(THREAD); 1848 1849 if (gc_stat->gc_ext_attribute_values_size > 0 && gc_stat->gc_ext_attribute_values == NULL) { 1850 THROW(vmSymbols::java_lang_NullPointerException()); 1851 } 1852 1853 // Get the GCMemoryManager 1854 GCMemoryManager* mgr = get_gc_memory_manager_from_jobject(obj, CHECK); 1855 1856 // Make a copy of the last GC statistics 1857 // GC may occur while constructing the last GC information 1858 int num_pools = MemoryService::num_memory_pools(); 1859 GCStatInfo stat(num_pools); 1860 if (mgr->get_last_gc_stat(&stat) == 0) { 1861 gc_stat->gc_index = 0; 1862 return; 1863 } 1864 1865 gc_stat->gc_index = stat.gc_index(); 1866 gc_stat->start_time = Management::ticks_to_ms(stat.start_time()); 1867 gc_stat->end_time = Management::ticks_to_ms(stat.end_time()); 1868 1869 // Current implementation does not have GC extension attributes 1870 gc_stat->num_gc_ext_attributes = 0; 1871 1872 // Fill the arrays of MemoryUsage objects with before and after GC 1873 // per pool memory usage 1874 objArrayOop bu = get_memory_usage_objArray(gc_stat->usage_before_gc, 1875 num_pools, 1876 CHECK); 1877 objArrayHandle usage_before_gc_ah(THREAD, bu); 1878 1879 objArrayOop au = get_memory_usage_objArray(gc_stat->usage_after_gc, 1880 num_pools, 1881 CHECK); 1882 objArrayHandle usage_after_gc_ah(THREAD, au); 1883 1884 for (int i = 0; i < num_pools; i++) { 1885 Handle before_usage = MemoryService::create_MemoryUsage_obj(stat.before_gc_usage_for_pool(i), CHECK); 1886 Handle after_usage; 1887 1888 MemoryUsage u = stat.after_gc_usage_for_pool(i); 1889 if (u.max_size() == 0 && u.used() > 0) { 1890 // If max size == 0, this pool is a survivor space. 1891 // Set max size = -1 since the pools will be swapped after GC. 1892 MemoryUsage usage(u.init_size(), u.used(), u.committed(), (size_t)-1); 1893 after_usage = MemoryService::create_MemoryUsage_obj(usage, CHECK); 1894 } else { 1895 after_usage = MemoryService::create_MemoryUsage_obj(stat.after_gc_usage_for_pool(i), CHECK); 1896 } 1897 usage_before_gc_ah->obj_at_put(i, before_usage()); 1898 usage_after_gc_ah->obj_at_put(i, after_usage()); 1899 } 1900 1901 if (gc_stat->gc_ext_attribute_values_size > 0) { 1902 // Current implementation only has 1 attribute (number of GC threads) 1903 // The type is 'I' 1904 gc_stat->gc_ext_attribute_values[0].i = mgr->num_gc_threads(); 1905 } 1906 JVM_END 1907 1908 JVM_ENTRY(void, jmm_SetGCNotificationEnabled(JNIEnv *env, jobject obj, jboolean enabled)) 1909 ResourceMark rm(THREAD); 1910 // Get the GCMemoryManager 1911 GCMemoryManager* mgr = get_gc_memory_manager_from_jobject(obj, CHECK); 1912 mgr->set_notification_enabled(enabled?true:false); 1913 JVM_END 1914 1915 // Dump heap - Returns 0 if succeeds. 1916 JVM_ENTRY(jint, jmm_DumpHeap0(JNIEnv *env, jstring outputfile, jboolean live)) 1917 #if INCLUDE_SERVICES 1918 ResourceMark rm(THREAD); 1919 oop on = JNIHandles::resolve_external_guard(outputfile); 1920 if (on == NULL) { 1921 THROW_MSG_(vmSymbols::java_lang_NullPointerException(), 1922 "Output file name cannot be null.", -1); 1923 } 1924 Handle onhandle(THREAD, on); 1925 char* name = java_lang_String::as_platform_dependent_str(onhandle, CHECK_(-1)); 1926 if (name == NULL) { 1927 THROW_MSG_(vmSymbols::java_lang_NullPointerException(), 1928 "Output file name cannot be null.", -1); 1929 } 1930 HeapDumper dumper(live ? true : false); 1931 if (dumper.dump(name) != 0) { 1932 const char* errmsg = dumper.error_as_C_string(); 1933 THROW_MSG_(vmSymbols::java_io_IOException(), errmsg, -1); 1934 } 1935 return 0; 1936 #else // INCLUDE_SERVICES 1937 return -1; 1938 #endif // INCLUDE_SERVICES 1939 JVM_END 1940 1941 JVM_ENTRY(jobjectArray, jmm_GetDiagnosticCommands(JNIEnv *env)) 1942 ResourceMark rm(THREAD); 1943 GrowableArray<const char *>* dcmd_list = DCmdFactory::DCmd_list(DCmd_Source_MBean); 1944 objArrayOop cmd_array_oop = oopFactory::new_objArray(SystemDictionary::String_klass(), 1945 dcmd_list->length(), CHECK_NULL); 1946 objArrayHandle cmd_array(THREAD, cmd_array_oop); 1947 for (int i = 0; i < dcmd_list->length(); i++) { 1948 oop cmd_name = java_lang_String::create_oop_from_str(dcmd_list->at(i), CHECK_NULL); 1949 cmd_array->obj_at_put(i, cmd_name); 1950 } 1951 return (jobjectArray) JNIHandles::make_local(env, cmd_array()); 1952 JVM_END 1953 1954 JVM_ENTRY(void, jmm_GetDiagnosticCommandInfo(JNIEnv *env, jobjectArray cmds, 1955 dcmdInfo* infoArray)) 1956 if (cmds == NULL || infoArray == NULL) { 1957 THROW(vmSymbols::java_lang_NullPointerException()); 1958 } 1959 1960 ResourceMark rm(THREAD); 1961 1962 objArrayOop ca = objArrayOop(JNIHandles::resolve_non_null(cmds)); 1963 objArrayHandle cmds_ah(THREAD, ca); 1964 1965 // Make sure we have a String array 1966 Klass* element_klass = ObjArrayKlass::cast(cmds_ah->klass())->element_klass(); 1967 if (element_klass != SystemDictionary::String_klass()) { 1968 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), 1969 "Array element type is not String class"); 1970 } 1971 1972 GrowableArray<DCmdInfo *>* info_list = DCmdFactory::DCmdInfo_list(DCmd_Source_MBean); 1973 1974 int num_cmds = cmds_ah->length(); 1975 for (int i = 0; i < num_cmds; i++) { 1976 oop cmd = cmds_ah->obj_at(i); 1977 if (cmd == NULL) { 1978 THROW_MSG(vmSymbols::java_lang_NullPointerException(), 1979 "Command name cannot be null."); 1980 } 1981 char* cmd_name = java_lang_String::as_utf8_string(cmd); 1982 if (cmd_name == NULL) { 1983 THROW_MSG(vmSymbols::java_lang_NullPointerException(), 1984 "Command name cannot be null."); 1985 } 1986 int pos = info_list->find((void*)cmd_name,DCmdInfo::by_name); 1987 if (pos == -1) { 1988 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), 1989 "Unknown diagnostic command"); 1990 } 1991 DCmdInfo* info = info_list->at(pos); 1992 infoArray[i].name = info->name(); 1993 infoArray[i].description = info->description(); 1994 infoArray[i].impact = info->impact(); 1995 JavaPermission p = info->permission(); 1996 infoArray[i].permission_class = p._class; 1997 infoArray[i].permission_name = p._name; 1998 infoArray[i].permission_action = p._action; 1999 infoArray[i].num_arguments = info->num_arguments(); 2000 infoArray[i].enabled = info->is_enabled(); 2001 } 2002 JVM_END 2003 2004 JVM_ENTRY(void, jmm_GetDiagnosticCommandArgumentsInfo(JNIEnv *env, 2005 jstring command, dcmdArgInfo* infoArray)) 2006 ResourceMark rm(THREAD); 2007 oop cmd = JNIHandles::resolve_external_guard(command); 2008 if (cmd == NULL) { 2009 THROW_MSG(vmSymbols::java_lang_NullPointerException(), 2010 "Command line cannot be null."); 2011 } 2012 char* cmd_name = java_lang_String::as_utf8_string(cmd); 2013 if (cmd_name == NULL) { 2014 THROW_MSG(vmSymbols::java_lang_NullPointerException(), 2015 "Command line content cannot be null."); 2016 } 2017 DCmd* dcmd = NULL; 2018 DCmdFactory*factory = DCmdFactory::factory(DCmd_Source_MBean, cmd_name, 2019 strlen(cmd_name)); 2020 if (factory != NULL) { 2021 dcmd = factory->create_resource_instance(NULL); 2022 } 2023 if (dcmd == NULL) { 2024 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), 2025 "Unknown diagnostic command"); 2026 } 2027 DCmdMark mark(dcmd); 2028 GrowableArray<DCmdArgumentInfo*>* array = dcmd->argument_info_array(); 2029 if (array->length() == 0) { 2030 return; 2031 } 2032 for (int i = 0; i < array->length(); i++) { 2033 infoArray[i].name = array->at(i)->name(); 2034 infoArray[i].description = array->at(i)->description(); 2035 infoArray[i].type = array->at(i)->type(); 2036 infoArray[i].default_string = array->at(i)->default_string(); 2037 infoArray[i].mandatory = array->at(i)->is_mandatory(); 2038 infoArray[i].option = array->at(i)->is_option(); 2039 infoArray[i].multiple = array->at(i)->is_multiple(); 2040 infoArray[i].position = array->at(i)->position(); 2041 } 2042 return; 2043 JVM_END 2044 2045 JVM_ENTRY(jstring, jmm_ExecuteDiagnosticCommand(JNIEnv *env, jstring commandline)) 2046 ResourceMark rm(THREAD); 2047 oop cmd = JNIHandles::resolve_external_guard(commandline); 2048 if (cmd == NULL) { 2049 THROW_MSG_NULL(vmSymbols::java_lang_NullPointerException(), 2050 "Command line cannot be null."); 2051 } 2052 char* cmdline = java_lang_String::as_utf8_string(cmd); 2053 if (cmdline == NULL) { 2054 THROW_MSG_NULL(vmSymbols::java_lang_NullPointerException(), 2055 "Command line content cannot be null."); 2056 } 2057 bufferedStream output; 2058 DCmd::parse_and_execute(DCmd_Source_MBean, &output, cmdline, ' ', CHECK_NULL); 2059 oop result = java_lang_String::create_oop_from_str(output.as_string(), CHECK_NULL); 2060 return (jstring) JNIHandles::make_local(env, result); 2061 JVM_END 2062 2063 JVM_ENTRY(void, jmm_SetDiagnosticFrameworkNotificationEnabled(JNIEnv *env, jboolean enabled)) 2064 DCmdFactory::set_jmx_notification_enabled(enabled?true:false); 2065 JVM_END 2066 2067 jlong Management::ticks_to_ms(jlong ticks) { 2068 assert(os::elapsed_frequency() > 0, "Must be non-zero"); 2069 return (jlong)(((double)ticks / (double)os::elapsed_frequency()) 2070 * (double)1000.0); 2071 } 2072 #endif // INCLUDE_MANAGEMENT 2073 2074 // Gets an array containing the amount of memory allocated on the Java 2075 // heap for a set of threads (in bytes). Each element of the array is 2076 // the amount of memory allocated for the thread ID specified in the 2077 // corresponding entry in the given array of thread IDs; or -1 if the 2078 // thread does not exist or has terminated. 2079 JVM_ENTRY(void, jmm_GetThreadAllocatedMemory(JNIEnv *env, jlongArray ids, 2080 jlongArray sizeArray)) 2081 // Check if threads is null 2082 if (ids == NULL || sizeArray == NULL) { 2083 THROW(vmSymbols::java_lang_NullPointerException()); 2084 } 2085 2086 ResourceMark rm(THREAD); 2087 typeArrayOop ta = typeArrayOop(JNIHandles::resolve_non_null(ids)); 2088 typeArrayHandle ids_ah(THREAD, ta); 2089 2090 typeArrayOop sa = typeArrayOop(JNIHandles::resolve_non_null(sizeArray)); 2091 typeArrayHandle sizeArray_h(THREAD, sa); 2092 2093 // validate the thread id array 2094 validate_thread_id_array(ids_ah, CHECK); 2095 2096 // sizeArray must be of the same length as the given array of thread IDs 2097 int num_threads = ids_ah->length(); 2098 if (num_threads != sizeArray_h->length()) { 2099 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), 2100 "The length of the given long array does not match the length of " 2101 "the given array of thread IDs"); 2102 } 2103 2104 ThreadsListHandle tlh; 2105 for (int i = 0; i < num_threads; i++) { 2106 JavaThread* java_thread = tlh.list()->find_JavaThread_from_java_tid(ids_ah->long_at(i)); 2107 if (java_thread != NULL) { 2108 sizeArray_h->long_at_put(i, java_thread->cooked_allocated_bytes()); 2109 } 2110 } 2111 JVM_END 2112 2113 // Returns the CPU time consumed by a given thread (in nanoseconds). 2114 // If thread_id == 0, CPU time for the current thread is returned. 2115 // If user_sys_cpu_time = true, user level and system CPU time of 2116 // a given thread is returned; otherwise, only user level CPU time 2117 // is returned. 2118 JVM_ENTRY(jlong, jmm_GetThreadCpuTimeWithKind(JNIEnv *env, jlong thread_id, jboolean user_sys_cpu_time)) 2119 if (!os::is_thread_cpu_time_supported()) { 2120 return -1; 2121 } 2122 2123 if (thread_id < 0) { 2124 THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(), 2125 "Invalid thread ID", -1); 2126 } 2127 2128 JavaThread* java_thread = NULL; 2129 if (thread_id == 0) { 2130 // current thread 2131 return os::current_thread_cpu_time(user_sys_cpu_time != 0); 2132 } else { 2133 ThreadsListHandle tlh; 2134 java_thread = tlh.list()->find_JavaThread_from_java_tid(thread_id); 2135 if (java_thread != NULL) { 2136 return os::thread_cpu_time((Thread*) java_thread, user_sys_cpu_time != 0); 2137 } 2138 } 2139 return -1; 2140 JVM_END 2141 2142 // Gets an array containing the CPU times consumed by a set of threads 2143 // (in nanoseconds). Each element of the array is the CPU time for the 2144 // thread ID specified in the corresponding entry in the given array 2145 // of thread IDs; or -1 if the thread does not exist or has terminated. 2146 // If user_sys_cpu_time = true, the sum of user level and system CPU time 2147 // for the given thread is returned; otherwise, only user level CPU time 2148 // is returned. 2149 JVM_ENTRY(void, jmm_GetThreadCpuTimesWithKind(JNIEnv *env, jlongArray ids, 2150 jlongArray timeArray, 2151 jboolean user_sys_cpu_time)) 2152 // Check if threads is null 2153 if (ids == NULL || timeArray == NULL) { 2154 THROW(vmSymbols::java_lang_NullPointerException()); 2155 } 2156 2157 ResourceMark rm(THREAD); 2158 typeArrayOop ta = typeArrayOop(JNIHandles::resolve_non_null(ids)); 2159 typeArrayHandle ids_ah(THREAD, ta); 2160 2161 typeArrayOop tia = typeArrayOop(JNIHandles::resolve_non_null(timeArray)); 2162 typeArrayHandle timeArray_h(THREAD, tia); 2163 2164 // validate the thread id array 2165 validate_thread_id_array(ids_ah, CHECK); 2166 2167 // timeArray must be of the same length as the given array of thread IDs 2168 int num_threads = ids_ah->length(); 2169 if (num_threads != timeArray_h->length()) { 2170 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), 2171 "The length of the given long array does not match the length of " 2172 "the given array of thread IDs"); 2173 } 2174 2175 ThreadsListHandle tlh; 2176 for (int i = 0; i < num_threads; i++) { 2177 JavaThread* java_thread = tlh.list()->find_JavaThread_from_java_tid(ids_ah->long_at(i)); 2178 if (java_thread != NULL) { 2179 timeArray_h->long_at_put(i, os::thread_cpu_time((Thread*)java_thread, 2180 user_sys_cpu_time != 0)); 2181 } 2182 } 2183 JVM_END 2184 2185 2186 2187 #if INCLUDE_MANAGEMENT 2188 const struct jmmInterface_1_ jmm_interface = { 2189 NULL, 2190 NULL, 2191 jmm_GetVersion, 2192 jmm_GetOptionalSupport, 2193 jmm_GetThreadInfo, 2194 jmm_GetMemoryPools, 2195 jmm_GetMemoryManagers, 2196 jmm_GetMemoryPoolUsage, 2197 jmm_GetPeakMemoryPoolUsage, 2198 jmm_GetThreadAllocatedMemory, 2199 jmm_GetMemoryUsage, 2200 jmm_GetLongAttribute, 2201 jmm_GetBoolAttribute, 2202 jmm_SetBoolAttribute, 2203 jmm_GetLongAttributes, 2204 jmm_FindMonitorDeadlockedThreads, 2205 jmm_GetThreadCpuTime, 2206 jmm_GetVMGlobalNames, 2207 jmm_GetVMGlobals, 2208 jmm_GetInternalThreadTimes, 2209 jmm_ResetStatistic, 2210 jmm_SetPoolSensor, 2211 jmm_SetPoolThreshold, 2212 jmm_GetPoolCollectionUsage, 2213 jmm_GetGCExtAttributeInfo, 2214 jmm_GetLastGCStat, 2215 jmm_GetThreadCpuTimeWithKind, 2216 jmm_GetThreadCpuTimesWithKind, 2217 jmm_DumpHeap0, 2218 jmm_FindDeadlockedThreads, 2219 jmm_SetVMGlobal, 2220 NULL, 2221 jmm_DumpThreads, 2222 jmm_SetGCNotificationEnabled, 2223 jmm_GetDiagnosticCommands, 2224 jmm_GetDiagnosticCommandInfo, 2225 jmm_GetDiagnosticCommandArgumentsInfo, 2226 jmm_ExecuteDiagnosticCommand, 2227 jmm_SetDiagnosticFrameworkNotificationEnabled 2228 }; 2229 #endif // INCLUDE_MANAGEMENT 2230 2231 void* Management::get_jmm_interface(int version) { 2232 #if INCLUDE_MANAGEMENT 2233 if (version == JMM_VERSION) { 2234 return (void*) &jmm_interface; 2235 } 2236 #endif // INCLUDE_MANAGEMENT 2237 return NULL; 2238 } --- EOF ---