management.cpp 81.8 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
19 20 21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
22 23 24
 *
 */

25 26 27 28 29 30 31 32 33 34
#include "precompiled.hpp"
#include "classfile/systemDictionary.hpp"
#include "compiler/compileBroker.hpp"
#include "memory/iterator.hpp"
#include "memory/oopFactory.hpp"
#include "memory/resourceArea.hpp"
#include "oops/klass.hpp"
#include "oops/objArrayKlass.hpp"
#include "oops/oop.inline.hpp"
#include "runtime/arguments.hpp"
35
#include "runtime/globals.hpp"
36 37 38 39 40
#include "runtime/handles.inline.hpp"
#include "runtime/interfaceSupport.hpp"
#include "runtime/javaCalls.hpp"
#include "runtime/jniHandles.hpp"
#include "runtime/os.hpp"
41
#include "runtime/serviceThread.hpp"
42
#include "runtime/thread.inline.hpp"
43
#include "services/classLoadingService.hpp"
44 45
#include "services/diagnosticCommand.hpp"
#include "services/diagnosticFramework.hpp"
46
#include "services/heapDumper.hpp"
47
#include "services/jmm.h"
48
#include "services/lowMemoryDetector.hpp"
49
#include "services/gcNotifier.hpp"
Z
zgu 已提交
50
#include "services/nmtDCmd.hpp"
51 52 53 54 55 56
#include "services/management.hpp"
#include "services/memoryManager.hpp"
#include "services/memoryPool.hpp"
#include "services/memoryService.hpp"
#include "services/runtimeService.hpp"
#include "services/threadService.hpp"
57
#include "utilities/macros.hpp"
D
duke 已提交
58

59 60
PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC

D
duke 已提交
61 62 63 64
PerfVariable* Management::_begin_vm_creation_time = NULL;
PerfVariable* Management::_end_vm_creation_time = NULL;
PerfVariable* Management::_vm_init_done_time = NULL;

65 66 67 68 69 70 71 72 73
Klass* Management::_sensor_klass = NULL;
Klass* Management::_threadInfo_klass = NULL;
Klass* Management::_memoryUsage_klass = NULL;
Klass* Management::_memoryPoolMXBean_klass = NULL;
Klass* Management::_memoryManagerMXBean_klass = NULL;
Klass* Management::_garbageCollectorMXBean_klass = NULL;
Klass* Management::_managementFactory_klass = NULL;
Klass* Management::_garbageCollectorImpl_klass = NULL;
Klass* Management::_gcInfo_klass = NULL;
74 75 76
Klass* Management::_diagnosticCommandImpl_klass = NULL;
Klass* Management::_managementFactoryHelper_klass = NULL;

D
duke 已提交
77 78 79 80 81

jmmOptionalSupport Management::_optional_support = {0};
TimeStamp Management::_stamp;

void management_init() {
82
#if INCLUDE_MANAGEMENT
D
duke 已提交
83 84 85 86
  Management::init();
  ThreadService::init();
  RuntimeService::init();
  ClassLoadingService::init();
87 88 89 90 91 92 93
#else
  ThreadService::init();
  // Make sure the VM version is initialized
  // This is normally called by RuntimeService::init().
  // Since that is conditionalized out, we need to call it here.
  Abstract_VM_Version::initialize();
#endif // INCLUDE_MANAGEMENT
D
duke 已提交
94 95
}

96 97
#if INCLUDE_MANAGEMENT

D
duke 已提交
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
void Management::init() {
  EXCEPTION_MARK;

  // These counters are for java.lang.management API support.
  // They are created even if -XX:-UsePerfData is set and in
  // that case, they will be allocated on C heap.

  _begin_vm_creation_time =
            PerfDataManager::create_variable(SUN_RT, "createVmBeginTime",
                                             PerfData::U_None, CHECK);

  _end_vm_creation_time =
            PerfDataManager::create_variable(SUN_RT, "createVmEndTime",
                                             PerfData::U_None, CHECK);

  _vm_init_done_time =
            PerfDataManager::create_variable(SUN_RT, "vmInitDoneTime",
                                             PerfData::U_None, CHECK);

  // Initialize optional support
  _optional_support.isLowMemoryDetectionSupported = 1;
  _optional_support.isCompilationTimeMonitoringSupported = 1;
  _optional_support.isThreadContentionMonitoringSupported = 1;

  if (os::is_thread_cpu_time_supported()) {
    _optional_support.isCurrentThreadCpuTimeSupported = 1;
    _optional_support.isOtherThreadCpuTimeSupported = 1;
  } else {
    _optional_support.isCurrentThreadCpuTimeSupported = 0;
    _optional_support.isOtherThreadCpuTimeSupported = 0;
  }
129

D
duke 已提交
130 131
  _optional_support.isBootClassPathSupported = 1;
  _optional_support.isObjectMonitorUsageSupported = 1;
132
#if INCLUDE_SERVICES
D
duke 已提交
133 134
  // This depends on the heap inspector
  _optional_support.isSynchronizerUsageSupported = 1;
135
#endif // INCLUDE_SERVICES
136
  _optional_support.isThreadAllocatedMemorySupported = 1;
137
  _optional_support.isRemoteDiagnosticCommandsSupported = 1;
138

F
fparain 已提交
139
  // Registration of the diagnostic commands
140 141
  DCmdRegistrant::register_dcmds();
  DCmdRegistrant::register_dcmds_ext();
142 143 144
  uint32_t full_export = DCmd_Source_Internal | DCmd_Source_AttachAPI
                         | DCmd_Source_MBean;
  DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<NMTDCmd>(full_export, true, false));
D
duke 已提交
145 146 147
}

void Management::initialize(TRAPS) {
148 149
  // Start the service thread
  ServiceThread::initialize();
D
duke 已提交
150 151 152 153 154 155 156 157

  if (ManagementServer) {
    ResourceMark rm(THREAD);
    HandleMark hm(THREAD);

    // Load and initialize the sun.management.Agent class
    // invoke startAgent method to start the management server
    Handle loader = Handle(THREAD, SystemDictionary::java_system_loader());
158
    Klass* k = SystemDictionary::resolve_or_null(vmSymbols::sun_management_Agent(),
D
duke 已提交
159 160
                                                   loader,
                                                   Handle(),
161 162 163 164 165
                                                   THREAD);
    if (k == NULL) {
      vm_exit_during_initialization("Management agent initialization failure: "
          "class sun.management.Agent not found.");
    }
D
duke 已提交
166 167 168 169 170
    instanceKlassHandle ik (THREAD, k);

    JavaValue result(T_VOID);
    JavaCalls::call_static(&result,
                           ik,
171 172
                           vmSymbols::startAgent_name(),
                           vmSymbols::void_method_signature(),
D
duke 已提交
173 174 175 176 177 178 179 180
                           CHECK);
  }
}

void Management::get_optional_support(jmmOptionalSupport* support) {
  memcpy(support, &_optional_support, sizeof(jmmOptionalSupport));
}

181 182
Klass* Management::load_and_initialize_klass(Symbol* sh, TRAPS) {
  Klass* k = SystemDictionary::resolve_or_fail(sh, true, CHECK_NULL);
D
duke 已提交
183 184 185 186
  instanceKlassHandle ik (THREAD, k);
  if (ik->should_be_initialized()) {
    ik->initialize(CHECK_NULL);
  }
187 188 189
  // If these classes change to not be owned by the boot loader, they need
  // to be walked to keep their class loader alive in oops_do.
  assert(ik->class_loader() == NULL, "need to follow in oops_do");
D
duke 已提交
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
  return ik();
}

void Management::record_vm_startup_time(jlong begin, jlong duration) {
  // if the performance counter is not initialized,
  // then vm initialization failed; simply return.
  if (_begin_vm_creation_time == NULL) return;

  _begin_vm_creation_time->set_value(begin);
  _end_vm_creation_time->set_value(begin + duration);
  PerfMemory::set_accessible(true);
}

jlong Management::timestamp() {
  TimeStamp t;
  t.update();
  return t.ticks() - _stamp.ticks();
}

void Management::oops_do(OopClosure* f) {
  MemoryService::oops_do(f);
  ThreadService::oops_do(f);
}

214
Klass* Management::java_lang_management_ThreadInfo_klass(TRAPS) {
D
duke 已提交
215
  if (_threadInfo_klass == NULL) {
216
    _threadInfo_klass = load_and_initialize_klass(vmSymbols::java_lang_management_ThreadInfo(), CHECK_NULL);
D
duke 已提交
217 218 219 220
  }
  return _threadInfo_klass;
}

221
Klass* Management::java_lang_management_MemoryUsage_klass(TRAPS) {
D
duke 已提交
222
  if (_memoryUsage_klass == NULL) {
223
    _memoryUsage_klass = load_and_initialize_klass(vmSymbols::java_lang_management_MemoryUsage(), CHECK_NULL);
D
duke 已提交
224 225 226 227
  }
  return _memoryUsage_klass;
}

228
Klass* Management::java_lang_management_MemoryPoolMXBean_klass(TRAPS) {
D
duke 已提交
229
  if (_memoryPoolMXBean_klass == NULL) {
230
    _memoryPoolMXBean_klass = load_and_initialize_klass(vmSymbols::java_lang_management_MemoryPoolMXBean(), CHECK_NULL);
D
duke 已提交
231 232 233 234
  }
  return _memoryPoolMXBean_klass;
}

235
Klass* Management::java_lang_management_MemoryManagerMXBean_klass(TRAPS) {
D
duke 已提交
236
  if (_memoryManagerMXBean_klass == NULL) {
237
    _memoryManagerMXBean_klass = load_and_initialize_klass(vmSymbols::java_lang_management_MemoryManagerMXBean(), CHECK_NULL);
D
duke 已提交
238 239 240 241
  }
  return _memoryManagerMXBean_klass;
}

242
Klass* Management::java_lang_management_GarbageCollectorMXBean_klass(TRAPS) {
D
duke 已提交
243
  if (_garbageCollectorMXBean_klass == NULL) {
244
      _garbageCollectorMXBean_klass = load_and_initialize_klass(vmSymbols::java_lang_management_GarbageCollectorMXBean(), CHECK_NULL);
D
duke 已提交
245 246 247 248
  }
  return _garbageCollectorMXBean_klass;
}

249
Klass* Management::sun_management_Sensor_klass(TRAPS) {
D
duke 已提交
250
  if (_sensor_klass == NULL) {
251
    _sensor_klass = load_and_initialize_klass(vmSymbols::sun_management_Sensor(), CHECK_NULL);
D
duke 已提交
252 253 254 255
  }
  return _sensor_klass;
}

256
Klass* Management::sun_management_ManagementFactory_klass(TRAPS) {
D
duke 已提交
257
  if (_managementFactory_klass == NULL) {
258
    _managementFactory_klass = load_and_initialize_klass(vmSymbols::sun_management_ManagementFactory(), CHECK_NULL);
D
duke 已提交
259 260 261 262
  }
  return _managementFactory_klass;
}

263
Klass* Management::sun_management_GarbageCollectorImpl_klass(TRAPS) {
264 265 266 267 268 269
  if (_garbageCollectorImpl_klass == NULL) {
    _garbageCollectorImpl_klass = load_and_initialize_klass(vmSymbols::sun_management_GarbageCollectorImpl(), CHECK_NULL);
  }
  return _garbageCollectorImpl_klass;
}

270
Klass* Management::com_sun_management_GcInfo_klass(TRAPS) {
271 272 273 274 275 276
  if (_gcInfo_klass == NULL) {
    _gcInfo_klass = load_and_initialize_klass(vmSymbols::com_sun_management_GcInfo(), CHECK_NULL);
  }
  return _gcInfo_klass;
}

277 278 279 280 281 282 283 284 285 286 287 288 289 290
Klass* Management::sun_management_DiagnosticCommandImpl_klass(TRAPS) {
  if (_diagnosticCommandImpl_klass == NULL) {
    _diagnosticCommandImpl_klass = load_and_initialize_klass(vmSymbols::sun_management_DiagnosticCommandImpl(), CHECK_NULL);
  }
  return _diagnosticCommandImpl_klass;
}

