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