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