Klass* Management::sun_management_ManagementFactoryHelper_klass(TRAPS) {
  if (_managementFactoryHelper_klass == NULL) {
    _managementFactoryHelper_klass = load_and_initialize_klass(vmSymbols::sun_management_ManagementFactoryHelper(), CHECK_NULL);
  }
  return _managementFactoryHelper_klass;
}

D
duke 已提交
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
static void initialize_ThreadInfo_constructor_arguments(JavaCallArguments* args, ThreadSnapshot* snapshot, TRAPS) {
  Handle snapshot_thread(THREAD, snapshot->threadObj());

  jlong contended_time;
  jlong waited_time;
  if (ThreadService::is_thread_monitoring_contention()) {
    contended_time = Management::ticks_to_ms(snapshot->contended_enter_ticks());
    waited_time = Management::ticks_to_ms(snapshot->monitor_wait_ticks() + snapshot->sleep_ticks());
  } else {
    // set them to -1 if thread contention monitoring is disabled.
    contended_time = max_julong;
    waited_time = max_julong;
  }

  int thread_status = snapshot->thread_status();
  assert((thread_status & JMM_THREAD_STATE_FLAG_MASK) == 0, "Flags already set in thread_status in Thread object");
  if (snapshot->is_ext_suspended()) {
    thread_status |= JMM_THREAD_STATE_FLAG_SUSPENDED;
  }
  if (snapshot->is_in_native()) {
    thread_status |= JMM_THREAD_STATE_FLAG_NATIVE;
  }

  ThreadStackTrace* st = snapshot->get_stack_trace();
  Handle stacktrace_h;
  if (st != NULL) {
    stacktrace_h = st->allocate_fill_stack_trace_element_array(CHECK);
  } else {
    stacktrace_h = Handle();
  }

  args->push_oop(snapshot_thread);
  args->push_int(thread_status);
  args->push_oop(Handle(THREAD, snapshot->blocker_object()));
  args->push_oop(Handle(THREAD, snapshot->blocker_object_owner()));
  args->push_long(snapshot->contended_enter_count());
  args->push_long(contended_time);
  args->push_long(snapshot->monitor_wait_count() + snapshot->sleep_count());
  args->push_long(waited_time);
  args->push_oop(stacktrace_h);
}

// Helper function to construct a ThreadInfo object
instanceOop Management::create_thread_info_instance(ThreadSnapshot* snapshot, TRAPS) {
335
  Klass* k = Management::java_lang_management_ThreadInfo_klass(CHECK_NULL);
D
duke 已提交
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
  instanceKlassHandle ik (THREAD, k);

  JavaValue result(T_VOID);
  JavaCallArguments args(14);

  // First allocate a ThreadObj object and
  // push the receiver as the first argument
  Handle element = ik->allocate_instance_handle(CHECK_NULL);
  args.push_oop(element);

  // initialize the arguments for the ThreadInfo constructor
  initialize_ThreadInfo_constructor_arguments(&args, snapshot, CHECK_NULL);

  // Call ThreadInfo constructor with no locked monitors and synchronizers
  JavaCalls::call_special(&result,
                          ik,
352 353
                          vmSymbols::object_initializer_name(),
                          vmSymbols::java_lang_management_ThreadInfo_constructor_signature(),
D
duke 已提交
354 355 356 357 358 359 360 361 362 363 364
                          &args,
                          CHECK_NULL);

  return (instanceOop) element();
}

instanceOop Management::create_thread_info_instance(ThreadSnapshot* snapshot,
                                                    objArrayHandle monitors_array,
                                                    typeArrayHandle depths_array,
                                                    objArrayHandle synchronizers_array,
                                                    TRAPS) {
365
  Klass* k = Management::java_lang_management_ThreadInfo_klass(CHECK_NULL);
D
duke 已提交
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
  instanceKlassHandle ik (THREAD, k);

  JavaValue result(T_VOID);
  JavaCallArguments args(17);

  // First allocate a ThreadObj object and
  // push the receiver as the first argument
  Handle element = ik->allocate_instance_handle(CHECK_NULL);
  args.push_oop(element);

  // initialize the arguments for the ThreadInfo constructor
  initialize_ThreadInfo_constructor_arguments(&args, snapshot, CHECK_NULL);

  // push the locked monitors and synchronizers in the arguments
  args.push_oop(monitors_array);
  args.push_oop(depths_array);
  args.push_oop(synchronizers_array);

  // Call ThreadInfo constructor with locked monitors and synchronizers
  JavaCalls::call_special(&result,
                          ik,
387 388
                          vmSymbols::object_initializer_name(),
                          vmSymbols::java_lang_management_ThreadInfo_with_locks_constructor_signature(),
D
duke 已提交
389 390 391 392 393 394 395 396 397 398 399 400 401 402
                          &args,
                          CHECK_NULL);

  return (instanceOop) element();
}


static GCMemoryManager* get_gc_memory_manager_from_jobject(jobject mgr, TRAPS) {
  if (mgr == NULL) {
    THROW_(vmSymbols::java_lang_NullPointerException(), NULL);
  }
  oop mgr_obj = JNIHandles::resolve(mgr);
  instanceHandle h(THREAD, (instanceOop) mgr_obj);

403
  Klass* k = Management::java_lang_management_GarbageCollectorMXBean_klass(CHECK_NULL);
D
duke 已提交
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
  if (!h->is_a(k)) {
    THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
               "the object is not an instance of java.lang.management.GarbageCollectorMXBean class",
               NULL);
  }

  MemoryManager* gc = MemoryService::get_memory_manager(h);
  if (gc == NULL || !gc->is_gc_memory_manager()) {
    THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
               "Invalid GC memory manager",
               NULL);
  }
  return (GCMemoryManager*) gc;
}

static MemoryPool* get_memory_pool_from_jobject(jobject obj, TRAPS) {
  if (obj == NULL) {
    THROW_(vmSymbols::java_lang_NullPointerException(), NULL);
  }

  oop pool_obj = JNIHandles::resolve(obj);
  assert(pool_obj->is_instance(), "Should be an instanceOop");
  instanceHandle ph(THREAD, (instanceOop) pool_obj);

  return MemoryService::get_memory_pool(ph);
}

S
sla 已提交
431 432
#endif // INCLUDE_MANAGEMENT

D
duke 已提交
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
static void validate_thread_id_array(typeArrayHandle ids_ah, TRAPS) {
  int num_threads = ids_ah->length();

  // Validate input thread IDs
  int i = 0;
  for (i = 0; i < num_threads; i++) {
    jlong tid = ids_ah->long_at(i);
    if (tid <= 0) {
      // throw exception if invalid thread id.
      THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
                "Invalid thread ID entry");
    }
  }
}

S
sla 已提交
448 449
#if INCLUDE_MANAGEMENT

D
duke 已提交
450 451
static void validate_thread_info_array(objArrayHandle infoArray_h, TRAPS) {
  // check if the element of infoArray is of type ThreadInfo class
452
  Klass* threadinfo_klass = Management::java_lang_management_ThreadInfo_klass(CHECK);
453
  Klass* element_klass = ObjArrayKlass::cast(infoArray_h->klass())->element_klass();
D
duke 已提交
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
  if (element_klass != threadinfo_klass) {
    THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
              "infoArray element type is not ThreadInfo class");
  }
}


static MemoryManager* get_memory_manager_from_jobject(jobject obj, TRAPS) {
  if (obj == NULL) {
    THROW_(vmSymbols::java_lang_NullPointerException(), NULL);
  }

  oop mgr_obj = JNIHandles::resolve(obj);
  assert(mgr_obj->is_instance(), "Should be an instanceOop");
  instanceHandle mh(THREAD, (instanceOop) mgr_obj);

  return MemoryService::get_memory_manager(mh);
}

// Returns a version string and sets major and minor version if
// the input parameters are non-null.
JVM_LEAF(jint, jmm_GetVersion(JNIEnv *env))
  return JMM_VERSION;
JVM_END

// Gets the list of VM monitoring and management optional supports
// Returns 0 if succeeded; otherwise returns non-zero.
JVM_LEAF(jint, jmm_GetOptionalSupport(JNIEnv *env, jmmOptionalSupport* support))
  if (support == NULL) {
    return -1;
  }
  Management::get_optional_support(support);
  return 0;
JVM_END

// Returns a java.lang.String object containing the input arguments to the VM.
JVM_ENTRY(jobject, jmm_GetInputArguments(JNIEnv *env))
  ResourceMark rm(THREAD);

  if (Arguments::num_jvm_args() == 0 && Arguments::num_jvm_flags() == 0) {
    return NULL;
  }

  char** vm_flags = Arguments::jvm_flags_array();
  char** vm_args  = Arguments::jvm_args_array();
  int num_flags   = Arguments::num_jvm_flags();
  int num_args    = Arguments::num_jvm_args();

  size_t length = 1; // null terminator
  int i;
  for (i = 0; i < num_flags; i++) {
    length += strlen(vm_flags[i]);
  }
  for (i = 0; i < num_args; i++) {
    length += strlen(vm_args[i]);
  }
  // add a space between each argument
  length += num_flags + num_args - 1;

  // Return the list of input arguments passed to the VM
  // and preserve the order that the VM processes.
  char* args = NEW_RESOURCE_ARRAY(char, length);
  args[0] = '\0';
  // concatenate all jvm_flags
  if (num_flags > 0) {
    strcat(args, vm_flags[0]);
    for (i = 1; i < num_flags; i++) {
      strcat(args, " ");
      strcat(args, vm_flags[i]);
    }
  }

  if (num_args > 0 && num_flags > 0) {
    // append a space if args already contains one or more jvm_flags
    strcat(args, " ");
  }

  // concatenate all jvm_args
  if (num_args > 0) {
    strcat(args, vm_args[0]);
    for (i = 1; i < num_args; i++) {
      strcat(args, " ");
      strcat(args, vm_args[i]);
    }
  }

  Handle hargs = java_lang_String::create_from_platform_dependent_str(args, CHECK_NULL);
  return JNIHandles::make_local(env, hargs());
JVM_END

// Returns an array of java.lang.String object containing the input arguments to the VM.
JVM_ENTRY(jobjectArray, jmm_GetInputArgumentArray(JNIEnv *env))
  ResourceMark rm(THREAD);

  if (Arguments::num_jvm_args() == 0 && Arguments::num_jvm_flags() == 0) {
    return NULL;
  }

  char** vm_flags = Arguments::jvm_flags_array();
  char** vm_args = Arguments::jvm_args_array();
  int num_flags = Arguments::num_jvm_flags();
  int num_args = Arguments::num_jvm_args();

557
  instanceKlassHandle ik (THREAD, SystemDictionary::String_klass());
D
duke 已提交
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
  objArrayOop r = oopFactory::new_objArray(ik(), num_args + num_flags, CHECK_NULL);
  objArrayHandle result_h(THREAD, r);

  int index = 0;
  for (int j = 0; j < num_flags; j++, index++) {
    Handle h = java_lang_String::create_from_platform_dependent_str(vm_flags[j], CHECK_NULL);
    result_h->obj_at_put(index, h());
  }
  for (int i = 0; i < num_args; i++, index++) {
    Handle h = java_lang_String::create_from_platform_dependent_str(vm_args[i], CHECK_NULL);
    result_h->obj_at_put(index, h());
  }
  return (jobjectArray) JNIHandles::make_local(env, result_h());
JVM_END

// Returns an array of java/lang/management/MemoryPoolMXBean object
// one for each memory pool if obj == null; otherwise returns
// an array of memory pools for a given memory manager if
// it is a valid memory manager.
JVM_ENTRY(jobjectArray, jmm_GetMemoryPools(JNIEnv* env, jobject obj))
  ResourceMark rm(THREAD);

  int num_memory_pools;
  MemoryManager* mgr = NULL;
  if (obj == NULL) {
    num_memory_pools = MemoryService::num_memory_pools();
  } else {
    mgr = get_memory_manager_from_jobject(obj, CHECK_NULL);
    if (mgr == NULL) {
      return NULL;
    }
    num_memory_pools = mgr->num_memory_pools();
  }

  // Allocate the resulting MemoryPoolMXBean[] object
593
  Klass* k = Management::java_lang_management_MemoryPoolMXBean_klass(CHECK_NULL);
