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