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