D
duke 已提交
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
  instanceKlassHandle ik (THREAD, k);
  objArrayOop r = oopFactory::new_objArray(ik(), num_memory_pools, CHECK_NULL);
  objArrayHandle poolArray(THREAD, r);

  if (mgr == NULL) {
    // Get all memory pools
    for (int i = 0; i < num_memory_pools; i++) {
      MemoryPool* pool = MemoryService::get_memory_pool(i);
      instanceOop p = pool->get_memory_pool_instance(CHECK_NULL);
      instanceHandle ph(THREAD, p);
      poolArray->obj_at_put(i, ph());
    }
  } else {
    // Get memory pools managed by a given memory manager
    for (int i = 0; i < num_memory_pools; i++) {
      MemoryPool* pool = mgr->get_memory_pool(i);
      instanceOop p = pool->get_memory_pool_instance(CHECK_NULL);
      instanceHandle ph(THREAD, p);
      poolArray->obj_at_put(i, ph());
    }
  }
  return (jobjectArray) JNIHandles::make_local(env, poolArray());
JVM_END

// Returns an array of java/lang/management/MemoryManagerMXBean object
// one for each memory manager if obj == null; otherwise returns
// an array of memory managers for a given memory pool if
// it is a valid memory pool.
JVM_ENTRY(jobjectArray, jmm_GetMemoryManagers(JNIEnv* env, jobject obj))
  ResourceMark rm(THREAD);

  int num_mgrs;
  MemoryPool* pool = NULL;
  if (obj == NULL) {
    num_mgrs = MemoryService::num_memory_managers();
  } else {
    pool = get_memory_pool_from_jobject(obj, CHECK_NULL);
    if (pool == NULL) {
      return NULL;
    }
    num_mgrs = pool->num_memory_managers();
  }

  // Allocate the resulting MemoryManagerMXBean[] object
638
  Klass* k = Management::java_lang_management_MemoryManagerMXBean_klass(CHECK_NULL);
D
duke 已提交
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
  instanceKlassHandle ik (THREAD, k);
  objArrayOop r = oopFactory::new_objArray(ik(), num_mgrs, CHECK_NULL);
  objArrayHandle mgrArray(THREAD, r);

  if (pool == NULL) {
    // Get all memory managers
    for (int i = 0; i < num_mgrs; i++) {
      MemoryManager* mgr = MemoryService::get_memory_manager(i);
      instanceOop p = mgr->get_memory_manager_instance(CHECK_NULL);
      instanceHandle ph(THREAD, p);
      mgrArray->obj_at_put(i, ph());
    }
  } else {
    // Get memory managers for a given memory pool
    for (int i = 0; i < num_mgrs; i++) {
      MemoryManager* mgr = pool->get_memory_manager(i);
      instanceOop p = mgr->get_memory_manager_instance(CHECK_NULL);
      instanceHandle ph(THREAD, p);
      mgrArray->obj_at_put(i, ph());
    }
  }
  return (jobjectArray) JNIHandles::make_local(env, mgrArray());
JVM_END


// Returns a java/lang/management/MemoryUsage object containing the memory usage
// of a given memory pool.
JVM_ENTRY(jobject, jmm_GetMemoryPoolUsage(JNIEnv* env, jobject obj))
  ResourceMark rm(THREAD);

  MemoryPool* pool = get_memory_pool_from_jobject(obj, CHECK_NULL);
  if (pool != NULL) {
    MemoryUsage usage = pool->get_memory_usage();
    Handle h = MemoryService::create_MemoryUsage_obj(usage, CHECK_NULL);
    return JNIHandles::make_local(env, h());
  } else {
    return NULL;
  }
JVM_END

// Returns a java/lang/management/MemoryUsage object containing the memory usage
// of a given memory pool.
JVM_ENTRY(jobject, jmm_GetPeakMemoryPoolUsage(JNIEnv* env, jobject obj))
  ResourceMark rm(THREAD);

  MemoryPool* pool = get_memory_pool_from_jobject(obj, CHECK_NULL);
  if (pool != NULL) {
    MemoryUsage usage = pool->get_peak_memory_usage();
    Handle h = MemoryService::create_MemoryUsage_obj(usage, CHECK_NULL);
    return JNIHandles::make_local(env, h());
  } else {
    return NULL;
  }
JVM_END

// Returns a java/lang/management/MemoryUsage object containing the memory usage
// of a given memory pool after most recent GC.
JVM_ENTRY(jobject, jmm_GetPoolCollectionUsage(JNIEnv* env, jobject obj))
  ResourceMark rm(THREAD);

  MemoryPool* pool = get_memory_pool_from_jobject(obj, CHECK_NULL);
  if (pool != NULL && pool->is_collected_pool()) {
    MemoryUsage usage = pool->get_last_collection_usage();
    Handle h = MemoryService::create_MemoryUsage_obj(usage, CHECK_NULL);
    return JNIHandles::make_local(env, h());
  } else {
    return NULL;
  }
JVM_END

// Sets the memory pool sensor for a threshold type
JVM_ENTRY(void, jmm_SetPoolSensor(JNIEnv* env, jobject obj, jmmThresholdType type, jobject sensorObj))
  if (obj == NULL || sensorObj == NULL) {
    THROW(vmSymbols::java_lang_NullPointerException());
  }

715
  Klass* sensor_klass = Management::sun_management_Sensor_klass(CHECK);
D
duke 已提交
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759
  oop s = JNIHandles::resolve(sensorObj);
  assert(s->is_instance(), "Sensor should be an instanceOop");
  instanceHandle sensor_h(THREAD, (instanceOop) s);
  if (!sensor_h->is_a(sensor_klass)) {
    THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
              "Sensor is not an instance of sun.management.Sensor class");
  }

  MemoryPool* mpool = get_memory_pool_from_jobject(obj, CHECK);
  assert(mpool != NULL, "MemoryPool should exist");

  switch (type) {
    case JMM_USAGE_THRESHOLD_HIGH:
    case JMM_USAGE_THRESHOLD_LOW:
      // have only one sensor for threshold high and low
      mpool->set_usage_sensor_obj(sensor_h);
      break;
    case JMM_COLLECTION_USAGE_THRESHOLD_HIGH:
    case JMM_COLLECTION_USAGE_THRESHOLD_LOW:
      // have only one sensor for threshold high and low
      mpool->set_gc_usage_sensor_obj(sensor_h);
      break;
    default:
      assert(false, "Unrecognized type");
  }

JVM_END


// Sets the threshold of a given memory pool.
// Returns the previous threshold.
//
// Input parameters:
//   pool      - the MemoryPoolMXBean object
//   type      - threshold type
//   threshold - the new threshold (must not be negative)
//
JVM_ENTRY(jlong, jmm_SetPoolThreshold(JNIEnv* env, jobject obj, jmmThresholdType type, jlong threshold))
  if (threshold < 0) {
    THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
               "Invalid threshold value",
               -1);
  }

760 761 762 763
  if ((size_t)threshold > max_uintx) {
    stringStream st;
    st.print("Invalid valid threshold value. Threshold value (" UINT64_FORMAT ") > max value of size_t (" SIZE_FORMAT ")", (size_t)threshold, max_uintx);
    THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(), st.as_string(), -1);
D
duke 已提交
764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848
  }

  MemoryPool* pool = get_memory_pool_from_jobject(obj, CHECK_(0L));
  assert(pool != NULL, "MemoryPool should exist");

  jlong prev = 0;
  switch (type) {
    case JMM_USAGE_THRESHOLD_HIGH:
      if (!pool->usage_threshold()->is_high_threshold_supported()) {
        return -1;
      }
      prev = pool->usage_threshold()->set_high_threshold((size_t) threshold);
      break;

    case JMM_USAGE_THRESHOLD_LOW:
      if (!pool->usage_threshold()->is_low_threshold_supported()) {
        return -1;
      }
      prev = pool->usage_threshold()->set_low_threshold((size_t) threshold);
      break;

    case JMM_COLLECTION_USAGE_THRESHOLD_HIGH:
      if (!pool->gc_usage_threshold()->is_high_threshold_supported()) {
        return -1;
      }
      // return and the new threshold is effective for the next GC
      return pool->gc_usage_threshold()->set_high_threshold((size_t) threshold);

    case JMM_COLLECTION_USAGE_THRESHOLD_LOW:
      if (!pool->gc_usage_threshold()->is_low_threshold_supported()) {
        return -1;
      }
      // return and the new threshold is effective for the next GC
      return pool->gc_usage_threshold()->set_low_threshold((size_t) threshold);

    default:
      assert(false, "Unrecognized type");
      return -1;
  }

  // When the threshold is changed, reevaluate if the low memory
  // detection is enabled.
  if (prev != threshold) {
    LowMemoryDetector::recompute_enabled_for_collected_pools();
    LowMemoryDetector::detect_low_memory(pool);
  }
  return prev;
JVM_END

// Returns a java/lang/management/MemoryUsage object representing
// the memory usage for the heap or non-heap memory.
JVM_ENTRY(jobject, jmm_GetMemoryUsage(JNIEnv* env, jboolean heap))
  ResourceMark rm(THREAD);

  // Calculate the memory usage
  size_t total_init = 0;
  size_t total_used = 0;
  size_t total_committed = 0;
  size_t total_max = 0;
  bool   has_undefined_init_size = false;
  bool   has_undefined_max_size = false;

  for (int i = 0; i < MemoryService::num_memory_pools(); i++) {
    MemoryPool* pool = MemoryService::get_memory_pool(i);
    if ((heap && pool->is_heap()) || (!heap && pool->is_non_heap())) {
      MemoryUsage u = pool->get_memory_usage();
      total_used += u.used();
      total_committed += u.committed();

      if (u.init_size() == (size_t)-1) {
        has_undefined_init_size = true;
      }
      if (!has_undefined_init_size) {
        total_init += u.init_size();
      }

      if (u.max_size() == (size_t)-1) {
        has_undefined_max_size = true;
      }
      if (!has_undefined_max_size) {
        total_max += u.max_size();
      }
    }
  }

849 850 851 852 853 854 855 856 857
  // if any one of the memory pool has undefined init_size or max_size,
  // set it to -1
  if (has_undefined_init_size) {
    total_init = (size_t)-1;
  }
  if (has_undefined_max_size) {
    total_max = (size_t)-1;
  }

P
phh 已提交
858
  MemoryUsage usage((heap ? InitialHeapSize : total_init),
D
duke 已提交
859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877
                    total_used,
                    total_committed,
                    (heap ? Universe::heap()->max_capacity() : total_max));

  Handle obj = MemoryService::create_MemoryUsage_obj(usage, CHECK_NULL);
  return JNIHandles::make_local(env, obj());
JVM_END

// Returns the boolean value of a given attribute.
JVM_LEAF(jboolean, jmm_GetBoolAttribute(JNIEnv *env, jmmBoolAttribute att))
  switch (att) {
  case JMM_VERBOSE_GC:
    return MemoryService::get_verbose();
  case JMM_VERBOSE_CLASS:
    return ClassLoadingService::get_verbose();
  case JMM_THREAD_CONTENTION_MONITORING:
    return ThreadService::is_thread_monitoring_contention();
  case JMM_THREAD_CPU_TIME:
    return ThreadService::is_thread_cpu_time_enabled();
878 879
  case JMM_THREAD_ALLOCATED_MEMORY:
    return ThreadService::is_thread_allocated_memory_enabled();
D
duke 已提交
880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896
  default:
    assert(0, "Unrecognized attribute");
    return false;
  }
JVM_END

// Sets the given boolean attribute and returns the previous value.
JVM_ENTRY(jboolean, jmm_SetBoolAttribute(JNIEnv *env, jmmBoolAttribute att, jboolean flag))
  switch (att) {
  case JMM_VERBOSE_GC:
    return MemoryService::set_verbose(flag != 0);
  case JMM_VERBOSE_CLASS:
    return ClassLoadingService::set_verbose(flag != 0);
  case JMM_THREAD_CONTENTION_MONITORING:
    return ThreadService::set_thread_monitoring_contention(flag != 0);
  case JMM_THREAD_CPU_TIME:
    return ThreadService::set_thread_cpu_time_enabled(flag != 0);
897 898
  case JMM_THREAD_ALLOCATED_MEMORY:
    return ThreadService::set_thread_allocated_memory_enabled(flag != 0);
D
duke 已提交
899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957
  default:
    assert(0, "Unrecognized attribute");
    return false;
  }
