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