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