JVM_END


static jlong get_gc_attribute(GCMemoryManager* mgr, jmmLongAttribute att) {
  switch (att) {
  case JMM_GC_TIME_MS:
    return mgr->gc_time_ms();

  case JMM_GC_COUNT:
    return mgr->gc_count();

  case JMM_GC_EXT_ATTRIBUTE_INFO_SIZE:
    // current implementation only has 1 ext attribute
    return 1;

  default:
    assert(0, "Unrecognized GC attribute");
    return -1;
  }
}

class VmThreadCountClosure: public ThreadClosure {
 private:
  int _count;
 public:
  VmThreadCountClosure() : _count(0) {};
  void do_thread(Thread* thread);
  int count() { return _count; }
};

void VmThreadCountClosure::do_thread(Thread* thread) {
  // exclude externally visible JavaThreads
  if (thread->is_Java_thread() && !thread->is_hidden_from_external_view()) {
    return;
  }

  _count++;
}

static jint get_vm_thread_count() {
  VmThreadCountClosure vmtcc;
  {
    MutexLockerEx ml(Threads_lock);
    Threads::threads_do(&vmtcc);
  }

  return vmtcc.count();
}

static jint get_num_flags() {
  // last flag entry is always NULL, so subtract 1
  int nFlags = (int) Flag::numFlags - 1;
  int count = 0;
  for (int i = 0; i < nFlags; i++) {
    Flag* flag = &Flag::flags[i];
958
    // Exclude the locked (diagnostic, experimental) flags
D
duke 已提交
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988
    if (flag->is_unlocked() || flag->is_unlocker()) {
      count++;
    }
  }
  return count;
}

static jlong get_long_attribute(jmmLongAttribute att) {
  switch (att) {
  case JMM_CLASS_LOADED_COUNT:
    return ClassLoadingService::loaded_class_count();

  case JMM_CLASS_UNLOADED_COUNT:
    return ClassLoadingService::unloaded_class_count();

  case JMM_THREAD_TOTAL_COUNT:
    return ThreadService::get_total_thread_count();

  case JMM_THREAD_LIVE_COUNT:
    return ThreadService::get_live_thread_count();

  case JMM_THREAD_PEAK_COUNT:
    return ThreadService::get_peak_thread_count();

  case JMM_THREAD_DAEMON_COUNT:
    return ThreadService::get_daemon_thread_count();

  case JMM_JVM_INIT_DONE_TIME_MS:
    return Management::vm_init_done_time();

989 990 991
  case JMM_JVM_UPTIME_MS:
    return Management::ticks_to_ms(os::elapsed_counter());

D
duke 已提交
992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
  case JMM_COMPILE_TOTAL_TIME_MS:
    return Management::ticks_to_ms(CompileBroker::total_compilation_ticks());

  case JMM_OS_PROCESS_ID:
    return os::current_process_id();

  // Hotspot-specific counters
  case JMM_CLASS_LOADED_BYTES:
    return ClassLoadingService::loaded_class_bytes();

  case JMM_CLASS_UNLOADED_BYTES:
    return ClassLoadingService::unloaded_class_bytes();

  case JMM_SHARED_CLASS_LOADED_COUNT:
    return ClassLoadingService::loaded_shared_class_count();

  case JMM_SHARED_CLASS_UNLOADED_COUNT:
    return ClassLoadingService::unloaded_shared_class_count();


  case JMM_SHARED_CLASS_LOADED_BYTES:
    return ClassLoadingService::loaded_shared_class_bytes();

  case JMM_SHARED_CLASS_UNLOADED_BYTES:
    return ClassLoadingService::unloaded_shared_class_bytes();

  case JMM_TOTAL_CLASSLOAD_TIME_MS:
    return ClassLoader::classloader_time_ms();

  case JMM_VM_GLOBAL_COUNT:
    return get_num_flags();

  case JMM_SAFEPOINT_COUNT:
    return RuntimeService::safepoint_count();

  case JMM_TOTAL_SAFEPOINTSYNC_TIME_MS:
    return RuntimeService::safepoint_sync_time_ms();

  case JMM_TOTAL_STOPPED_TIME_MS:
    return RuntimeService::safepoint_time_ms();

  case JMM_TOTAL_APP_TIME_MS:
    return RuntimeService::application_time_ms();

  case JMM_VM_THREAD_COUNT:
    return get_vm_thread_count();

  case JMM_CLASS_INIT_TOTAL_COUNT:
    return ClassLoader::class_init_count();

  case JMM_CLASS_INIT_TOTAL_TIME_MS:
    return ClassLoader::class_init_time_ms();

  case JMM_CLASS_VERIFY_TOTAL_TIME_MS:
    return ClassLoader::class_verify_time_ms();

  case JMM_METHOD_DATA_SIZE_BYTES:
    return ClassLoadingService::class_method_data_size();

  case JMM_OS_MEM_TOTAL_PHYSICAL_BYTES:
    return os::physical_memory();

  default:
    return -1;
  }
}


// Returns the long value of a given attribute.
JVM_ENTRY(jlong, jmm_GetLongAttribute(JNIEnv *env, jobject obj, jmmLongAttribute att))
  if (obj == NULL) {
    return get_long_attribute(att);
  } else {
    GCMemoryManager* mgr = get_gc_memory_manager_from_jobject(obj, CHECK_(0L));
    if (mgr != NULL) {
      return get_gc_attribute(mgr, att);
    }
  }
  return -1;
JVM_END

// Gets the value of all attributes specified in the given array
// and sets the value in the result array.
// Returns the number of attributes found.
JVM_ENTRY(jint, jmm_GetLongAttributes(JNIEnv *env,
                                      jobject obj,
                                      jmmLongAttribute* atts,
                                      jint count,
                                      jlong* result))

  int num_atts = 0;
  if (obj == NULL) {
    for (int i = 0; i < count; i++) {
      result[i] = get_long_attribute(atts[i]);
      if (result[i] != -1) {
        num_atts++;
      }
    }
  } else {
    GCMemoryManager* mgr = get_gc_memory_manager_from_jobject(obj, CHECK_0);
    for (int i = 0; i < count; i++) {
      result[i] = get_gc_attribute(mgr, atts[i]);
      if (result[i] != -1) {
        num_atts++;
      }
    }
  }
  return num_atts;
JVM_END

// Helper function to do thread dump for a specific list of threads
static void do_thread_dump(ThreadDumpResult* dump_result,
                           typeArrayHandle ids_ah,  // array of thread ID (long[])
                           int num_threads,
                           int max_depth,
                           bool with_locked_monitors,
                           bool with_locked_synchronizers,
                           TRAPS) {

  // First get an array of threadObj handles.
  // A JavaThread may terminate before we get the stack trace.
  GrowableArray<instanceHandle>* thread_handle_array = new GrowableArray<instanceHandle>(num_threads);
  {
    MutexLockerEx ml(Threads_lock);
    for (int i = 0; i < num_threads; i++) {
      jlong tid = ids_ah->long_at(i);
S
sla 已提交
1118
      JavaThread* jt = Threads::find_java_thread_from_java_tid(tid);
D
duke 已提交
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
      oop thread_obj = (jt != NULL ? jt->threadObj() : (oop)NULL);
      instanceHandle threadObj_h(THREAD, (instanceOop) thread_obj);
      thread_handle_array->append(threadObj_h);
    }
  }

  // Obtain thread dumps and thread snapshot information
  VM_ThreadDump op(dump_result,
                   thread_handle_array,
                   num_threads,
                   max_depth, /* stack depth */
                   with_locked_monitors,
                   with_locked_synchronizers);
  VMThread::execute(&op);
}

// Gets an array of ThreadInfo objects. Each element is the ThreadInfo
// for the thread ID specified in the corresponding entry in
// the given array of thread IDs; or NULL if the thread does not exist
// or has terminated.
//
// Input parameters:
//   ids       - array of thread IDs
//   maxDepth  - the maximum depth of stack traces to be dumped:
//               maxDepth == -1 requests to dump entire stack trace.
//               maxDepth == 0  requests no stack trace.
//   infoArray - array of ThreadInfo objects
//
1147
// QQQ - Why does this method return a value instead of void?
D
duke 已提交
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
JVM_ENTRY(jint, jmm_GetThreadInfo(JNIEnv *env, jlongArray ids, jint maxDepth, jobjectArray infoArray))
  // Check if threads is null
  if (ids == NULL || infoArray == NULL) {
    THROW_(vmSymbols::java_lang_NullPointerException(), -1);
  }

  if (maxDepth < -1) {
    THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
               "Invalid maxDepth", -1);
  }

  ResourceMark rm(THREAD);
  typeArrayOop ta = typeArrayOop(JNIHandles::resolve_non_null(ids));
  typeArrayHandle ids_ah(THREAD, ta);

  oop infoArray_obj = JNIHandles::resolve_non_null(infoArray);
  objArrayOop oa = objArrayOop(infoArray_obj);
  objArrayHandle infoArray_h(THREAD, oa);

  // validate the thread id array
  validate_thread_id_array(ids_ah, CHECK_0);

  // validate the ThreadInfo[] parameters
  validate_thread_info_array(infoArray_h, CHECK_0);

  // infoArray must be of the same length as the given array of thread IDs
  int num_threads = ids_ah->length();
  if (num_threads != infoArray_h->length()) {
    THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
               "The length of the given ThreadInfo array does not match the length of the given array of thread IDs", -1);
  }

  if (JDK_Version::is_gte_jdk16x_version()) {
    // make sure the AbstractOwnableSynchronizer klass is loaded before taking thread snapshots
    java_util_concurrent_locks_AbstractOwnableSynchronizer::initialize(CHECK_0);
  }

  // Must use ThreadDumpResult to store the ThreadSnapshot.
  // GC may occur after the thread snapshots are taken but before
  // this function returns. The threadObj and other oops kept
  // in the ThreadSnapshot are marked and adjusted during GC.
  ThreadDumpResult dump_result(num_threads);

  if (maxDepth == 0) {
    // no stack trace dumped - do not need to stop the world
    {
      MutexLockerEx ml(Threads_lock);
      for (int i = 0; i < num_threads; i++) {
        jlong tid = ids_ah->long_at(i);
S
sla 已提交
1197
        JavaThread* jt = Threads::find_java_thread_from_java_tid(tid);
D
duke 已提交
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289
        ThreadSnapshot* ts;
        if (jt == NULL) {
          // if the thread does not exist or now it is terminated,
          // create dummy snapshot
          ts = new ThreadSnapshot();
        } else {
          ts = new ThreadSnapshot(jt);
        }
        dump_result.add_thread_snapshot(ts);
      }
    }
  } else {
    // obtain thread dump with the specific list of threads with stack trace
    do_thread_dump(&dump_result,
                   ids_ah,
                   num_threads,
                   maxDepth,
                   false, /* no locked monitor */
                   false, /* no locked synchronizers */
                   CHECK_0);
  }

  int num_snapshots = dump_result.num_snapshots();
  assert(num_snapshots == num_threads, "Must match the number of thread snapshots");
  int index = 0;
  for (ThreadSnapshot* ts = dump_result.snapshots(); ts != NULL; index++, ts = ts->next()) {
    // For each thread, create an java/lang/management/ThreadInfo object
    // and fill with the thread information

    if (ts->threadObj() == NULL) {
     // if the thread does not exist or now it is terminated, set threadinfo to NULL
      infoArray_h->obj_at_put(index, NULL);
      continue;
    }

    // Create java.lang.management.ThreadInfo object
    instanceOop info_obj = Management::create_thread_info_instance(ts, CHECK_0);
    infoArray_h->obj_at_put(index, info_obj);
  }
  return 0;
JVM_END

