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