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