// Dump thread info for the specified threads.
// It returns an array of ThreadInfo objects. Each element is the ThreadInfo
// for the thread ID specified in the corresponding entry in
// the given array of thread IDs; or NULL if the thread does not exist
// or has terminated.
//
// Input parameter:
//    ids - array of thread IDs; NULL indicates all live threads
//    locked_monitors - if true, dump locked object monitors
//    locked_synchronizers - if true, dump locked JSR-166 synchronizers
//
JVM_ENTRY(jobjectArray, jmm_DumpThreads(JNIEnv *env, jlongArray thread_ids, jboolean locked_monitors, jboolean locked_synchronizers))
  ResourceMark rm(THREAD);

  if (JDK_Version::is_gte_jdk16x_version()) {
    // make sure the AbstractOwnableSynchronizer klass is loaded before taking thread snapshots
    java_util_concurrent_locks_AbstractOwnableSynchronizer::initialize(CHECK_NULL);
  }

  typeArrayOop ta = typeArrayOop(JNIHandles::resolve(thread_ids));
  int num_threads = (ta != NULL ? ta->length() : 0);
  typeArrayHandle ids_ah(THREAD, ta);

  ThreadDumpResult dump_result(num_threads);  // can safepoint

  if (ids_ah() != NULL) {

    // validate the thread id array
    validate_thread_id_array(ids_ah, CHECK_NULL);

    // obtain thread dump of a specific list of threads
    do_thread_dump(&dump_result,
                   ids_ah,
                   num_threads,
                   -1, /* entire stack */
                   (locked_monitors ? true : false),      /* with locked monitors */
                   (locked_synchronizers ? true : false), /* with locked synchronizers */
                   CHECK_NULL);
  } else {
    // obtain thread dump of all threads
    VM_ThreadDump op(&dump_result,
                     -1, /* entire stack */
                     (locked_monitors ? true : false),     /* with locked monitors */
                     (locked_synchronizers ? true : false) /* with locked synchronizers */);
    VMThread::execute(&op);
  }

  int num_snapshots = dump_result.num_snapshots();

  // create the result ThreadInfo[] object
1290
  Klass* k = Management::java_lang_management_ThreadInfo_klass(CHECK_NULL);
D
duke 已提交
1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323
  instanceKlassHandle ik (THREAD, k);
  objArrayOop r = oopFactory::new_objArray(ik(), num_snapshots, CHECK_NULL);
  objArrayHandle result_h(THREAD, r);

  int index = 0;
  for (ThreadSnapshot* ts = dump_result.snapshots(); ts != NULL; ts = ts->next(), index++) {
    if (ts->threadObj() == NULL) {
     // if the thread does not exist or now it is terminated, set threadinfo to NULL
      result_h->obj_at_put(index, NULL);
      continue;
    }

    ThreadStackTrace* stacktrace = ts->get_stack_trace();
    assert(stacktrace != NULL, "Must have a stack trace dumped");

    // Create Object[] filled with locked monitors
    // Create int[] filled with the stack depth where a monitor was locked
    int num_frames = stacktrace->get_stack_depth();
    int num_locked_monitors = stacktrace->num_jni_locked_monitors();

    // Count the total number of locked monitors
    for (int i = 0; i < num_frames; i++) {
      StackFrameInfo* frame = stacktrace->stack_frame_at(i);
      num_locked_monitors += frame->num_locked_monitors();
    }

    objArrayHandle monitors_array;
    typeArrayHandle depths_array;
    objArrayHandle synchronizers_array;

    if (locked_monitors) {
      // Constructs Object[] and int[] to contain the object monitor and the stack depth
      // where the thread locked it
1324
      objArrayOop array = oopFactory::new_objArray(SystemDictionary::Object_klass(), num_locked_monitors, CHECK_NULL);
D
duke 已提交
1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
      objArrayHandle mh(THREAD, array);
      monitors_array = mh;

      typeArrayOop tarray = oopFactory::new_typeArray(T_INT, num_locked_monitors, CHECK_NULL);
      typeArrayHandle dh(THREAD, tarray);
      depths_array = dh;

      int count = 0;
      int j = 0;
      for (int depth = 0; depth < num_frames; depth++) {
        StackFrameInfo* frame = stacktrace->stack_frame_at(depth);
        int len = frame->num_locked_monitors();
        GrowableArray<oop>* locked_monitors = frame->locked_monitors();
        for (j = 0; j < len; j++) {
          oop monitor = locked_monitors->at(j);
          assert(monitor != NULL && monitor->is_instance(), "must be a Java object");
          monitors_array->obj_at_put(count, monitor);
          depths_array->int_at_put(count, depth);
          count++;
        }
      }

      GrowableArray<oop>* jni_locked_monitors = stacktrace->jni_locked_monitors();
      for (j = 0; j < jni_locked_monitors->length(); j++) {
        oop object = jni_locked_monitors->at(j);
        assert(object != NULL && object->is_instance(), "must be a Java object");
        monitors_array->obj_at_put(count, object);
        // Monitor locked via JNI MonitorEnter call doesn't have stack depth info
        depths_array->int_at_put(count, -1);
        count++;
      }
      assert(count == num_locked_monitors, "number of locked monitors doesn't match");
    }

    if (locked_synchronizers) {
      // Create Object[] filled with locked JSR-166 synchronizers
      assert(ts->threadObj() != NULL, "Must be a valid JavaThread");
      ThreadConcurrentLocks* tcl = ts->get_concurrent_locks();
      GrowableArray<instanceOop>* locks = (tcl != NULL ? tcl->owned_locks() : NULL);
      int num_locked_synchronizers = (locks != NULL ? locks->length() : 0);

1366
      objArrayOop array = oopFactory::new_objArray(SystemDictionary::Object_klass(), num_locked_synchronizers, CHECK_NULL);
D
duke 已提交
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393
      objArrayHandle sh(THREAD, array);
      synchronizers_array = sh;

      for (int k = 0; k < num_locked_synchronizers; k++) {
        synchronizers_array->obj_at_put(k, locks->at(k));
      }
    }

    // Create java.lang.management.ThreadInfo object
    instanceOop info_obj = Management::create_thread_info_instance(ts,
                                                                   monitors_array,
                                                                   depths_array,
                                                                   synchronizers_array,
                                                                   CHECK_NULL);
    result_h->obj_at_put(index, info_obj);
  }

  return (jobjectArray) JNIHandles::make_local(env, result_h());
JVM_END

// Returns an array of Class objects.
JVM_ENTRY(jobjectArray, jmm_GetLoadedClasses(JNIEnv *env))
  ResourceMark rm(THREAD);

  LoadedClassesEnumerator lce(THREAD);  // Pass current Thread as parameter

  int num_classes = lce.num_loaded_classes();
1394
  objArrayOop r = oopFactory::new_objArray(SystemDictionary::Class_klass(), num_classes, CHECK_0);
D
duke 已提交
1395 1396 1397 1398
  objArrayHandle classes_ah(THREAD, r);

  for (int i = 0; i < num_classes; i++) {
    KlassHandle kh = lce.get_klass(i);
H
hseigel 已提交
1399
    oop mirror = kh()->java_mirror();
D
duke 已提交
1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442
    classes_ah->obj_at_put(i, mirror);
  }

  return (jobjectArray) JNIHandles::make_local(env, classes_ah());
JVM_END

// Reset statistic.  Return true if the requested statistic is reset.
// Otherwise, return false.
//
// Input parameters:
//  obj  - specify which instance the statistic associated with to be reset
//         For PEAK_POOL_USAGE stat, obj is required to be a memory pool object.
//         For THREAD_CONTENTION_COUNT and TIME stat, obj is required to be a thread ID.
//  type - the type of statistic to be reset
//
JVM_ENTRY(jboolean, jmm_ResetStatistic(JNIEnv *env, jvalue obj, jmmStatisticType type))
  ResourceMark rm(THREAD);

  switch (type) {
    case JMM_STAT_PEAK_THREAD_COUNT:
      ThreadService::reset_peak_thread_count();
      return true;

    case JMM_STAT_THREAD_CONTENTION_COUNT:
    case JMM_STAT_THREAD_CONTENTION_TIME: {
      jlong tid = obj.j;
      if (tid < 0) {
        THROW_(vmSymbols::java_lang_IllegalArgumentException(), JNI_FALSE);
      }

      // Look for the JavaThread of this given tid
      MutexLockerEx ml(Threads_lock);
      if (tid == 0) {
        // reset contention statistics for all threads if tid == 0
        for (JavaThread* java_thread = Threads::first(); java_thread != NULL; java_thread = java_thread->next()) {
          if (type == JMM_STAT_THREAD_CONTENTION_COUNT) {
            ThreadService::reset_contention_count_stat(java_thread);
          } else {
            ThreadService::reset_contention_time_stat(java_thread);
          }
        }
      } else {
        // reset contention statistics for a given thread
S
sla 已提交
1443
        JavaThread* java_thread = Threads::find_java_thread_from_java_tid(tid);
D
duke 已提交
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511
        if (java_thread == NULL) {
          return false;
        }

        if (type == JMM_STAT_THREAD_CONTENTION_COUNT) {
          ThreadService::reset_contention_count_stat(java_thread);
        } else {
          ThreadService::reset_contention_time_stat(java_thread);
        }
      }
      return true;
      break;
    }
    case JMM_STAT_PEAK_POOL_USAGE: {
      jobject o = obj.l;
      if (o == NULL) {
        THROW_(vmSymbols::java_lang_NullPointerException(), JNI_FALSE);
      }

      oop pool_obj = JNIHandles::resolve(o);
      assert(pool_obj->is_instance(), "Should be an instanceOop");
      instanceHandle ph(THREAD, (instanceOop) pool_obj);

      MemoryPool* pool = MemoryService::get_memory_pool(ph);
      if (pool != NULL) {
        pool->reset_peak_memory_usage();
        return true;
      }
      break;
    }
    case JMM_STAT_GC_STAT: {
      jobject o = obj.l;
      if (o == NULL) {
        THROW_(vmSymbols::java_lang_NullPointerException(), JNI_FALSE);
      }

      GCMemoryManager* mgr = get_gc_memory_manager_from_jobject(o, CHECK_0);
      if (mgr != NULL) {
        mgr->reset_gc_stat();
        return true;
      }
      break;
    }
    default:
      assert(0, "Unknown Statistic Type");
  }
  return false;
JVM_END

// Returns the fast estimate of CPU time consumed by
// a given thread (in nanoseconds).
// If thread_id == 0, return CPU time for the current thread.
JVM_ENTRY(jlong, jmm_GetThreadCpuTime(JNIEnv *env, jlong thread_id))
  if (!os::is_thread_cpu_time_supported()) {
    return -1;
  }

  if (thread_id < 0) {
    THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
               "Invalid thread ID", -1);
  }

  JavaThread* java_thread = NULL;
  if (thread_id == 0) {
    // current thread
    return os::current_thread_cpu_time();
  } else {
    MutexLockerEx ml(Threads_lock);
S
sla 已提交
1512
    java_thread = Threads::find_java_thread_from_java_tid(thread_id);
D
duke 已提交
1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524
    if (java_thread != NULL) {
      return os::thread_cpu_time((Thread*) java_thread);
    }
  }
  return -1;
JVM_END

// Returns a String array of all VM global flag names
JVM_ENTRY(jobjectArray, jmm_GetVMGlobalNames(JNIEnv *env))
  // last flag entry is always NULL, so subtract 1
  int nFlags = (int) Flag::numFlags - 1;
  // allocate a temp array
1525
  objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),
D
duke 已提交
1526 1527 1528 1529 1530
                                           nFlags, CHECK_0);
  objArrayHandle flags_ah(THREAD, r);
  int num_entries = 0;
  for (int i = 0; i < nFlags; i++) {
    Flag* flag = &Flag::flags[i];
1531 1532 1533 1534
    // Exclude notproduct and develop flags in product builds.
    if (flag->is_constant_in_binary()) {
      continue;
    }
1535
    // Exclude the locked (experimental, diagnostic) flags
D
duke 已提交
1536
    if (flag->is_unlocked() || flag->is_unlocker()) {
1537
      Handle s = java_lang_String::create_from_str(flag->_name, CHECK_0);
D
duke 已提交
1538 1539 1540 1541 1542 1543 1544
      flags_ah->obj_at_put(num_entries, s());
      num_entries++;
    }
  }

  if (num_entries < nFlags) {
    // Return array of right length
1545
    objArrayOop res = oopFactory::new_objArray(SystemDictionary::String_klass(), num_entries, CHECK_0);
D
duke 已提交
1546 1547 1548 1549 1550 1551 1552 1553 1554
    for(int i = 0; i < num_entries; i++) {
      res->obj_at_put(i, flags_ah->obj_at(i));
    }
    return (jobjectArray)JNIHandles::make_local(env, res);
  }

  return (jobjectArray)JNIHandles::make_local(env, flags_ah());
