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