1 /*
   2  * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "classfile/classLoaderStats.hpp"
  27 #include "classfile/compactHashtable.hpp"
  28 #include "compiler/compileBroker.hpp"
  29 #include "compiler/directivesParser.hpp"
  30 #include "gc/shared/vmGCOperations.hpp"
  31 #include "memory/resourceArea.hpp"
  32 #include "oops/oop.inline.hpp"
  33 #include "runtime/globals.hpp"
  34 #include "runtime/javaCalls.hpp"
  35 #include "runtime/os.hpp"
  36 #include "services/diagnosticArgument.hpp"
  37 #include "services/diagnosticCommand.hpp"
  38 #include "services/diagnosticFramework.hpp"
  39 #include "services/heapDumper.hpp"
  40 #include "services/management.hpp"
  41 #include "services/writeableFlags.hpp"
  42 #include "utilities/macros.hpp"
  43 #include "oops/objArrayOop.inline.hpp"
  44 
  45 void DCmdRegistrant::register_dcmds(){
  46   // Registration of the diagnostic commands
  47   // First argument specifies which interfaces will export the command
  48   // Second argument specifies if the command is enabled
  49   // Third  argument specifies if the command is hidden
  50   uint32_t full_export = DCmd_Source_Internal | DCmd_Source_AttachAPI
  51                          | DCmd_Source_MBean;
  52   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<HelpDCmd>(full_export, true, false));
  53   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<VersionDCmd>(full_export, true, false));
  54   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<CommandLineDCmd>(full_export, true, false));
  55   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<PrintSystemPropertiesDCmd>(full_export, true, false));
  56   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<PrintVMFlagsDCmd>(full_export, true, false));
  57   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<SetVMFlagDCmd>(full_export, true, false));
  58   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<VMDynamicLibrariesDCmd>(full_export, true, false));
  59   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<VMUptimeDCmd>(full_export, true, false));
  60   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<VMInfoDCmd>(full_export, true, false));
  61   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<SystemGCDCmd>(full_export, true, false));
  62   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<RunFinalizationDCmd>(full_export, true, false));
  63   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<HeapInfoDCmd>(full_export, true, false));
  64   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<FinalizerInfoDCmd>(full_export, true, false));
  65 #if INCLUDE_SERVICES
  66   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<HeapDumpDCmd>(DCmd_Source_Internal | DCmd_Source_AttachAPI, true, false));
  67   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<ClassHistogramDCmd>(full_export, true, false));
  68   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<ClassStatsDCmd>(full_export, true, false));
  69   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<ClassHierarchyDCmd>(full_export, true, false));
  70   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<SymboltableDCmd>(full_export, true, false));
  71   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<StringtableDCmd>(full_export, true, false));
  72 #if INCLUDE_JVMTI // Both JVMTI and SERVICES have to be enabled to have this dcmd
  73   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<JVMTIAgentLoadDCmd>(full_export, true, false));
  74 #endif // INCLUDE_JVMTI
  75 #endif // INCLUDE_SERVICES
  76 #if INCLUDE_JVMTI
  77   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<JVMTIDataDumpDCmd>(full_export, true, false));
  78 #endif // INCLUDE_JVMTI
  79   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<ThreadDumpDCmd>(full_export, true, false));
  80   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<ClassLoaderStatsDCmd>(full_export, true, false));
  81   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<CompileQueueDCmd>(full_export, true, false));
  82   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<CodeListDCmd>(full_export, true, false));
  83   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<CodeCacheDCmd>(full_export, true, false));
  84   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<TouchedMethodsDCmd>(full_export, true, false));
  85 
  86   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<CompilerDirectivesPrintDCmd>(full_export, true, false));
  87   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<CompilerDirectivesAddDCmd>(full_export, true, false));
  88   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<CompilerDirectivesRemoveDCmd>(full_export, true, false));
  89   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<CompilerDirectivesClearDCmd>(full_export, true, false));
  90 
  91   // Enhanced JMX Agent Support
  92   // These commands won't be exported via the DiagnosticCommandMBean until an
  93   // appropriate permission is created for them
  94   uint32_t jmx_agent_export_flags = DCmd_Source_Internal | DCmd_Source_AttachAPI;
  95   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<JMXStartRemoteDCmd>(jmx_agent_export_flags, true,false));
  96   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<JMXStartLocalDCmd>(jmx_agent_export_flags, true,false));
  97   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<JMXStopRemoteDCmd>(jmx_agent_export_flags, true,false));
  98   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<JMXStatusDCmd>(jmx_agent_export_flags, true,false));
  99 
 100 }
 101 
 102 #ifndef HAVE_EXTRA_DCMD
 103 void DCmdRegistrant::register_dcmds_ext(){
 104    // Do nothing here
 105 }
 106 #endif
 107 
 108 
 109 HelpDCmd::HelpDCmd(outputStream* output, bool heap) : DCmdWithParser(output, heap),
 110   _all("-all", "Show help for all commands", "BOOLEAN", false, "false"),
 111   _cmd("command name", "The name of the command for which we want help",
 112         "STRING", false) {
 113   _dcmdparser.add_dcmd_option(&_all);
 114   _dcmdparser.add_dcmd_argument(&_cmd);
 115 };
 116 
 117 void HelpDCmd::execute(DCmdSource source, TRAPS) {
 118   if (_all.value()) {
 119     GrowableArray<const char*>* cmd_list = DCmdFactory::DCmd_list(source);
 120     for (int i = 0; i < cmd_list->length(); i++) {
 121       DCmdFactory* factory = DCmdFactory::factory(source, cmd_list->at(i),
 122                                                   strlen(cmd_list->at(i)));
 123       output()->print_cr("%s%s", factory->name(),
 124                          factory->is_enabled() ? "" : " [disabled]");
 125       output()->print_cr("\t%s", factory->description());
 126       output()->cr();
 127       factory = factory->next();
 128     }
 129   } else if (_cmd.has_value()) {
 130     DCmd* cmd = NULL;
 131     DCmdFactory* factory = DCmdFactory::factory(source, _cmd.value(),
 132                                                 strlen(_cmd.value()));
 133     if (factory != NULL) {
 134       output()->print_cr("%s%s", factory->name(),
 135                          factory->is_enabled() ? "" : " [disabled]");
 136       output()->print_cr("%s", factory->description());
 137       output()->print_cr("\nImpact: %s", factory->impact());
 138       JavaPermission p = factory->permission();
 139       if(p._class != NULL) {
 140         if(p._action != NULL) {
 141           output()->print_cr("\nPermission: %s(%s, %s)",
 142                   p._class, p._name == NULL ? "null" : p._name, p._action);
 143         } else {
 144           output()->print_cr("\nPermission: %s(%s)",
 145                   p._class, p._name == NULL ? "null" : p._name);
 146         }
 147       }
 148       output()->cr();
 149       cmd = factory->create_resource_instance(output());
 150       if (cmd != NULL) {
 151         DCmdMark mark(cmd);
 152         cmd->print_help(factory->name());
 153       }
 154     } else {
 155       output()->print_cr("Help unavailable : '%s' : No such command", _cmd.value());
 156     }
 157   } else {
 158     output()->print_cr("The following commands are available:");
 159     GrowableArray<const char *>* cmd_list = DCmdFactory::DCmd_list(source);
 160     for (int i = 0; i < cmd_list->length(); i++) {
 161       DCmdFactory* factory = DCmdFactory::factory(source, cmd_list->at(i),
 162                                                   strlen(cmd_list->at(i)));
 163       output()->print_cr("%s%s", factory->name(),
 164                          factory->is_enabled() ? "" : " [disabled]");
 165       factory = factory->_next;
 166     }
 167     output()->print_cr("\nFor more information about a specific command use 'help <command>'.");
 168   }
 169 }
 170 
 171 int HelpDCmd::num_arguments() {
 172   ResourceMark rm;
 173   HelpDCmd* dcmd = new HelpDCmd(NULL, false);
 174   if (dcmd != NULL) {
 175     DCmdMark mark(dcmd);
 176     return dcmd->_dcmdparser.num_arguments();
 177   } else {
 178     return 0;
 179   }
 180 }
 181 
 182 void VersionDCmd::execute(DCmdSource source, TRAPS) {
 183   output()->print_cr("%s version %s", Abstract_VM_Version::vm_name(),
 184           Abstract_VM_Version::vm_release());
 185   JDK_Version jdk_version = JDK_Version::current();
 186   if (jdk_version.patch_version() > 0) {
 187     output()->print_cr("JDK %d.%d.%d.%d", jdk_version.major_version(),
 188             jdk_version.minor_version(), jdk_version.security_version(),
 189             jdk_version.patch_version());
 190   } else {
 191     output()->print_cr("JDK %d.%d.%d", jdk_version.major_version(),
 192             jdk_version.minor_version(), jdk_version.security_version());
 193   }
 194 }
 195 
 196 PrintVMFlagsDCmd::PrintVMFlagsDCmd(outputStream* output, bool heap) :
 197                                    DCmdWithParser(output, heap),
 198   _all("-all", "Print all flags supported by the VM", "BOOLEAN", false, "false") {
 199   _dcmdparser.add_dcmd_option(&_all);
 200 }
 201 
 202 void PrintVMFlagsDCmd::execute(DCmdSource source, TRAPS) {
 203   if (_all.value()) {
 204     CommandLineFlags::printFlags(output(), true);
 205   } else {
 206     CommandLineFlags::printSetFlags(output());
 207   }
 208 }
 209 
 210 int PrintVMFlagsDCmd::num_arguments() {
 211     ResourceMark rm;
 212     PrintVMFlagsDCmd* dcmd = new PrintVMFlagsDCmd(NULL, false);
 213     if (dcmd != NULL) {
 214       DCmdMark mark(dcmd);
 215       return dcmd->_dcmdparser.num_arguments();
 216     } else {
 217       return 0;
 218     }
 219 }
 220 
 221 SetVMFlagDCmd::SetVMFlagDCmd(outputStream* output, bool heap) :
 222                                    DCmdWithParser(output, heap),
 223   _flag("flag name", "The name of the flag we want to set",
 224         "STRING", true),
 225   _value("string value", "The value we want to set", "STRING", false) {
 226   _dcmdparser.add_dcmd_argument(&_flag);
 227   _dcmdparser.add_dcmd_argument(&_value);
 228 }
 229 
 230 void SetVMFlagDCmd::execute(DCmdSource source, TRAPS) {
 231   const char* val = NULL;
 232   if (_value.value() != NULL) {
 233     val = _value.value();
 234   }
 235 
 236   FormatBuffer<80> err_msg("%s", "");
 237   int ret = WriteableFlags::set_flag(_flag.value(), val, Flag::MANAGEMENT, err_msg);
 238 
 239   if (ret != Flag::SUCCESS) {
 240     output()->print_cr("%s", err_msg.buffer());
 241   }
 242 }
 243 
 244 int SetVMFlagDCmd::num_arguments() {
 245   ResourceMark rm;
 246   SetVMFlagDCmd* dcmd = new SetVMFlagDCmd(NULL, false);
 247   if (dcmd != NULL) {
 248     DCmdMark mark(dcmd);
 249     return dcmd->_dcmdparser.num_arguments();
 250   } else {
 251     return 0;
 252   }
 253 }
 254 
 255 void JVMTIDataDumpDCmd::execute(DCmdSource source, TRAPS) {
 256   if (JvmtiExport::should_post_data_dump()) {
 257     JvmtiExport::post_data_dump();
 258   }
 259 }
 260 
 261 #if INCLUDE_SERVICES
 262 JVMTIAgentLoadDCmd::JVMTIAgentLoadDCmd(outputStream* output, bool heap) :
 263                                        DCmdWithParser(output, heap),
 264   _libpath("library path", "Absolute path of the JVMTI agent to load.",
 265            "STRING", true),
 266   _option("agent option", "Option string to pass the agent.", "STRING", false) {
 267   _dcmdparser.add_dcmd_argument(&_libpath);
 268   _dcmdparser.add_dcmd_argument(&_option);
 269 }
 270 
 271 void JVMTIAgentLoadDCmd::execute(DCmdSource source, TRAPS) {
 272 
 273   if (_libpath.value() == NULL) {
 274     output()->print_cr("JVMTI.agent_load dcmd needs library path.");
 275     return;
 276   }
 277 
 278   char *suffix = strrchr(_libpath.value(), '.');
 279   bool is_java_agent = (suffix != NULL) && (strncmp(".jar", suffix, 4) == 0);
 280   jint result = JNI_ERR;
 281 
 282   if (is_java_agent) {
 283     if (_option.value() == NULL) {
 284       result = JvmtiExport::load_agent_library("instrument", "false",
 285                                                 _libpath.value(), output());
 286     } else {
 287       size_t opt_len = strlen(_libpath.value()) + strlen(_option.value()) + 2;
 288       if (opt_len > 4096) {
 289         output()->print_cr("JVMTI agent attach failed: Options is too long.");
 290         return;
 291       }
 292 
 293       char *opt = (char *)os::malloc(opt_len, mtInternal);
 294       if (opt == NULL) {
 295         output()->print_cr("JVMTI agent attach failed: "
 296                            "Could not allocate %zu bytes for argument.",
 297                            opt_len);
 298         return;
 299       }
 300 
 301       jio_snprintf(opt, opt_len, "%s=%s", _libpath.value(), _option.value());
 302       result = JvmtiExport::load_agent_library("instrument", "false",
 303                                                 opt, output());
 304 
 305       os::free(opt);
 306     }
 307   } else {
 308     result = JvmtiExport::load_agent_library(_libpath.value(), "true",
 309                                              _option.value(), output());
 310   }
 311 
 312   output()->print_cr("JVMTI agent attach %s.",
 313                                   (result == JNI_OK) ? "succeeded" : "failed");
 314 }
 315 
 316 int JVMTIAgentLoadDCmd::num_arguments() {
 317   ResourceMark rm;
 318   JVMTIAgentLoadDCmd* dcmd = new JVMTIAgentLoadDCmd(NULL, false);
 319   if (dcmd != NULL) {
 320     DCmdMark mark(dcmd);
 321     return dcmd->_dcmdparser.num_arguments();
 322   } else {
 323     return 0;
 324   }
 325 }
 326 #endif // INCLUDE_SERVICES
 327 
 328 void PrintSystemPropertiesDCmd::execute(DCmdSource source, TRAPS) {
 329   // load VMSupport
 330   Symbol* klass = vmSymbols::jdk_internal_vm_VMSupport();
 331   Klass* k = SystemDictionary::resolve_or_fail(klass, true, CHECK);
 332   instanceKlassHandle ik (THREAD, k);
 333   if (ik->should_be_initialized()) {
 334     ik->initialize(THREAD);
 335   }
 336   if (HAS_PENDING_EXCEPTION) {
 337     java_lang_Throwable::print(PENDING_EXCEPTION, output());
 338     output()->cr();
 339     CLEAR_PENDING_EXCEPTION;
 340     return;
 341   }
 342 
 343   // invoke the serializePropertiesToByteArray method
 344   JavaValue result(T_OBJECT);
 345   JavaCallArguments args;
 346 
 347   Symbol* signature = vmSymbols::serializePropertiesToByteArray_signature();
 348   JavaCalls::call_static(&result,
 349                          ik,
 350                          vmSymbols::serializePropertiesToByteArray_name(),
 351                          signature,
 352                          &args,
 353                          THREAD);
 354   if (HAS_PENDING_EXCEPTION) {
 355     java_lang_Throwable::print(PENDING_EXCEPTION, output());
 356     output()->cr();
 357     CLEAR_PENDING_EXCEPTION;
 358     return;
 359   }
 360 
 361   // The result should be a [B
 362   oop res = (oop)result.get_jobject();
 363   assert(res->is_typeArray(), "just checking");
 364   assert(TypeArrayKlass::cast(res->klass())->element_type() == T_BYTE, "just checking");
 365 
 366   // copy the bytes to the output stream
 367   typeArrayOop ba = typeArrayOop(res);
 368   jbyte* addr = typeArrayOop(res)->byte_at_addr(0);
 369   output()->print_raw((const char*)addr, ba->length());
 370 }
 371 
 372 VMUptimeDCmd::VMUptimeDCmd(outputStream* output, bool heap) :
 373                            DCmdWithParser(output, heap),
 374   _date("-date", "Add a prefix with current date", "BOOLEAN", false, "false") {
 375   _dcmdparser.add_dcmd_option(&_date);
 376 }
 377 
 378 void VMUptimeDCmd::execute(DCmdSource source, TRAPS) {
 379   if (_date.value()) {
 380     output()->date_stamp(true, "", ": ");
 381   }
 382   output()->time_stamp().update_to(tty->time_stamp().ticks());
 383   output()->stamp();
 384   output()->print_cr(" s");
 385 }
 386 
 387 int VMUptimeDCmd::num_arguments() {
 388   ResourceMark rm;
 389   VMUptimeDCmd* dcmd = new VMUptimeDCmd(NULL, false);
 390   if (dcmd != NULL) {
 391     DCmdMark mark(dcmd);
 392     return dcmd->_dcmdparser.num_arguments();
 393   } else {
 394     return 0;
 395   }
 396 }
 397 
 398 void VMInfoDCmd::execute(DCmdSource source, TRAPS) {
 399   VMError::print_vm_info(_output);
 400 }
 401 
 402 void SystemGCDCmd::execute(DCmdSource source, TRAPS) {
 403   if (!DisableExplicitGC) {
 404     Universe::heap()->collect(GCCause::_dcmd_gc_run);
 405   } else {
 406     output()->print_cr("Explicit GC is disabled, no GC has been performed.");
 407   }
 408 }
 409 
 410 void RunFinalizationDCmd::execute(DCmdSource source, TRAPS) {
 411   Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_System(),
 412                                                  true, CHECK);
 413   instanceKlassHandle klass(THREAD, k);
 414   JavaValue result(T_VOID);
 415   JavaCalls::call_static(&result, klass,
 416                          vmSymbols::run_finalization_name(),
 417                          vmSymbols::void_method_signature(), CHECK);
 418 }
 419 
 420 void HeapInfoDCmd::execute(DCmdSource source, TRAPS) {
 421   MutexLocker hl(Heap_lock);
 422   Universe::heap()->print_on(output());
 423 }
 424 
 425 void FinalizerInfoDCmd::execute(DCmdSource source, TRAPS) {
 426   ResourceMark rm;
 427 
 428 
 429   Klass* k = SystemDictionary::resolve_or_null(
 430     vmSymbols::finalizer_histogram_klass(), THREAD);
 431   assert(k != NULL, "FinalizerHistogram class is not accessible");
 432 
 433   instanceKlassHandle klass(THREAD, k);
 434   JavaValue result(T_ARRAY);
 435 
 436   // We are calling lang.ref.FinalizerHistogram.getFinalizerHistogram() method
 437   // and expect it to return array of FinalizerHistogramEntry as Object[]
 438 
 439   JavaCalls::call_static(&result, klass,
 440                          vmSymbols::get_finalizer_histogram_name(),
 441                          vmSymbols::void_finalizer_histogram_entry_array_signature(), CHECK);
 442 
 443   objArrayOop result_oop = (objArrayOop) result.get_jobject();
 444   if (result_oop->length() == 0) {
 445     output()->print_cr("No instances waiting for finalization found");
 446     return;
 447   }
 448 
 449   oop foop = result_oop->obj_at(0);
 450   InstanceKlass* ik = InstanceKlass::cast(foop->klass());
 451 
 452   fieldDescriptor count_fd, name_fd;
 453 
 454   Klass* count_res = ik->find_field(
 455     vmSymbols::finalizer_histogram_entry_count_field(), vmSymbols::int_signature(), &count_fd);
 456 
 457   Klass* name_res = ik->find_field(
 458     vmSymbols::finalizer_histogram_entry_name_field(), vmSymbols::string_signature(), &name_fd);
 459 
 460   assert(count_res != NULL && name_res != NULL, "Unexpected layout of FinalizerHistogramEntry");
 461 
 462   output()->print_cr("Unreachable instances waiting for finalization");
 463   output()->print_cr("#instances  class name");
 464   output()->print_cr("-----------------------");
 465 
 466   for (int i = 0; i < result_oop->length(); ++i) {
 467     oop element_oop = result_oop->obj_at(i);
 468     oop str_oop = element_oop->obj_field(name_fd.offset());
 469     char *name = java_lang_String::as_utf8_string(str_oop);
 470     int count = element_oop->int_field(count_fd.offset());
 471     output()->print_cr("%10d  %s", count, name);
 472   }
 473 }
 474 
 475 #if INCLUDE_SERVICES // Heap dumping/inspection supported
 476 HeapDumpDCmd::HeapDumpDCmd(outputStream* output, bool heap) :
 477                            DCmdWithParser(output, heap),
 478   _filename("filename","Name of the dump file", "STRING",true),
 479   _all("-all", "Dump all objects, including unreachable objects",
 480        "BOOLEAN", false, "false") {
 481   _dcmdparser.add_dcmd_option(&_all);
 482   _dcmdparser.add_dcmd_argument(&_filename);
 483 }
 484 
 485 void HeapDumpDCmd::execute(DCmdSource source, TRAPS) {
 486   // Request a full GC before heap dump if _all is false
 487   // This helps reduces the amount of unreachable objects in the dump
 488   // and makes it easier to browse.
 489   HeapDumper dumper(!_all.value() /* request GC if _all is false*/);
 490   int res = dumper.dump(_filename.value());
 491   if (res == 0) {
 492     output()->print_cr("Heap dump file created");
 493   } else {
 494     // heap dump failed
 495     ResourceMark rm;
 496     char* error = dumper.error_as_C_string();
 497     if (error == NULL) {
 498       output()->print_cr("Dump failed - reason unknown");
 499     } else {
 500       output()->print_cr("%s", error);
 501     }
 502   }
 503 }
 504 
 505 int HeapDumpDCmd::num_arguments() {
 506   ResourceMark rm;
 507   HeapDumpDCmd* dcmd = new HeapDumpDCmd(NULL, false);
 508   if (dcmd != NULL) {
 509     DCmdMark mark(dcmd);
 510     return dcmd->_dcmdparser.num_arguments();
 511   } else {
 512     return 0;
 513   }
 514 }
 515 
 516 ClassHistogramDCmd::ClassHistogramDCmd(outputStream* output, bool heap) :
 517                                        DCmdWithParser(output, heap),
 518   _all("-all", "Inspect all objects, including unreachable objects",
 519        "BOOLEAN", false, "false") {
 520   _dcmdparser.add_dcmd_option(&_all);
 521 }
 522 
 523 void ClassHistogramDCmd::execute(DCmdSource source, TRAPS) {
 524   VM_GC_HeapInspection heapop(output(),
 525                               !_all.value() /* request full gc if false */);
 526   VMThread::execute(&heapop);
 527 }
 528 
 529 int ClassHistogramDCmd::num_arguments() {
 530   ResourceMark rm;
 531   ClassHistogramDCmd* dcmd = new ClassHistogramDCmd(NULL, false);
 532   if (dcmd != NULL) {
 533     DCmdMark mark(dcmd);
 534     return dcmd->_dcmdparser.num_arguments();
 535   } else {
 536     return 0;
 537   }
 538 }
 539 
 540 #define DEFAULT_COLUMNS "InstBytes,KlassBytes,CpAll,annotations,MethodCount,Bytecodes,MethodAll,ROAll,RWAll,Total"
 541 ClassStatsDCmd::ClassStatsDCmd(outputStream* output, bool heap) :
 542                                        DCmdWithParser(output, heap),
 543   _csv("-csv", "Print in CSV (comma-separated values) format for spreadsheets",
 544        "BOOLEAN", false, "false"),
 545   _all("-all", "Show all columns",
 546        "BOOLEAN", false, "false"),
 547   _help("-help", "Show meaning of all the columns",
 548        "BOOLEAN", false, "false"),
 549   _columns("columns", "Comma-separated list of all the columns to show. "
 550            "If not specified, the following columns are shown: " DEFAULT_COLUMNS,
 551            "STRING", false) {
 552   _dcmdparser.add_dcmd_option(&_all);
 553   _dcmdparser.add_dcmd_option(&_csv);
 554   _dcmdparser.add_dcmd_option(&_help);
 555   _dcmdparser.add_dcmd_argument(&_columns);
 556 }
 557 
 558 void ClassStatsDCmd::execute(DCmdSource source, TRAPS) {
 559   if (!UnlockDiagnosticVMOptions) {
 560     output()->print_cr("GC.class_stats command requires -XX:+UnlockDiagnosticVMOptions");
 561     return;
 562   }
 563 
 564   VM_GC_HeapInspection heapop(output(),
 565                               true /* request_full_gc */);
 566   heapop.set_csv_format(_csv.value());
 567   heapop.set_print_help(_help.value());
 568   heapop.set_print_class_stats(true);
 569   if (_all.value()) {
 570     if (_columns.has_value()) {
 571       output()->print_cr("Cannot specify -all and individual columns at the same time");
 572       return;
 573     } else {
 574       heapop.set_columns(NULL);
 575     }
 576   } else {
 577     if (_columns.has_value()) {
 578       heapop.set_columns(_columns.value());
 579     } else {
 580       heapop.set_columns(DEFAULT_COLUMNS);
 581     }
 582   }
 583   VMThread::execute(&heapop);
 584 }
 585 
 586 int ClassStatsDCmd::num_arguments() {
 587   ResourceMark rm;
 588   ClassStatsDCmd* dcmd = new ClassStatsDCmd(NULL, false);
 589   if (dcmd != NULL) {
 590     DCmdMark mark(dcmd);
 591     return dcmd->_dcmdparser.num_arguments();
 592   } else {
 593     return 0;
 594   }
 595 }
 596 #endif // INCLUDE_SERVICES
 597 
 598 ThreadDumpDCmd::ThreadDumpDCmd(outputStream* output, bool heap) :
 599                                DCmdWithParser(output, heap),
 600   _locks("-l", "print java.util.concurrent locks", "BOOLEAN", false, "false") {
 601   _dcmdparser.add_dcmd_option(&_locks);
 602 }
 603 
 604 void ThreadDumpDCmd::execute(DCmdSource source, TRAPS) {
 605   // thread stacks
 606   VM_PrintThreads op1(output(), _locks.value());
 607   VMThread::execute(&op1);
 608 
 609   // JNI global handles
 610   VM_PrintJNI op2(output());
 611   VMThread::execute(&op2);
 612 
 613   // Deadlock detection
 614   VM_FindDeadlocks op3(output());
 615   VMThread::execute(&op3);
 616 }
 617 
 618 int ThreadDumpDCmd::num_arguments() {
 619   ResourceMark rm;
 620   ThreadDumpDCmd* dcmd = new ThreadDumpDCmd(NULL, false);
 621   if (dcmd != NULL) {
 622     DCmdMark mark(dcmd);
 623     return dcmd->_dcmdparser.num_arguments();
 624   } else {
 625     return 0;
 626   }
 627 }
 628 
 629 // Enhanced JMX Agent support
 630 
 631 JMXStartRemoteDCmd::JMXStartRemoteDCmd(outputStream *output, bool heap_allocated) :
 632 
 633   DCmdWithParser(output, heap_allocated),
 634 
 635   _config_file
 636   ("config.file",
 637    "set com.sun.management.config.file", "STRING", false),
 638 
 639   _jmxremote_host
 640   ("jmxremote.host",
 641    "set com.sun.management.jmxremote.host", "STRING", false),
 642 
 643   _jmxremote_port
 644   ("jmxremote.port",
 645    "set com.sun.management.jmxremote.port", "STRING", false),
 646 
 647   _jmxremote_rmi_port
 648   ("jmxremote.rmi.port",
 649    "set com.sun.management.jmxremote.rmi.port", "STRING", false),
 650 
 651   _jmxremote_ssl
 652   ("jmxremote.ssl",
 653    "set com.sun.management.jmxremote.ssl", "STRING", false),
 654 
 655   _jmxremote_registry_ssl
 656   ("jmxremote.registry.ssl",
 657    "set com.sun.management.jmxremote.registry.ssl", "STRING", false),
 658 
 659   _jmxremote_authenticate
 660   ("jmxremote.authenticate",
 661    "set com.sun.management.jmxremote.authenticate", "STRING", false),
 662 
 663   _jmxremote_password_file
 664   ("jmxremote.password.file",
 665    "set com.sun.management.jmxremote.password.file", "STRING", false),
 666 
 667   _jmxremote_access_file
 668   ("jmxremote.access.file",
 669    "set com.sun.management.jmxremote.access.file", "STRING", false),
 670 
 671   _jmxremote_login_config
 672   ("jmxremote.login.config",
 673    "set com.sun.management.jmxremote.login.config", "STRING", false),
 674 
 675   _jmxremote_ssl_enabled_cipher_suites
 676   ("jmxremote.ssl.enabled.cipher.suites",
 677    "set com.sun.management.jmxremote.ssl.enabled.cipher.suite", "STRING", false),
 678 
 679   _jmxremote_ssl_enabled_protocols
 680   ("jmxremote.ssl.enabled.protocols",
 681    "set com.sun.management.jmxremote.ssl.enabled.protocols", "STRING", false),
 682 
 683   _jmxremote_ssl_need_client_auth
 684   ("jmxremote.ssl.need.client.auth",
 685    "set com.sun.management.jmxremote.need.client.auth", "STRING", false),
 686 
 687   _jmxremote_ssl_config_file
 688   ("jmxremote.ssl.config.file",
 689    "set com.sun.management.jmxremote.ssl_config_file", "STRING", false),
 690 
 691 // JDP Protocol support
 692   _jmxremote_autodiscovery
 693   ("jmxremote.autodiscovery",
 694    "set com.sun.management.jmxremote.autodiscovery", "STRING", false),
 695 
 696    _jdp_port
 697   ("jdp.port",
 698    "set com.sun.management.jdp.port", "INT", false),
 699 
 700    _jdp_address
 701   ("jdp.address",
 702    "set com.sun.management.jdp.address", "STRING", false),
 703 
 704    _jdp_source_addr
 705   ("jdp.source_addr",
 706    "set com.sun.management.jdp.source_addr", "STRING", false),
 707 
 708    _jdp_ttl
 709   ("jdp.ttl",
 710    "set com.sun.management.jdp.ttl", "INT", false),
 711 
 712    _jdp_pause
 713   ("jdp.pause",
 714    "set com.sun.management.jdp.pause", "INT", false),
 715 
 716    _jdp_name
 717   ("jdp.name",
 718    "set com.sun.management.jdp.name", "STRING", false)
 719 
 720   {
 721     _dcmdparser.add_dcmd_option(&_config_file);
 722     _dcmdparser.add_dcmd_option(&_jmxremote_host);
 723     _dcmdparser.add_dcmd_option(&_jmxremote_port);
 724     _dcmdparser.add_dcmd_option(&_jmxremote_rmi_port);
 725     _dcmdparser.add_dcmd_option(&_jmxremote_ssl);
 726     _dcmdparser.add_dcmd_option(&_jmxremote_registry_ssl);
 727     _dcmdparser.add_dcmd_option(&_jmxremote_authenticate);
 728     _dcmdparser.add_dcmd_option(&_jmxremote_password_file);
 729     _dcmdparser.add_dcmd_option(&_jmxremote_access_file);
 730     _dcmdparser.add_dcmd_option(&_jmxremote_login_config);
 731     _dcmdparser.add_dcmd_option(&_jmxremote_ssl_enabled_cipher_suites);
 732     _dcmdparser.add_dcmd_option(&_jmxremote_ssl_enabled_protocols);
 733     _dcmdparser.add_dcmd_option(&_jmxremote_ssl_need_client_auth);
 734     _dcmdparser.add_dcmd_option(&_jmxremote_ssl_config_file);
 735     _dcmdparser.add_dcmd_option(&_jmxremote_autodiscovery);
 736     _dcmdparser.add_dcmd_option(&_jdp_port);
 737     _dcmdparser.add_dcmd_option(&_jdp_address);
 738     _dcmdparser.add_dcmd_option(&_jdp_source_addr);
 739     _dcmdparser.add_dcmd_option(&_jdp_ttl);
 740     _dcmdparser.add_dcmd_option(&_jdp_pause);
 741     _dcmdparser.add_dcmd_option(&_jdp_name);
 742 }
 743 
 744 
 745 int JMXStartRemoteDCmd::num_arguments() {
 746   ResourceMark rm;
 747   JMXStartRemoteDCmd* dcmd = new JMXStartRemoteDCmd(NULL, false);
 748   if (dcmd != NULL) {
 749     DCmdMark mark(dcmd);
 750     return dcmd->_dcmdparser.num_arguments();
 751   } else {
 752     return 0;
 753   }
 754 }
 755 
 756 
 757 void JMXStartRemoteDCmd::execute(DCmdSource source, TRAPS) {
 758     ResourceMark rm(THREAD);
 759     HandleMark hm(THREAD);
 760 
 761     // Load and initialize the sun.management.Agent class
 762     // invoke startRemoteManagementAgent(string) method to start
 763     // the remote management server.
 764     // throw java.lang.NoSuchMethodError if the method doesn't exist
 765 
 766     Handle loader = Handle(THREAD, SystemDictionary::java_system_loader());
 767     Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::sun_management_Agent(), loader, Handle(), true, CHECK);
 768     instanceKlassHandle ik (THREAD, k);
 769 
 770     JavaValue result(T_VOID);
 771 
 772     // Pass all command line arguments to java as key=value,...
 773     // All checks are done on java side
 774 
 775     int len = 0;
 776     stringStream options;
 777     char comma[2] = {0,0};
 778 
 779     // Leave default values on Agent.class side and pass only
 780     // agruments explicitly set by user. All arguments passed
 781     // to jcmd override properties with the same name set by
 782     // command line with -D or by managmenent.properties
 783     // file.
 784 #define PUT_OPTION(a) \
 785     do { \
 786         if ( (a).is_set() ){ \
 787             if ( *((a).type()) == 'I' ) { \
 788                 options.print("%scom.sun.management.%s=" JLONG_FORMAT, comma, (a).name(), (jlong)((a).value())); \
 789             } else { \
 790                 options.print("%scom.sun.management.%s=%s", comma, (a).name(), (char*)((a).value())); \
 791             } \
 792             comma[0] = ','; \
 793         }\
 794     } while(0);
 795 
 796 
 797     PUT_OPTION(_config_file);
 798     PUT_OPTION(_jmxremote_host);
 799     PUT_OPTION(_jmxremote_port);
 800     PUT_OPTION(_jmxremote_rmi_port);
 801     PUT_OPTION(_jmxremote_ssl);
 802     PUT_OPTION(_jmxremote_registry_ssl);
 803     PUT_OPTION(_jmxremote_authenticate);
 804     PUT_OPTION(_jmxremote_password_file);
 805     PUT_OPTION(_jmxremote_access_file);
 806     PUT_OPTION(_jmxremote_login_config);
 807     PUT_OPTION(_jmxremote_ssl_enabled_cipher_suites);
 808     PUT_OPTION(_jmxremote_ssl_enabled_protocols);
 809     PUT_OPTION(_jmxremote_ssl_need_client_auth);
 810     PUT_OPTION(_jmxremote_ssl_config_file);
 811     PUT_OPTION(_jmxremote_autodiscovery);
 812     PUT_OPTION(_jdp_port);
 813     PUT_OPTION(_jdp_address);
 814     PUT_OPTION(_jdp_source_addr);
 815     PUT_OPTION(_jdp_ttl);
 816     PUT_OPTION(_jdp_pause);
 817     PUT_OPTION(_jdp_name);
 818 
 819 #undef PUT_OPTION
 820 
 821     Handle str = java_lang_String::create_from_str(options.as_string(), CHECK);
 822     JavaCalls::call_static(&result, ik, vmSymbols::startRemoteAgent_name(), vmSymbols::string_void_signature(), str, CHECK);
 823 }
 824 
 825 JMXStartLocalDCmd::JMXStartLocalDCmd(outputStream *output, bool heap_allocated) :
 826   DCmd(output, heap_allocated) {
 827   // do nothing
 828 }
 829 
 830 void JMXStartLocalDCmd::execute(DCmdSource source, TRAPS) {
 831     ResourceMark rm(THREAD);
 832     HandleMark hm(THREAD);
 833 
 834     // Load and initialize the sun.management.Agent class
 835     // invoke startLocalManagementAgent(void) method to start
 836     // the local management server
 837     // throw java.lang.NoSuchMethodError if method doesn't exist
 838 
 839     Handle loader = Handle(THREAD, SystemDictionary::java_system_loader());
 840     Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::sun_management_Agent(), loader, Handle(), true, CHECK);
 841     instanceKlassHandle ik (THREAD, k);
 842 
 843     JavaValue result(T_VOID);
 844     JavaCalls::call_static(&result, ik, vmSymbols::startLocalAgent_name(), vmSymbols::void_method_signature(), CHECK);
 845 }
 846 
 847 void JMXStopRemoteDCmd::execute(DCmdSource source, TRAPS) {
 848     ResourceMark rm(THREAD);
 849     HandleMark hm(THREAD);
 850 
 851     // Load and initialize the sun.management.Agent class
 852     // invoke stopRemoteManagementAgent method to stop the
 853     // management server
 854     // throw java.lang.NoSuchMethodError if method doesn't exist
 855 
 856     Handle loader = Handle(THREAD, SystemDictionary::java_system_loader());
 857     Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::sun_management_Agent(), loader, Handle(), true, CHECK);
 858     instanceKlassHandle ik (THREAD, k);
 859 
 860     JavaValue result(T_VOID);
 861     JavaCalls::call_static(&result, ik, vmSymbols::stopRemoteAgent_name(), vmSymbols::void_method_signature(), CHECK);
 862 }
 863 
 864 JMXStatusDCmd::JMXStatusDCmd(outputStream *output, bool heap_allocated) :
 865   DCmd(output, heap_allocated) {
 866   // do nothing
 867 }
 868 
 869 void JMXStatusDCmd::execute(DCmdSource source, TRAPS) {
 870   ResourceMark rm(THREAD);
 871   HandleMark hm(THREAD);
 872 
 873   // Load and initialize the sun.management.Agent class
 874   // invoke getManagementAgentStatus() method to generate the status info
 875   // throw java.lang.NoSuchMethodError if method doesn't exist
 876 
 877   Handle loader = Handle(THREAD, SystemDictionary::java_system_loader());
 878   Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::sun_management_Agent(), loader, Handle(), true, CHECK);
 879   instanceKlassHandle ik (THREAD, k);
 880 
 881   JavaValue result(T_OBJECT);
 882   JavaCalls::call_static(&result, ik, vmSymbols::getAgentStatus_name(), vmSymbols::void_string_signature(), CHECK);
 883 
 884   jvalue* jv = (jvalue*) result.get_value_addr();
 885   oop str = (oop) jv->l;
 886   if (str != NULL) {
 887       char* out = java_lang_String::as_utf8_string(str);
 888       if (out) {
 889           output()->print_cr("%s", out);
 890           return;
 891       }
 892   }
 893   output()->print_cr("Error obtaining management agent status");
 894 }
 895 
 896 VMDynamicLibrariesDCmd::VMDynamicLibrariesDCmd(outputStream *output, bool heap_allocated) :
 897   DCmd(output, heap_allocated) {
 898   // do nothing
 899 }
 900 
 901 void VMDynamicLibrariesDCmd::execute(DCmdSource source, TRAPS) {
 902   os::print_dll_info(output());
 903   output()->cr();
 904 }
 905 
 906 void CompileQueueDCmd::execute(DCmdSource source, TRAPS) {
 907   VM_PrintCompileQueue printCompileQueueOp(output());
 908   VMThread::execute(&printCompileQueueOp);
 909 }
 910 
 911 void CodeListDCmd::execute(DCmdSource source, TRAPS) {
 912   CodeCache::print_codelist(output());
 913 }
 914 
 915 void CodeCacheDCmd::execute(DCmdSource source, TRAPS) {
 916   CodeCache::print_layout(output());
 917 }
 918 
 919 void CompilerDirectivesPrintDCmd::execute(DCmdSource source, TRAPS) {
 920   DirectivesStack::print(output());
 921 }
 922 
 923 CompilerDirectivesAddDCmd::CompilerDirectivesAddDCmd(outputStream* output, bool heap) :
 924                            DCmdWithParser(output, heap),
 925   _filename("filename","Name of the directives file", "STRING",true) {
 926   _dcmdparser.add_dcmd_argument(&_filename);
 927 }
 928 
 929 void CompilerDirectivesAddDCmd::execute(DCmdSource source, TRAPS) {
 930   DirectivesParser::parse_from_file(_filename.value(), output());
 931 }
 932 
 933 int CompilerDirectivesAddDCmd::num_arguments() {
 934   ResourceMark rm;
 935   CompilerDirectivesAddDCmd* dcmd = new CompilerDirectivesAddDCmd(NULL, false);
 936   if (dcmd != NULL) {
 937     DCmdMark mark(dcmd);
 938     return dcmd->_dcmdparser.num_arguments();
 939   } else {
 940     return 0;
 941   }
 942 }
 943 
 944 void CompilerDirectivesRemoveDCmd::execute(DCmdSource source, TRAPS) {
 945   DirectivesStack::pop(1);
 946 }
 947 
 948 void CompilerDirectivesClearDCmd::execute(DCmdSource source, TRAPS) {
 949   DirectivesStack::clear();
 950 }
 951 #if INCLUDE_SERVICES
 952 ClassHierarchyDCmd::ClassHierarchyDCmd(outputStream* output, bool heap) :
 953                                        DCmdWithParser(output, heap),
 954   _print_interfaces("-i", "Inherited interfaces should be printed.", "BOOLEAN", false, "false"),
 955   _print_subclasses("-s", "If a classname is specified, print its subclasses. "
 956                     "Otherwise only its superclasses are printed.", "BOOLEAN", false, "false"),
 957   _classname("classname", "Name of class whose hierarchy should be printed. "
 958              "If not specified, all class hierarchies are printed.",
 959              "STRING", false) {
 960   _dcmdparser.add_dcmd_option(&_print_interfaces);
 961   _dcmdparser.add_dcmd_option(&_print_subclasses);
 962   _dcmdparser.add_dcmd_argument(&_classname);
 963 }
 964 
 965 void ClassHierarchyDCmd::execute(DCmdSource source, TRAPS) {
 966   VM_PrintClassHierarchy printClassHierarchyOp(output(), _print_interfaces.value(),
 967                                                _print_subclasses.value(), _classname.value());
 968   VMThread::execute(&printClassHierarchyOp);
 969 }
 970 
 971 int ClassHierarchyDCmd::num_arguments() {
 972   ResourceMark rm;
 973   ClassHierarchyDCmd* dcmd = new ClassHierarchyDCmd(NULL, false);
 974   if (dcmd != NULL) {
 975     DCmdMark mark(dcmd);
 976     return dcmd->_dcmdparser.num_arguments();
 977   } else {
 978     return 0;
 979   }
 980 }
 981 
 982 #endif
 983 
 984 class VM_DumpTouchedMethods : public VM_Operation {
 985 private:
 986   outputStream* _out;
 987 public:
 988   VM_DumpTouchedMethods(outputStream* out) {
 989     _out = out;
 990   }
 991 
 992   virtual VMOp_Type type() const { return VMOp_DumpTouchedMethods; }
 993 
 994   virtual void doit() {
 995     Method::print_touched_methods(_out);
 996   }
 997 };
 998 
 999 TouchedMethodsDCmd::TouchedMethodsDCmd(outputStream* output, bool heap) :
1000                                        DCmdWithParser(output, heap)
1001 {}
1002 
1003 void TouchedMethodsDCmd::execute(DCmdSource source, TRAPS) {
1004   if (!UnlockDiagnosticVMOptions) {
1005     output()->print_cr("VM.touched_methods command requires -XX:+UnlockDiagnosticVMOptions");
1006     return;
1007   }
1008   VM_DumpTouchedMethods dumper(output());
1009   VMThread::execute(&dumper);
1010 }
1011 
1012 int TouchedMethodsDCmd::num_arguments() {
1013   return 0;
1014 }