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