JVM_END

1555 1556 1557 1558
// Utility function used by jmm_GetVMGlobals.  Returns false if flag type
// can't be determined, true otherwise.  If false is returned, then *global
// will be incomplete and invalid.
bool add_global_entry(JNIEnv* env, Handle name, jmmVMGlobal *global, Flag *flag, TRAPS) {
D
duke 已提交
1559 1560
  Handle flag_name;
  if (name() == NULL) {
1561
    flag_name = java_lang_String::create_from_str(flag->_name, CHECK_false);
D
duke 已提交
1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575
  } else {
    flag_name = name;
  }
  global->name = (jstring)JNIHandles::make_local(env, flag_name());

  if (flag->is_bool()) {
    global->value.z = flag->get_bool() ? JNI_TRUE : JNI_FALSE;
    global->type = JMM_VMGLOBAL_TYPE_JBOOLEAN;
  } else if (flag->is_intx()) {
    global->value.j = (jlong)flag->get_intx();
    global->type = JMM_VMGLOBAL_TYPE_JLONG;
  } else if (flag->is_uintx()) {
    global->value.j = (jlong)flag->get_uintx();
    global->type = JMM_VMGLOBAL_TYPE_JLONG;
1576 1577 1578
  } else if (flag->is_uint64_t()) {
    global->value.j = (jlong)flag->get_uint64_t();
    global->type = JMM_VMGLOBAL_TYPE_JLONG;
D
duke 已提交
1579
  } else if (flag->is_ccstr()) {
1580
    Handle str = java_lang_String::create_from_str(flag->get_ccstr(), CHECK_false);
D
duke 已提交
1581 1582
    global->value.l = (jobject)JNIHandles::make_local(env, str());
    global->type = JMM_VMGLOBAL_TYPE_JSTRING;
1583 1584 1585
  } else {
    global->type = JMM_VMGLOBAL_TYPE_UNKNOWN;
    return false;
D
duke 已提交
1586 1587 1588 1589
  }

  global->writeable = flag->is_writeable();
  global->external = flag->is_external();
1590 1591
  switch (flag->get_origin()) {
    case Flag::DEFAULT:
D
duke 已提交
1592 1593
      global->origin = JMM_VMGLOBAL_ORIGIN_DEFAULT;
      break;
1594
    case Flag::COMMAND_LINE:
D
duke 已提交
1595 1596
      global->origin = JMM_VMGLOBAL_ORIGIN_COMMAND_LINE;
      break;
1597
    case Flag::ENVIRON_VAR:
D
duke 已提交
1598 1599
      global->origin = JMM_VMGLOBAL_ORIGIN_ENVIRON_VAR;
      break;
1600
    case Flag::CONFIG_FILE:
D
duke 已提交
1601 1602
      global->origin = JMM_VMGLOBAL_ORIGIN_CONFIG_FILE;
      break;
1603
    case Flag::MANAGEMENT:
D
duke 已提交
1604 1605
      global->origin = JMM_VMGLOBAL_ORIGIN_MANAGEMENT;
      break;
1606
    case Flag::ERGONOMIC:
D
duke 已提交
1607 1608 1609 1610 1611
      global->origin = JMM_VMGLOBAL_ORIGIN_ERGONOMIC;
      break;
    default:
      global->origin = JMM_VMGLOBAL_ORIGIN_OTHER;
  }
1612 1613

  return true;
D
duke 已提交
1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638
}

// Fill globals array of count length with jmmVMGlobal entries
// specified by names. If names == NULL, fill globals array
// with all Flags. Return value is number of entries
// created in globals.
// If a Flag with a given name in an array element does not
// exist, globals[i].name will be set to NULL.
JVM_ENTRY(jint, jmm_GetVMGlobals(JNIEnv *env,
                                 jobjectArray names,
                                 jmmVMGlobal *globals,
                                 jint count))


  if (globals == NULL) {
    THROW_(vmSymbols::java_lang_NullPointerException(), 0);
  }

  ResourceMark rm(THREAD);

  if (names != NULL) {
    // return the requested globals
    objArrayOop ta = objArrayOop(JNIHandles::resolve_non_null(names));
    objArrayHandle names_ah(THREAD, ta);
    // 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()) {
D
duke 已提交
1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655
      THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
                 "Array element type is not String class", 0);
    }

    int names_length = names_ah->length();
    int num_entries = 0;
    for (int i = 0; i < names_length && i < count; i++) {
      oop s = names_ah->obj_at(i);
      if (s == NULL) {
        THROW_(vmSymbols::java_lang_NullPointerException(), 0);
      }

      Handle sh(THREAD, s);
      char* str = java_lang_String::as_utf8_string(s);
      Flag* flag = Flag::find_flag(str, strlen(str));
1656 1657
      if (flag != NULL &&
          add_global_entry(env, sh, &globals[i], flag, THREAD)) {
D
duke 已提交
1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672
        num_entries++;
      } else {
        globals[i].name = NULL;
      }
    }
    return num_entries;
  } else {
    // return all globals if names == NULL

    // last flag entry is always NULL, so subtract 1
    int nFlags = (int) Flag::numFlags - 1;
    Handle null_h;
    int num_entries = 0;
    for (int i = 0; i < nFlags && num_entries < count;  i++) {
      Flag* flag = &Flag::flags[i];
1673 1674 1675 1676
      // Exclude notproduct and develop flags in product builds.
      if (flag->is_constant_in_binary()) {
        continue;
      }
1677
      // Exclude the locked (diagnostic, experimental) flags
1678 1679
      if ((flag->is_unlocked() || flag->is_unlocker()) &&
          add_global_entry(env, null_h, &globals[num_entries], flag, THREAD)) {
D
duke 已提交
1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705
        num_entries++;
      }
    }
    return num_entries;
  }
JVM_END

JVM_ENTRY(void, jmm_SetVMGlobal(JNIEnv *env, jstring flag_name, jvalue new_value))
  ResourceMark rm(THREAD);

  oop fn = JNIHandles::resolve_external_guard(flag_name);
  if (fn == NULL) {
    THROW_MSG(vmSymbols::java_lang_NullPointerException(),
              "The flag name cannot be null.");
  }
  char* name = java_lang_String::as_utf8_string(fn);
  Flag* flag = Flag::find_flag(name, strlen(name));
  if (flag == NULL) {
    THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
              "Flag does not exist.");
  }
  if (!flag->is_writeable()) {
    THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
              "This flag is not writeable.");
  }

1706
  bool succeed = false;
D
duke 已提交
1707 1708
  if (flag->is_bool()) {
    bool bvalue = (new_value.z == JNI_TRUE ? true : false);
1709
    succeed = CommandLineFlags::boolAtPut(name, &bvalue, Flag::MANAGEMENT);
D
duke 已提交
1710
  } else if (flag->is_intx()) {
1711
    intx ivalue = (intx)new_value.j;
1712
    succeed = CommandLineFlags::intxAtPut(name, &ivalue, Flag::MANAGEMENT);
D
duke 已提交
1713
  } else if (flag->is_uintx()) {
1714
    uintx uvalue = (uintx)new_value.j;
1715 1716

    if (strncmp(name, "MaxHeapFreeRatio", 17) == 0) {
1717
      FormatBuffer<80> err_msg("%s", "");
1718 1719 1720 1721
      if (!Arguments::verify_MaxHeapFreeRatio(err_msg, uvalue)) {
        THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), err_msg.buffer());
      }
    } else if (strncmp(name, "MinHeapFreeRatio", 17) == 0) {
1722
      FormatBuffer<80> err_msg("%s", "");
1723 1724 1725 1726
      if (!Arguments::verify_MinHeapFreeRatio(err_msg, uvalue)) {
        THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), err_msg.buffer());
      }
    }
1727
    succeed = CommandLineFlags::uintxAtPut(name, &uvalue, Flag::MANAGEMENT);
1728 1729
  } else if (flag->is_uint64_t()) {
    uint64_t uvalue = (uint64_t)new_value.j;
1730
    succeed = CommandLineFlags::uint64_tAtPut(name, &uvalue, Flag::MANAGEMENT);
D
duke 已提交
1731 1732 1733 1734 1735 1736
  } else if (flag->is_ccstr()) {
    oop str = JNIHandles::resolve_external_guard(new_value.l);
    if (str == NULL) {
      THROW(vmSymbols::java_lang_NullPointerException());
    }
    ccstr svalue = java_lang_String::as_utf8_string(str);
1737
    succeed = CommandLineFlags::ccstrAtPut(name, &svalue, Flag::MANAGEMENT);
1738 1739 1740
    if (succeed) {
      FREE_C_HEAP_ARRAY(char, svalue, mtInternal);
    }
D
duke 已提交
1741 1742 1743 1744 1745 1746
  }
  assert(succeed, "Setting flag should succeed");
JVM_END

class ThreadTimesClosure: public ThreadClosure {
 private:
1747 1748
  objArrayHandle _names_strings;
  char **_names_chars;
1749
  typeArrayHandle _times;
D
duke 已提交
1750 1751 1752 1753 1754
  int _names_len;
  int _times_len;
  int _count;

 public:
1755
  ThreadTimesClosure(objArrayHandle names, typeArrayHandle times);
1756
  ~ThreadTimesClosure();
D
duke 已提交
1757
  virtual void do_thread(Thread* thread);
1758
  void do_unlocked();
D
duke 已提交
1759 1760 1761
  int count() { return _count; }
};

1762
ThreadTimesClosure::ThreadTimesClosure(objArrayHandle names,
1763
                                       typeArrayHandle times) {
1764
  assert(names() != NULL, "names was NULL");
1765
  assert(times() != NULL, "times was NULL");
1766
  _names_strings = names;
D
duke 已提交
1767
  _names_len = names->length();
1768
  _names_chars = NEW_C_HEAP_ARRAY(char*, _names_len, mtInternal);
D
duke 已提交
1769 1770 1771 1772 1773
  _times = times;
  _times_len = times->length();
  _count = 0;
}

1774 1775 1776
//
// Called with Threads_lock held
//
D
duke 已提交
1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790
void ThreadTimesClosure::do_thread(Thread* thread) {
  assert(thread != NULL, "thread was NULL");

  // exclude externally visible JavaThreads
  if (thread->is_Java_thread() && !thread->is_hidden_from_external_view()) {
    return;
  }

  if (_count >= _names_len || _count >= _times_len) {
    // skip if the result array is not big enough
    return;
  }

  EXCEPTION_MARK;
1791
  ResourceMark rm(THREAD); // thread->name() uses ResourceArea
D
duke 已提交
1792 1793

  assert(thread->name() != NULL, "All threads should have a name");
1794
  _names_chars[_count] = strdup(thread->name());
D
duke 已提交
1795 1796 1797 1798 1799
  _times->long_at_put(_count, os::is_thread_cpu_time_supported() ?
                        os::thread_cpu_time(thread) : -1);
  _count++;
}

1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816
// Called without Threads_lock, we can allocate String objects.
void ThreadTimesClosure::do_unlocked() {

  EXCEPTION_MARK;
  for (int i = 0; i < _count; i++) {
    Handle s = java_lang_String::create_from_str(_names_chars[i],  CHECK);
    _names_strings->obj_at_put(i, s());
  }
}

ThreadTimesClosure::~ThreadTimesClosure() {
  for (int i = 0; i < _count; i++) {
    free(_names_chars[i]);
  }
  FREE_C_HEAP_ARRAY(char *, _names_chars, mtInternal);
}

