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