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