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