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