D
duke 已提交
1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833
// Fills names with VM internal thread names and times with the corresponding
// CPU times.  If names or times is NULL, a NullPointerException is thrown.
// If the element type of names is not String, an IllegalArgumentException is
// thrown.
// If an array is not large enough to hold all the entries, only the entries
// that fit will be returned.  Return value is the number of VM internal
// threads entries.
JVM_ENTRY(jint, jmm_GetInternalThreadTimes(JNIEnv *env,
                                           jobjectArray names,
                                           jlongArray times))
  if (names == NULL || times == NULL) {
     THROW_(vmSymbols::java_lang_NullPointerException(), 0);
  }
  objArrayOop na = objArrayOop(JNIHandles::resolve_non_null(names));
  objArrayHandle names_ah(THREAD, na);

  // Make sure we have a String array
1834
  Klass* element_klass = ObjArrayKlass::cast(names_ah->klass())->element_klass();
1835
  if (element_klass != SystemDictionary::String_klass()) {
D
duke 已提交
1836 1837 1838 1839 1840 1841 1842
    THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
               "Array element type is not String class", 0);
  }

  typeArrayOop ta = typeArrayOop(JNIHandles::resolve_non_null(times));
  typeArrayHandle times_ah(THREAD, ta);

1843
  ThreadTimesClosure ttc(names_ah, times_ah);
D
duke 已提交
1844 1845 1846 1847
  {
    MutexLockerEx ml(Threads_lock);
    Threads::threads_do(&ttc);
  }
1848
  ttc.do_unlocked();
D
duke 已提交
1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869
  return ttc.count();
JVM_END

static Handle find_deadlocks(bool object_monitors_only, TRAPS) {
  ResourceMark rm(THREAD);

  VM_FindDeadlocks op(!object_monitors_only /* also check concurrent locks? */);
  VMThread::execute(&op);

  DeadlockCycle* deadlocks = op.result();
  if (deadlocks == NULL) {
    // no deadlock found and return
    return Handle();
  }

  int num_threads = 0;
  DeadlockCycle* cycle;
  for (cycle = deadlocks; cycle != NULL; cycle = cycle->next()) {
    num_threads += cycle->num_threads();
  }

1870
  objArrayOop r = oopFactory::new_objArray(SystemDictionary::Thread_klass(), num_threads, CHECK_NH);
D
duke 已提交
1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949
  objArrayHandle threads_ah(THREAD, r);

  int index = 0;
  for (cycle = deadlocks; cycle != NULL; cycle = cycle->next()) {
    GrowableArray<JavaThread*>* deadlock_threads = cycle->threads();
    int len = deadlock_threads->length();
    for (int i = 0; i < len; i++) {
      threads_ah->obj_at_put(index, deadlock_threads->at(i)->threadObj());
      index++;
    }
  }
  return threads_ah;
}

// Finds cycles of threads that are deadlocked involved in object monitors
// and JSR-166 synchronizers.
// Returns an array of Thread objects which are in deadlock, if any.
// Otherwise, returns NULL.
//
// Input parameter:
//    object_monitors_only - if true, only check object monitors
//
JVM_ENTRY(jobjectArray, jmm_FindDeadlockedThreads(JNIEnv *env, jboolean object_monitors_only))
  Handle result = find_deadlocks(object_monitors_only != 0, CHECK_0);
  return (jobjectArray) JNIHandles::make_local(env, result());
JVM_END

// Finds cycles of threads that are deadlocked on monitor locks
// Returns an array of Thread objects which are in deadlock, if any.
// Otherwise, returns NULL.
JVM_ENTRY(jobjectArray, jmm_FindMonitorDeadlockedThreads(JNIEnv *env))
  Handle result = find_deadlocks(true, CHECK_0);
  return (jobjectArray) JNIHandles::make_local(env, result());
JVM_END

// Gets the information about GC extension attributes including
// the name of the attribute, its type, and a short description.
//
// Input parameters:
//   mgr   - GC memory manager
//   info  - caller allocated array of jmmExtAttributeInfo
//   count - number of elements of the info array
//
// Returns the number of GC extension attributes filled in the info array; or
// -1 if info is not big enough
//
JVM_ENTRY(jint, jmm_GetGCExtAttributeInfo(JNIEnv *env, jobject mgr, jmmExtAttributeInfo* info, jint count))
  // All GC memory managers have 1 attribute (number of GC threads)
  if (count == 0) {
    return 0;
  }

  if (info == NULL) {
   THROW_(vmSymbols::java_lang_NullPointerException(), 0);
  }

  info[0].name = "GcThreadCount";
  info[0].type = 'I';
  info[0].description = "Number of GC threads";
  return 1;
JVM_END

// verify the given array is an array of java/lang/management/MemoryUsage objects
// of a given length and return the objArrayOop
static objArrayOop get_memory_usage_objArray(jobjectArray array, int length, TRAPS) {
  if (array == NULL) {
    THROW_(vmSymbols::java_lang_NullPointerException(), 0);
  }

  objArrayOop oa = objArrayOop(JNIHandles::resolve_non_null(array));
  objArrayHandle array_h(THREAD, oa);

  // array must be of the given length
  if (length != array_h->length()) {
    THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
               "The length of the given MemoryUsage array does not match the number of memory pools.", 0);
  }

  // check if the element of array is of type MemoryUsage class
1950
  Klass* usage_klass = Management::java_lang_management_MemoryUsage_klass(CHECK_0);
1951
  Klass* element_klass = ObjArrayKlass::cast(array_h->klass())->element_klass();
D
duke 已提交
1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992
  if (element_klass != usage_klass) {
    THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
               "The element type is not MemoryUsage class", 0);
  }

  return array_h();
}

// Gets the statistics of the last GC of a given GC memory manager.
// Input parameters:
//   obj     - GarbageCollectorMXBean object
//   gc_stat - caller allocated jmmGCStat where:
//     a. before_gc_usage - array of MemoryUsage objects
//     b. after_gc_usage  - array of MemoryUsage objects
//     c. gc_ext_attributes_values_size is set to the
//        gc_ext_attribute_values array allocated
//     d. gc_ext_attribute_values is a caller allocated array of jvalue.
//
// On return,
//   gc_index == 0 indicates no GC statistics available
//
//   before_gc_usage and after_gc_usage - filled with per memory pool
//      before and after GC usage in the same order as the memory pools
//      returned by GetMemoryPools for a given GC memory manager.
//   num_gc_ext_attributes indicates the number of elements in
//      the gc_ext_attribute_values array is filled; or
//      -1 if the gc_ext_attributes_values array is not big enough
//
JVM_ENTRY(void, jmm_GetLastGCStat(JNIEnv *env, jobject obj, jmmGCStat *gc_stat))
  ResourceMark rm(THREAD);

  if (gc_stat->gc_ext_attribute_values_size > 0 && gc_stat->gc_ext_attribute_values == NULL) {
    THROW(vmSymbols::java_lang_NullPointerException());
  }

  // Get the GCMemoryManager
  GCMemoryManager* mgr = get_gc_memory_manager_from_jobject(obj, CHECK);

  // Make a copy of the last GC statistics
  // GC may occur while constructing the last GC information
  int num_pools = MemoryService::num_memory_pools();
1993 1994
  GCStatInfo stat(num_pools);
  if (mgr->get_last_gc_stat(&stat) == 0) {
1995 1996 1997
    gc_stat->gc_index = 0;
    return;
  }
D
duke 已提交
1998

1999 2000 2001
  gc_stat->gc_index = stat.gc_index();
  gc_stat->start_time = Management::ticks_to_ms(stat.start_time());
  gc_stat->end_time = Management::ticks_to_ms(stat.end_time());
D
duke 已提交
2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018

  // Current implementation does not have GC extension attributes
  gc_stat->num_gc_ext_attributes = 0;

  // Fill the arrays of MemoryUsage objects with before and after GC
  // per pool memory usage
  objArrayOop bu = get_memory_usage_objArray(gc_stat->usage_before_gc,
                                             num_pools,
                                             CHECK);
  objArrayHandle usage_before_gc_ah(THREAD, bu);

  objArrayOop au = get_memory_usage_objArray(gc_stat->usage_after_gc,
                                             num_pools,
                                             CHECK);
  objArrayHandle usage_after_gc_ah(THREAD, au);

  for (int i = 0; i < num_pools; i++) {
2019
    Handle before_usage = MemoryService::create_MemoryUsage_obj(stat.before_gc_usage_for_pool(i), CHECK);
D
duke 已提交
2020 2021
    Handle after_usage;

2022
    MemoryUsage u = stat.after_gc_usage_for_pool(i);
D
duke 已提交
2023 2024 2025 2026 2027 2028
    if (u.max_size() == 0 && u.used() > 0) {
      // If max size == 0, this pool is a survivor space.
      // Set max size = -1 since the pools will be swapped after GC.
      MemoryUsage usage(u.init_size(), u.used(), u.committed(), (size_t)-1);
      after_usage = MemoryService::create_MemoryUsage_obj(usage, CHECK);
    } else {
2029
      after_usage = MemoryService::create_MemoryUsage_obj(stat.after_gc_usage_for_pool(i), CHECK);
D
duke 已提交
2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041
    }
    usage_before_gc_ah->obj_at_put(i, before_usage());
    usage_after_gc_ah->obj_at_put(i, after_usage());
  }

  if (gc_stat->gc_ext_attribute_values_size > 0) {
    // Current implementation only has 1 attribute (number of GC threads)
    // The type is 'I'
    gc_stat->gc_ext_attribute_values[0].i = mgr->num_gc_threads();
  }
JVM_END

2042 2043 2044 2045 2046 2047 2048
JVM_ENTRY(void, jmm_SetGCNotificationEnabled(JNIEnv *env, jobject obj, jboolean enabled))
  ResourceMark rm(THREAD);
  // Get the GCMemoryManager
  GCMemoryManager* mgr = get_gc_memory_manager_from_jobject(obj, CHECK);
  mgr->set_notification_enabled(enabled?true:false);
JVM_END

D
duke 已提交
2049 2050
// Dump heap - Returns 0 if succeeds.
JVM_ENTRY(jint, jmm_DumpHeap0(JNIEnv *env, jstring outputfile, jboolean live))
2051
#if INCLUDE_SERVICES
D
duke 已提交
2052 2053 2054 2055 2056 2057
  ResourceMark rm(THREAD);
  oop on = JNIHandles::resolve_external_guard(outputfile);
  if (on == NULL) {
    THROW_MSG_(vmSymbols::java_lang_NullPointerException(),
               "Output file name cannot be null.", -1);
  }
2058
  char* name = java_lang_String::as_platform_dependent_str(on, CHECK_(-1));
D
duke 已提交
2059 2060 2061 2062 2063 2064 2065 2066 2067 2068
  if (name == NULL) {
    THROW_MSG_(vmSymbols::java_lang_NullPointerException(),
               "Output file name cannot be null.", -1);
  }
  HeapDumper dumper(live ? true : false);
  if (dumper.dump(name) != 0) {
    const char* errmsg = dumper.error_as_C_string();
    THROW_MSG_(vmSymbols::java_io_IOException(), errmsg, -1);
  }
  return 0;
2069
#else  // INCLUDE_SERVICES
D
duke 已提交
2070
  return -1;
2071
#endif // INCLUDE_SERVICES
D
duke 已提交
2072 2073
JVM_END

2074 2075
JVM_ENTRY(jobjectArray, jmm_GetDiagnosticCommands(JNIEnv *env))
  ResourceMark rm(THREAD);
2076
  GrowableArray<const char *>* dcmd_list = DCmdFactory::DCmd_list(DCmd_Source_MBean);
2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098
  objArrayOop cmd_array_oop = oopFactory::new_objArray(SystemDictionary::String_klass(),
          dcmd_list->length(), CHECK_NULL);
  objArrayHandle cmd_array(THREAD, cmd_array_oop);
  for (int i = 0; i < dcmd_list->length(); i++) {
    oop cmd_name = java_lang_String::create_oop_from_str(dcmd_list->at(i), CHECK_NULL);
    cmd_array->obj_at_put(i, cmd_name);
  }
  return (jobjectArray) JNIHandles::make_local(env, cmd_array());
JVM_END

JVM_ENTRY(void, jmm_GetDiagnosticCommandInfo(JNIEnv *env, jobjectArray cmds,
          dcmdInfo* infoArray))
  if (cmds == NULL || infoArray == NULL) {
    THROW(vmSymbols::java_lang_NullPointerException());
  }

  ResourceMark rm(THREAD);

  objArrayOop ca = objArrayOop(JNIHandles::resolve_non_null(cmds));
  objArrayHandle cmds_ah(THREAD, ca);

  // Make sure we have a String array
2099
  Klass* element_klass = ObjArrayKlass::cast(cmds_ah->klass())->element_klass();
2100 2101 2102 2103 2104
  if (element_klass != SystemDictionary::String_klass()) {
    THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
               "Array element type is not String class");
  }

2105
  GrowableArray<DCmdInfo *>* info_list = DCmdFactory::DCmdInfo_list(DCmd_Source_MBean);
2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127

  int num_cmds = cmds_ah->length();
  for (int i = 0; i < num_cmds; i++) {
    oop cmd = cmds_ah->obj_at(i);
    if (cmd == NULL) {
        THROW_MSG(vmSymbols::java_lang_NullPointerException(),
                "Command name cannot be null.");
    }
    char* cmd_name = java_lang_String::as_utf8_string(cmd);
    if (cmd_name == NULL) {
        THROW_MSG(vmSymbols::java_lang_NullPointerException(),
                "Command name cannot be null.");
    }
    int pos = info_list->find((void*)cmd_name,DCmdInfo::by_name);
    if (pos == -1) {
        THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
             "Unknown diagnostic command");
    }
    DCmdInfo* info = info_list->at(pos);
    infoArray[i].name = info->name();
    infoArray[i].description = info->description();
    infoArray[i].impact = info->impact();
2128 2129 2130 2131
    JavaPermission p = info->permission();
    infoArray[i].permission_class = p._class;
    infoArray[i].permission_name = p._name;
    infoArray[i].permission_action = p._action;
2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150
    infoArray[i].num_arguments = info->num_arguments();
    infoArray[i].enabled = info->is_enabled();
  }
JVM_END

JVM_ENTRY(void, jmm_GetDiagnosticCommandArgumentsInfo(JNIEnv *env,
          jstring command, dcmdArgInfo* infoArray))
  ResourceMark rm(THREAD);
  oop cmd = JNIHandles::resolve_external_guard(command);
  if (cmd == NULL) {
    THROW_MSG(vmSymbols::java_lang_NullPointerException(),
              "Command line cannot be null.");
  }
  char* cmd_name = java_lang_String::as_utf8_string(cmd);
  if (cmd_name == NULL) {
    THROW_MSG(vmSymbols::java_lang_NullPointerException(),
              "Command line content cannot be null.");
  }
  DCmd* dcmd = NULL;
2151 2152
  DCmdFactory*factory = DCmdFactory::factory(DCmd_Source_MBean, cmd_name,
                                             strlen(cmd_name));
2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171
  if (factory != NULL) {
    dcmd = factory->create_resource_instance(NULL);
  }
  if (dcmd == NULL) {
    THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
              "Unknown diagnostic command");
  }
  DCmdMark mark(dcmd);
  GrowableArray<DCmdArgumentInfo*>* array = dcmd->argument_info_array();
  if (array->length() == 0) {
    return;
  }
  for (int i = 0; i < array->length(); i++) {
    infoArray[i].name = array->at(i)->name();
    infoArray[i].description = array->at(i)->description();
    infoArray[i].type = array->at(i)->type();
    infoArray[i].default_string = array->at(i)->default_string();
    infoArray[i].mandatory = array->at(i)->is_mandatory();
    infoArray[i].option = array->at(i)->is_option();
2172
    infoArray[i].multiple = array->at(i)->is_multiple();
2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190
    infoArray[i].position = array->at(i)->position();
  }
  return;
JVM_END

JVM_ENTRY(jstring, jmm_ExecuteDiagnosticCommand(JNIEnv *env, jstring commandline))
  ResourceMark rm(THREAD);
  oop cmd = JNIHandles::resolve_external_guard(commandline);
  if (cmd == NULL) {
    THROW_MSG_NULL(vmSymbols::java_lang_NullPointerException(),
                   "Command line cannot be null.");
  }
  char* cmdline = java_lang_String::as_utf8_string(cmd);
  if (cmdline == NULL) {
    THROW_MSG_NULL(vmSymbols::java_lang_NullPointerException(),
                   "Command line content cannot be null.");
  }
  bufferedStream output;
2191
  DCmd::parse_and_execute(DCmd_Source_MBean, &output, cmdline, ' ', CHECK_NULL);
2192 2193 2194 2195
  oop result = java_lang_String::create_oop_from_str(output.as_string(), CHECK_NULL);
  return (jstring) JNIHandles::make_local(env, result);
JVM_END

2196 2197 2198 2199
JVM_ENTRY(void, jmm_SetDiagnosticFrameworkNotificationEnabled(JNIEnv *env, jboolean enabled))
  DCmdFactory::set_jmx_notification_enabled(enabled?true:false);
JVM_END

D
duke 已提交
2200 2201 2202 2203 2204
jlong Management::ticks_to_ms(jlong ticks) {
  assert(os::elapsed_frequency() > 0, "Must be non-zero");
  return (jlong)(((double)ticks / (double)os::elapsed_frequency())
                 * (double)1000.0);
}
S
sla 已提交
2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235
#endif // INCLUDE_MANAGEMENT

// Gets an array containing the amount of memory allocated on the Java
// heap for a set of threads (in bytes).  Each element of the array is
// the amount of memory allocated for the thread ID specified in the
// corresponding entry in the given array of thread IDs; or -1 if the
// thread does not exist or has terminated.
JVM_ENTRY(void, jmm_GetThreadAllocatedMemory(JNIEnv *env, jlongArray ids,
                                             jlongArray sizeArray))
  // Check if threads is null
  if (ids == NULL || sizeArray == NULL) {
    THROW(vmSymbols::java_lang_NullPointerException());
  }

  ResourceMark rm(THREAD);
  typeArrayOop ta = typeArrayOop(JNIHandles::resolve_non_null(ids));
  typeArrayHandle ids_ah(THREAD, ta);

  typeArrayOop sa = typeArrayOop(JNIHandles::resolve_non_null(sizeArray));
  typeArrayHandle sizeArray_h(THREAD, sa);

  // validate the thread id array
  validate_thread_id_array(ids_ah, CHECK);

  // sizeArray must be of the same length as the given array of thread IDs
  int num_threads = ids_ah->length();
  if (num_threads != sizeArray_h->length()) {
    THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
              "The length of the given long array does not match the length of "
              "the given array of thread IDs");
  }
D
duke 已提交
2236

S
sla 已提交
2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320
  MutexLockerEx ml(Threads_lock);
  for (int i = 0; i < num_threads; i++) {
    JavaThread* java_thread = Threads::find_java_thread_from_java_tid(ids_ah->long_at(i));
    if (java_thread != NULL) {
      sizeArray_h->long_at_put(i, java_thread->cooked_allocated_bytes());
    }
  }
JVM_END

// Returns the CPU time consumed by a given thread (in nanoseconds).
// If thread_id == 0, CPU time for the current thread is returned.
// If user_sys_cpu_time = true, user level and system CPU time of
// a given thread is returned; otherwise, only user level CPU time
// is returned.
JVM_ENTRY(jlong, jmm_GetThreadCpuTimeWithKind(JNIEnv *env, jlong thread_id, jboolean user_sys_cpu_time))
  if (!os::is_thread_cpu_time_supported()) {
    return -1;
  }

  if (thread_id < 0) {
    THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
               "Invalid thread ID", -1);
  }

  JavaThread* java_thread = NULL;
  if (thread_id == 0) {
    // current thread
    return os::current_thread_cpu_time(user_sys_cpu_time != 0);
  } else {
    MutexLockerEx ml(Threads_lock);
    java_thread = Threads::find_java_thread_from_java_tid(thread_id);
    if (java_thread != NULL) {
      return os::thread_cpu_time((Thread*) java_thread, user_sys_cpu_time != 0);
    }
  }
  return -1;
JVM_END

// Gets an array containing the CPU times consumed by a set of threads
// (in nanoseconds).  Each element of the array is the CPU time for the
// thread ID specified in the corresponding entry in the given array
// of thread IDs; or -1 if the thread does not exist or has terminated.
// If user_sys_cpu_time = true, the sum of user level and system CPU time
// for the given thread is returned; otherwise, only user level CPU time
// is returned.
JVM_ENTRY(void, jmm_GetThreadCpuTimesWithKind(JNIEnv *env, jlongArray ids,
                                              jlongArray timeArray,
                                              jboolean user_sys_cpu_time))
  // Check if threads is null
  if (ids == NULL || timeArray == NULL) {
    THROW(vmSymbols::java_lang_NullPointerException());
  }

  ResourceMark rm(THREAD);
  typeArrayOop ta = typeArrayOop(JNIHandles::resolve_non_null(ids));
  typeArrayHandle ids_ah(THREAD, ta);

  typeArrayOop tia = typeArrayOop(JNIHandles::resolve_non_null(timeArray));
  typeArrayHandle timeArray_h(THREAD, tia);

  // validate the thread id array
  validate_thread_id_array(ids_ah, CHECK);

  // timeArray must be of the same length as the given array of thread IDs
  int num_threads = ids_ah->length();
  if (num_threads != timeArray_h->length()) {
    THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
              "The length of the given long array does not match the length of "
              "the given array of thread IDs");
  }

  MutexLockerEx ml(Threads_lock);
  for (int i = 0; i < num_threads; i++) {
    JavaThread* java_thread = Threads::find_java_thread_from_java_tid(ids_ah->long_at(i));
    if (java_thread != NULL) {
      timeArray_h->long_at_put(i, os::thread_cpu_time((Thread*)java_thread,
                                                      user_sys_cpu_time != 0));
    }
  }
JVM_END



#if INCLUDE_MANAGEMENT
D
duke 已提交
2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332
const struct jmmInterface_1_ jmm_interface = {
  NULL,
  NULL,
  jmm_GetVersion,
  jmm_GetOptionalSupport,
  jmm_GetInputArguments,
  jmm_GetThreadInfo,
  jmm_GetInputArgumentArray,
  jmm_GetMemoryPools,
  jmm_GetMemoryManagers,
  jmm_GetMemoryPoolUsage,
  jmm_GetPeakMemoryPoolUsage,
2333
  jmm_GetThreadAllocatedMemory,
D
duke 已提交
2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350
  jmm_GetMemoryUsage,
  jmm_GetLongAttribute,
  jmm_GetBoolAttribute,
  jmm_SetBoolAttribute,
  jmm_GetLongAttributes,
  jmm_FindMonitorDeadlockedThreads,
  jmm_GetThreadCpuTime,
  jmm_GetVMGlobalNames,
  jmm_GetVMGlobals,
  jmm_GetInternalThreadTimes,
  jmm_ResetStatistic,
  jmm_SetPoolSensor,
  jmm_SetPoolThreshold,
  jmm_GetPoolCollectionUsage,
  jmm_GetGCExtAttributeInfo,
  jmm_GetLastGCStat,
  jmm_GetThreadCpuTimeWithKind,
2351
  jmm_GetThreadCpuTimesWithKind,
D
duke 已提交
2352 2353 2354 2355
  jmm_DumpHeap0,
  jmm_FindDeadlockedThreads,
  jmm_SetVMGlobal,
  NULL,
2356
  jmm_DumpThreads,
2357 2358 2359 2360
  jmm_SetGCNotificationEnabled,
  jmm_GetDiagnosticCommands,
  jmm_GetDiagnosticCommandInfo,
  jmm_GetDiagnosticCommandArgumentsInfo,
2361 2362
  jmm_ExecuteDiagnosticCommand,
  jmm_SetDiagnosticFrameworkNotificationEnabled
D
duke 已提交
2363
};
2364
#endif // INCLUDE_MANAGEMENT
D
duke 已提交
2365 2366

void* Management::get_jmm_interface(int version) {
2367
#if INCLUDE_MANAGEMENT
D
duke 已提交
2368 2369 2370
  if (version == JMM_VERSION_1_0) {
    return (void*) &jmm_interface;
  }
2371
#endif // INCLUDE_MANAGEMENT
D
duke 已提交
2372 2373
  return NULL;
}