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 "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       size_t opt_len = strlen(_libpath.value()) + strlen(_option.value()) + 2;
 283       if (opt_len > 4096) {
 284         output()->print_cr("JVMTI agent attach failed: Options is too long.");
 285         return;
 286       }
 287 
 288       char *opt = (char *)os::malloc(opt_len, mtInternal);
 289       if (opt == NULL) {
 290         output()->print_cr("JVMTI agent attach failed: "
 291                            "Could not allocate %zu bytes for argument.",
 292                            opt_len);
 293         return;
 294       }
 295 
 296       jio_snprintf(opt, opt_len, "%s=%s", _libpath.value(), _option.value());
 297       JvmtiExport::load_agent_library("instrument", "false", opt, output());
 298 
 299       os::free(opt);
 300     }
 301   } else {
 302     JvmtiExport::load_agent_library(_libpath.value(), "true",
 303                                     _option.value(), output());
 304   }
 305 }
 306 
 307 int JVMTIAgentLoadDCmd::num_arguments() {
 308   ResourceMark rm;
 309   JVMTIAgentLoadDCmd* dcmd = new JVMTIAgentLoadDCmd(NULL, false);
 310   if (dcmd != NULL) {
 311     DCmdMark mark(dcmd);
 312     return dcmd->_dcmdparser.num_arguments();
 313   } else {
 314     return 0;
 315   }
 316 }
 317 
 318 void PrintSystemPropertiesDCmd::execute(DCmdSource source, TRAPS) {
 319   // load sun.misc.VMSupport
 320   Symbol* klass = vmSymbols::sun_misc_VMSupport();
 321   Klass* k = SystemDictionary::resolve_or_fail(klass, true, CHECK);
 322   instanceKlassHandle ik (THREAD, k);
 323   if (ik->should_be_initialized()) {
 324     ik->initialize(THREAD);
 325   }
 326   if (HAS_PENDING_EXCEPTION) {
 327     java_lang_Throwable::print(PENDING_EXCEPTION, output());
 328     output()->cr();
 329     CLEAR_PENDING_EXCEPTION;
 330     return;
 331   }
 332 
 333   // invoke the serializePropertiesToByteArray method
 334   JavaValue result(T_OBJECT);
 335   JavaCallArguments args;
 336 
 337   Symbol* signature = vmSymbols::serializePropertiesToByteArray_signature();
 338   JavaCalls::call_static(&result,
 339                          ik,
 340                          vmSymbols::serializePropertiesToByteArray_name(),
 341                          signature,
 342                          &args,
 343                          THREAD);
 344   if (HAS_PENDING_EXCEPTION) {
 345     java_lang_Throwable::print(PENDING_EXCEPTION, output());
 346     output()->cr();
 347     CLEAR_PENDING_EXCEPTION;
 348     return;
 349   }
 350 
 351   // The result should be a [B
 352   oop res = (oop)result.get_jobject();
 353   assert(res->is_typeArray(), "just checking");
 354   assert(TypeArrayKlass::cast(res->klass())->element_type() == T_BYTE, "just checking");
 355 
 356   // copy the bytes to the output stream
 357   typeArrayOop ba = typeArrayOop(res);
 358   jbyte* addr = typeArrayOop(res)->byte_at_addr(0);
 359   output()->print_raw((const char*)addr, ba->length());
 360 }
 361 
 362 VMUptimeDCmd::VMUptimeDCmd(outputStream* output, bool heap) :
 363                            DCmdWithParser(output, heap),
 364   _date("-date", "Add a prefix with current date", "BOOLEAN", false, "false") {
 365   _dcmdparser.add_dcmd_option(&_date);
 366 }
 367 
 368 void VMUptimeDCmd::execute(DCmdSource source, TRAPS) {
 369   if (_date.value()) {
 370     output()->date_stamp(true, "", ": ");
 371   }
 372   output()->time_stamp().update_to(tty->time_stamp().ticks());
 373   output()->stamp();
 374   output()->print_cr(" s");
 375 }
 376 
 377 int VMUptimeDCmd::num_arguments() {
 378   ResourceMark rm;
 379   VMUptimeDCmd* dcmd = new VMUptimeDCmd(NULL, false);
 380   if (dcmd != NULL) {
 381     DCmdMark mark(dcmd);
 382     return dcmd->_dcmdparser.num_arguments();
 383   } else {
 384     return 0;
 385   }
 386 }
 387 
 388 void VMInfoDCmd::execute(DCmdSource source, TRAPS) {
 389   VMError::print_vm_info(_output);
 390 }
 391 
 392 void SystemGCDCmd::execute(DCmdSource source, TRAPS) {
 393   if (!DisableExplicitGC) {
 394     Universe::heap()->collect(GCCause::_dcmd_gc_run);
 395   } else {
 396     output()->print_cr("Explicit GC is disabled, no GC has been performed.");
 397   }
 398 }
 399 
 400 void RunFinalizationDCmd::execute(DCmdSource source, TRAPS) {
 401   Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_System(),
 402                                                  true, CHECK);
 403   instanceKlassHandle klass(THREAD, k);
 404   JavaValue result(T_VOID);
 405   JavaCalls::call_static(&result, klass,
 406                          vmSymbols::run_finalization_name(),
 407                          vmSymbols::void_method_signature(), CHECK);
 408 }
 409 
 410 void HeapInfoDCmd::execute(DCmdSource source, TRAPS) {
 411   Universe::heap()->print_on(output());
 412 }
 413 
 414 void FinalizerInfoDCmd::execute(DCmdSource source, TRAPS) {
 415   ResourceMark rm;
 416 
 417 
 418   Klass* k = SystemDictionary::resolve_or_null(
 419     vmSymbols::finalizer_histogram_klass(), THREAD);
 420   assert(k != NULL, "FinalizerHistogram class is not accessible");
 421 
 422   instanceKlassHandle klass(THREAD, k);
 423   JavaValue result(T_ARRAY);
 424 
 425   // We are calling lang.ref.FinalizerHistogram.getFinalizerHistogram() method
 426   // and expect it to return array of FinalizerHistogramEntry as Object[]
 427 
 428   JavaCalls::call_static(&result, klass,
 429                          vmSymbols::get_finalizer_histogram_name(),
 430                          vmSymbols::void_finalizer_histogram_entry_array_signature(), CHECK);
 431 
 432   objArrayOop result_oop = (objArrayOop) result.get_jobject();
 433   if (result_oop->length() == 0) {
 434     output()->print_cr("No instances waiting for finalization found");
 435     return;
 436   }
 437 
 438   oop foop = result_oop->obj_at(0);
 439   InstanceKlass* ik = InstanceKlass::cast(foop->klass());
 440 
 441   fieldDescriptor count_fd, name_fd;
 442 
 443   Klass* count_res = ik->find_field(
 444     vmSymbols::finalizer_histogram_entry_count_field(), vmSymbols::int_signature(), &count_fd);
 445 
 446   Klass* name_res = ik->find_field(
 447     vmSymbols::finalizer_histogram_entry_name_field(), vmSymbols::string_signature(), &name_fd);
 448 
 449   assert(count_res != NULL && name_res != NULL, "Unexpected layout of FinalizerHistogramEntry");
 450 
 451   output()->print_cr("Unreachable instances waiting for finalization");
 452   output()->print_cr("#instances  class name");
 453   output()->print_cr("-----------------------");
 454 
 455   for (int i = 0; i < result_oop->length(); ++i) {
 456     oop element_oop = result_oop->obj_at(i);
 457     oop str_oop = element_oop->obj_field(name_fd.offset());
 458     char *name = java_lang_String::as_utf8_string(str_oop);
 459     int count = element_oop->int_field(count_fd.offset());
 460     output()->print_cr("%10d  %s", count, name);
 461   }
 462 }
 463 
 464 #if INCLUDE_SERVICES // Heap dumping/inspection supported
 465 HeapDumpDCmd::HeapDumpDCmd(outputStream* output, bool heap) :
 466                            DCmdWithParser(output, heap),
 467   _filename("filename","Name of the dump file", "STRING",true),
 468   _all("-all", "Dump all objects, including unreachable objects",
 469        "BOOLEAN", false, "false") {
 470   _dcmdparser.add_dcmd_option(&_all);
 471   _dcmdparser.add_dcmd_argument(&_filename);
 472 }
 473 
 474 void HeapDumpDCmd::execute(DCmdSource source, TRAPS) {
 475   // Request a full GC before heap dump if _all is false
 476   // This helps reduces the amount of unreachable objects in the dump
 477   // and makes it easier to browse.
 478   HeapDumper dumper(!_all.value() /* request GC if _all is false*/);
 479   int res = dumper.dump(_filename.value());
 480   if (res == 0) {
 481     output()->print_cr("Heap dump file created");
 482   } else {
 483     // heap dump failed
 484     ResourceMark rm;
 485     char* error = dumper.error_as_C_string();
 486     if (error == NULL) {
 487       output()->print_cr("Dump failed - reason unknown");
 488     } else {
 489       output()->print_cr("%s", error);
 490     }
 491   }
 492 }
 493 
 494 int HeapDumpDCmd::num_arguments() {
 495   ResourceMark rm;
 496   HeapDumpDCmd* dcmd = new HeapDumpDCmd(NULL, false);
 497   if (dcmd != NULL) {
 498     DCmdMark mark(dcmd);
 499     return dcmd->_dcmdparser.num_arguments();
 500   } else {
 501     return 0;
 502   }
 503 }
 504 
 505 ClassHistogramDCmd::ClassHistogramDCmd(outputStream* output, bool heap) :
 506                                        DCmdWithParser(output, heap),
 507   _all("-all", "Inspect all objects, including unreachable objects",
 508        "BOOLEAN", false, "false") {
 509   _dcmdparser.add_dcmd_option(&_all);
 510 }
 511 
 512 void ClassHistogramDCmd::execute(DCmdSource source, TRAPS) {
 513   VM_GC_HeapInspection heapop(output(),
 514                               !_all.value() /* request full gc if false */);
 515   VMThread::execute(&heapop);
 516 }
 517 
 518 int ClassHistogramDCmd::num_arguments() {
 519   ResourceMark rm;
 520   ClassHistogramDCmd* dcmd = new ClassHistogramDCmd(NULL, false);
 521   if (dcmd != NULL) {
 522     DCmdMark mark(dcmd);
 523     return dcmd->_dcmdparser.num_arguments();
 524   } else {
 525     return 0;
 526   }
 527 }
 528 
 529 #define DEFAULT_COLUMNS "InstBytes,KlassBytes,CpAll,annotations,MethodCount,Bytecodes,MethodAll,ROAll,RWAll,Total"
 530 ClassStatsDCmd::ClassStatsDCmd(outputStream* output, bool heap) :
 531                                        DCmdWithParser(output, heap),
 532   _csv("-csv", "Print in CSV (comma-separated values) format for spreadsheets",
 533        "BOOLEAN", false, "false"),
 534   _all("-all", "Show all columns",
 535        "BOOLEAN", false, "false"),
 536   _help("-help", "Show meaning of all the columns",
 537        "BOOLEAN", false, "false"),
 538   _columns("columns", "Comma-separated list of all the columns to show. "
 539            "If not specified, the following columns are shown: " DEFAULT_COLUMNS,
 540            "STRING", false) {
 541   _dcmdparser.add_dcmd_option(&_all);
 542   _dcmdparser.add_dcmd_option(&_csv);
 543   _dcmdparser.add_dcmd_option(&_help);
 544   _dcmdparser.add_dcmd_argument(&_columns);
 545 }
 546 
 547 void ClassStatsDCmd::execute(DCmdSource source, TRAPS) {
 548   if (!UnlockDiagnosticVMOptions) {
 549     output()->print_cr("GC.class_stats command requires -XX:+UnlockDiagnosticVMOptions");
 550     return;
 551   }
 552 
 553   VM_GC_HeapInspection heapop(output(),
 554                               true /* request_full_gc */);
 555   heapop.set_csv_format(_csv.value());
 556   heapop.set_print_help(_help.value());
 557   heapop.set_print_class_stats(true);
 558   if (_all.value()) {
 559     if (_columns.has_value()) {
 560       output()->print_cr("Cannot specify -all and individual columns at the same time");
 561       return;
 562     } else {
 563       heapop.set_columns(NULL);
 564     }
 565   } else {
 566     if (_columns.has_value()) {
 567       heapop.set_columns(_columns.value());
 568     } else {
 569       heapop.set_columns(DEFAULT_COLUMNS);
 570     }
 571   }
 572   VMThread::execute(&heapop);
 573 }
 574 
 575 int ClassStatsDCmd::num_arguments() {
 576   ResourceMark rm;
 577   ClassStatsDCmd* dcmd = new ClassStatsDCmd(NULL, false);
 578   if (dcmd != NULL) {
 579     DCmdMark mark(dcmd);
 580     return dcmd->_dcmdparser.num_arguments();
 581   } else {
 582     return 0;
 583   }
 584 }
 585 #endif // INCLUDE_SERVICES
 586 
 587 ThreadDumpDCmd::ThreadDumpDCmd(outputStream* output, bool heap) :
 588                                DCmdWithParser(output, heap),
 589   _locks("-l", "print java.util.concurrent locks", "BOOLEAN", false, "false") {
 590   _dcmdparser.add_dcmd_option(&_locks);
 591 }
 592 
 593 void ThreadDumpDCmd::execute(DCmdSource source, TRAPS) {
 594   // thread stacks
 595   VM_PrintThreads op1(output(), _locks.value());
 596   VMThread::execute(&op1);
 597 
 598   // JNI global handles
 599   VM_PrintJNI op2(output());
 600   VMThread::execute(&op2);
 601 
 602   // Deadlock detection
 603   VM_FindDeadlocks op3(output());
 604   VMThread::execute(&op3);
 605 }
 606 
 607 int ThreadDumpDCmd::num_arguments() {
 608   ResourceMark rm;
 609   ThreadDumpDCmd* dcmd = new ThreadDumpDCmd(NULL, false);
 610   if (dcmd != NULL) {
 611     DCmdMark mark(dcmd);
 612     return dcmd->_dcmdparser.num_arguments();
 613   } else {
 614     return 0;
 615   }
 616 }
 617 
 618 // Enhanced JMX Agent support
 619 
 620 JMXStartRemoteDCmd::JMXStartRemoteDCmd(outputStream *output, bool heap_allocated) :
 621 
 622   DCmdWithParser(output, heap_allocated),
 623 
 624   _config_file
 625   ("config.file",
 626    "set com.sun.management.config.file", "STRING", false),
 627 
 628   _jmxremote_host
 629   ("jmxremote.host",
 630    "set com.sun.management.jmxremote.host", "STRING", false),
 631 
 632   _jmxremote_port
 633   ("jmxremote.port",
 634    "set com.sun.management.jmxremote.port", "STRING", false),
 635 
 636   _jmxremote_rmi_port
 637   ("jmxremote.rmi.port",
 638    "set com.sun.management.jmxremote.rmi.port", "STRING", false),
 639 
 640   _jmxremote_ssl
 641   ("jmxremote.ssl",
 642    "set com.sun.management.jmxremote.ssl", "STRING", false),
 643 
 644   _jmxremote_registry_ssl
 645   ("jmxremote.registry.ssl",
 646    "set com.sun.management.jmxremote.registry.ssl", "STRING", false),
 647 
 648   _jmxremote_authenticate
 649   ("jmxremote.authenticate",
 650    "set com.sun.management.jmxremote.authenticate", "STRING", false),
 651 
 652   _jmxremote_password_file
 653   ("jmxremote.password.file",
 654    "set com.sun.management.jmxremote.password.file", "STRING", false),
 655 
 656   _jmxremote_access_file
 657   ("jmxremote.access.file",
 658    "set com.sun.management.jmxremote.access.file", "STRING", false),
 659 
 660   _jmxremote_login_config
 661   ("jmxremote.login.config",
 662    "set com.sun.management.jmxremote.login.config", "STRING", false),
 663 
 664   _jmxremote_ssl_enabled_cipher_suites
 665   ("jmxremote.ssl.enabled.cipher.suites",
 666    "set com.sun.management.jmxremote.ssl.enabled.cipher.suite", "STRING", false),
 667 
 668   _jmxremote_ssl_enabled_protocols
 669   ("jmxremote.ssl.enabled.protocols",
 670    "set com.sun.management.jmxremote.ssl.enabled.protocols", "STRING", false),
 671 
 672   _jmxremote_ssl_need_client_auth
 673   ("jmxremote.ssl.need.client.auth",
 674    "set com.sun.management.jmxremote.need.client.auth", "STRING", false),
 675 
 676   _jmxremote_ssl_config_file
 677   ("jmxremote.ssl.config.file",
 678    "set com.sun.management.jmxremote.ssl_config_file", "STRING", false),
 679 
 680 // JDP Protocol support
 681   _jmxremote_autodiscovery
 682   ("jmxremote.autodiscovery",
 683    "set com.sun.management.jmxremote.autodiscovery", "STRING", false),
 684 
 685    _jdp_port
 686   ("jdp.port",
 687    "set com.sun.management.jdp.port", "INT", false),
 688 
 689    _jdp_address
 690   ("jdp.address",
 691    "set com.sun.management.jdp.address", "STRING", false),
 692 
 693    _jdp_source_addr
 694   ("jdp.source_addr",
 695    "set com.sun.management.jdp.source_addr", "STRING", false),
 696 
 697    _jdp_ttl
 698   ("jdp.ttl",
 699    "set com.sun.management.jdp.ttl", "INT", false),
 700 
 701    _jdp_pause
 702   ("jdp.pause",
 703    "set com.sun.management.jdp.pause", "INT", false),
 704 
 705    _jdp_name
 706   ("jdp.name",
 707    "set com.sun.management.jdp.name", "STRING", false)
 708 
 709   {
 710     _dcmdparser.add_dcmd_option(&_config_file);
 711     _dcmdparser.add_dcmd_option(&_jmxremote_host);
 712     _dcmdparser.add_dcmd_option(&_jmxremote_port);
 713     _dcmdparser.add_dcmd_option(&_jmxremote_rmi_port);
 714     _dcmdparser.add_dcmd_option(&_jmxremote_ssl);
 715     _dcmdparser.add_dcmd_option(&_jmxremote_registry_ssl);
 716     _dcmdparser.add_dcmd_option(&_jmxremote_authenticate);
 717     _dcmdparser.add_dcmd_option(&_jmxremote_password_file);
 718     _dcmdparser.add_dcmd_option(&_jmxremote_access_file);
 719     _dcmdparser.add_dcmd_option(&_jmxremote_login_config);
 720     _dcmdparser.add_dcmd_option(&_jmxremote_ssl_enabled_cipher_suites);
 721     _dcmdparser.add_dcmd_option(&_jmxremote_ssl_enabled_protocols);
 722     _dcmdparser.add_dcmd_option(&_jmxremote_ssl_need_client_auth);
 723     _dcmdparser.add_dcmd_option(&_jmxremote_ssl_config_file);
 724     _dcmdparser.add_dcmd_option(&_jmxremote_autodiscovery);
 725     _dcmdparser.add_dcmd_option(&_jdp_port);
 726     _dcmdparser.add_dcmd_option(&_jdp_address);
 727     _dcmdparser.add_dcmd_option(&_jdp_source_addr);
 728     _dcmdparser.add_dcmd_option(&_jdp_ttl);
 729     _dcmdparser.add_dcmd_option(&_jdp_pause);
 730     _dcmdparser.add_dcmd_option(&_jdp_name);
 731 }
 732 
 733 
 734 int JMXStartRemoteDCmd::num_arguments() {
 735   ResourceMark rm;
 736   JMXStartRemoteDCmd* dcmd = new JMXStartRemoteDCmd(NULL, false);
 737   if (dcmd != NULL) {
 738     DCmdMark mark(dcmd);
 739     return dcmd->_dcmdparser.num_arguments();
 740   } else {
 741     return 0;
 742   }
 743 }
 744 
 745 
 746 void JMXStartRemoteDCmd::execute(DCmdSource source, TRAPS) {
 747     ResourceMark rm(THREAD);
 748     HandleMark hm(THREAD);
 749 
 750     // Load and initialize the sun.management.Agent class
 751     // invoke startRemoteManagementAgent(string) method to start
 752     // the remote management server.
 753     // throw java.lang.NoSuchMethodError if the method doesn't exist
 754 
 755     Handle loader = Handle(THREAD, SystemDictionary::java_system_loader());
 756     Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::sun_management_Agent(), loader, Handle(), true, CHECK);
 757     instanceKlassHandle ik (THREAD, k);
 758 
 759     JavaValue result(T_VOID);
 760 
 761     // Pass all command line arguments to java as key=value,...
 762     // All checks are done on java side
 763 
 764     int len = 0;
 765     stringStream options;
 766     char comma[2] = {0,0};
 767 
 768     // Leave default values on Agent.class side and pass only
 769     // agruments explicitly set by user. All arguments passed
 770     // to jcmd override properties with the same name set by
 771     // command line with -D or by managmenent.properties
 772     // file.
 773 #define PUT_OPTION(a) \
 774     do { \
 775         if ( (a).is_set() ){ \
 776             if ( *((a).type()) == 'I' ) { \
 777                 options.print("%scom.sun.management.%s=" JLONG_FORMAT, comma, (a).name(), (jlong)((a).value())); \
 778             } else { \
 779                 options.print("%scom.sun.management.%s=%s", comma, (a).name(), (char*)((a).value())); \
 780             } \
 781             comma[0] = ','; \
 782         }\
 783     } while(0);
 784 
 785 
 786     PUT_OPTION(_config_file);
 787     PUT_OPTION(_jmxremote_host);
 788     PUT_OPTION(_jmxremote_port);
 789     PUT_OPTION(_jmxremote_rmi_port);
 790     PUT_OPTION(_jmxremote_ssl);
 791     PUT_OPTION(_jmxremote_registry_ssl);
 792     PUT_OPTION(_jmxremote_authenticate);
 793     PUT_OPTION(_jmxremote_password_file);
 794     PUT_OPTION(_jmxremote_access_file);
 795     PUT_OPTION(_jmxremote_login_config);
 796     PUT_OPTION(_jmxremote_ssl_enabled_cipher_suites);
 797     PUT_OPTION(_jmxremote_ssl_enabled_protocols);
 798     PUT_OPTION(_jmxremote_ssl_need_client_auth);
 799     PUT_OPTION(_jmxremote_ssl_config_file);
 800     PUT_OPTION(_jmxremote_autodiscovery);
 801     PUT_OPTION(_jdp_port);
 802     PUT_OPTION(_jdp_address);
 803     PUT_OPTION(_jdp_source_addr);
 804     PUT_OPTION(_jdp_ttl);
 805     PUT_OPTION(_jdp_pause);
 806     PUT_OPTION(_jdp_name);
 807 
 808 #undef PUT_OPTION
 809 
 810     Handle str = java_lang_String::create_from_str(options.as_string(), CHECK);
 811     JavaCalls::call_static(&result, ik, vmSymbols::startRemoteAgent_name(), vmSymbols::string_void_signature(), str, CHECK);
 812 }
 813 
 814 JMXStartLocalDCmd::JMXStartLocalDCmd(outputStream *output, bool heap_allocated) :
 815   DCmd(output, heap_allocated) {
 816   // do nothing
 817 }
 818 
 819 void JMXStartLocalDCmd::execute(DCmdSource source, TRAPS) {
 820     ResourceMark rm(THREAD);
 821     HandleMark hm(THREAD);
 822 
 823     // Load and initialize the sun.management.Agent class
 824     // invoke startLocalManagementAgent(void) method to start
 825     // the local management server
 826     // throw java.lang.NoSuchMethodError if method doesn't exist
 827 
 828     Handle loader = Handle(THREAD, SystemDictionary::java_system_loader());
 829     Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::sun_management_Agent(), loader, Handle(), true, CHECK);
 830     instanceKlassHandle ik (THREAD, k);
 831 
 832     JavaValue result(T_VOID);
 833     JavaCalls::call_static(&result, ik, vmSymbols::startLocalAgent_name(), vmSymbols::void_method_signature(), CHECK);
 834 }
 835 
 836 void JMXStopRemoteDCmd::execute(DCmdSource source, TRAPS) {
 837     ResourceMark rm(THREAD);
 838     HandleMark hm(THREAD);
 839 
 840     // Load and initialize the sun.management.Agent class
 841     // invoke stopRemoteManagementAgent method to stop the
 842     // management server
 843     // throw java.lang.NoSuchMethodError if method doesn't exist
 844 
 845     Handle loader = Handle(THREAD, SystemDictionary::java_system_loader());
 846     Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::sun_management_Agent(), loader, Handle(), true, CHECK);
 847     instanceKlassHandle ik (THREAD, k);
 848 
 849     JavaValue result(T_VOID);
 850     JavaCalls::call_static(&result, ik, vmSymbols::stopRemoteAgent_name(), vmSymbols::void_method_signature(), CHECK);
 851 }
 852 
 853 JMXStatusDCmd::JMXStatusDCmd(outputStream *output, bool heap_allocated) :
 854   DCmd(output, heap_allocated) {
 855   // do nothing
 856 }
 857 
 858 void JMXStatusDCmd::execute(DCmdSource source, TRAPS) {
 859   ResourceMark rm(THREAD);
 860   HandleMark hm(THREAD);
 861 
 862   // Load and initialize the sun.management.Agent class
 863   // invoke getManagementAgentStatus() method to generate the status info
 864   // throw java.lang.NoSuchMethodError if method doesn't exist
 865 
 866   Handle loader = Handle(THREAD, SystemDictionary::java_system_loader());
 867   Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::sun_management_Agent(), loader, Handle(), true, CHECK);
 868   instanceKlassHandle ik (THREAD, k);
 869 
 870   JavaValue result(T_OBJECT);
 871   JavaCalls::call_static(&result, ik, vmSymbols::getAgentStatus_name(), vmSymbols::void_string_signature(), CHECK);
 872 
 873   jvalue* jv = (jvalue*) result.get_value_addr();
 874   oop str = (oop) jv->l;
 875   if (str != NULL) {
 876       char* out = java_lang_String::as_utf8_string(str);
 877       if (out) {
 878           output()->print_cr("%s", out);
 879           return;
 880       }
 881   }
 882   output()->print_cr("Error obtaining management agent status");
 883 }
 884 
 885 VMDynamicLibrariesDCmd::VMDynamicLibrariesDCmd(outputStream *output, bool heap_allocated) :
 886   DCmd(output, heap_allocated) {
 887   // do nothing
 888 }
 889 
 890 void VMDynamicLibrariesDCmd::execute(DCmdSource source, TRAPS) {
 891   os::print_dll_info(output());
 892   output()->cr();
 893 }
 894 
 895 void CompileQueueDCmd::execute(DCmdSource source, TRAPS) {
 896   VM_PrintCompileQueue printCompileQueueOp(output());
 897   VMThread::execute(&printCompileQueueOp);
 898 }
 899 
 900 void CodeListDCmd::execute(DCmdSource source, TRAPS) {
 901   CodeCache::print_codelist(output());
 902 }
 903 
 904 void CodeCacheDCmd::execute(DCmdSource source, TRAPS) {
 905   CodeCache::print_layout(output());
 906 }
 907 
 908 void CompilerDirectivesPrintDCmd::execute(DCmdSource source, TRAPS) {
 909   DirectivesStack::print(output());
 910 }
 911 
 912 CompilerDirectivesAddDCmd::CompilerDirectivesAddDCmd(outputStream* output, bool heap) :
 913                            DCmdWithParser(output, heap),
 914   _filename("filename","Name of the directives file", "STRING",true) {
 915   _dcmdparser.add_dcmd_argument(&_filename);
 916 }
 917 
 918 void CompilerDirectivesAddDCmd::execute(DCmdSource source, TRAPS) {
 919   DirectivesParser::parse_from_file(_filename.value(), output());
 920 }
 921 
 922 int CompilerDirectivesAddDCmd::num_arguments() {
 923   ResourceMark rm;
 924   CompilerDirectivesAddDCmd* dcmd = new CompilerDirectivesAddDCmd(NULL, false);
 925   if (dcmd != NULL) {
 926     DCmdMark mark(dcmd);
 927     return dcmd->_dcmdparser.num_arguments();
 928   } else {
 929     return 0;
 930   }
 931 }
 932 
 933 void CompilerDirectivesRemoveDCmd::execute(DCmdSource source, TRAPS) {
 934   DirectivesStack::pop(1);
 935 }
 936 
 937 void CompilerDirectivesClearDCmd::execute(DCmdSource source, TRAPS) {
 938   DirectivesStack::clear();
 939 }
 940 #if INCLUDE_SERVICES
 941 ClassHierarchyDCmd::ClassHierarchyDCmd(outputStream* output, bool heap) :
 942                                        DCmdWithParser(output, heap),
 943   _print_interfaces("-i", "Inherited interfaces should be printed.", "BOOLEAN", false, "false"),
 944   _print_subclasses("-s", "If a classname is specified, print its subclasses. "
 945                     "Otherwise only its superclasses are printed.", "BOOLEAN", false, "false"),
 946   _classname("classname", "Name of class whose hierarchy should be printed. "
 947              "If not specified, all class hierarchies are printed.",
 948              "STRING", false) {
 949   _dcmdparser.add_dcmd_option(&_print_interfaces);
 950   _dcmdparser.add_dcmd_option(&_print_subclasses);
 951   _dcmdparser.add_dcmd_argument(&_classname);
 952 }
 953 
 954 void ClassHierarchyDCmd::execute(DCmdSource source, TRAPS) {
 955   VM_PrintClassHierarchy printClassHierarchyOp(output(), _print_interfaces.value(),
 956                                                _print_subclasses.value(), _classname.value());
 957   VMThread::execute(&printClassHierarchyOp);
 958 }
 959 
 960 int ClassHierarchyDCmd::num_arguments() {
 961   ResourceMark rm;
 962   ClassHierarchyDCmd* dcmd = new ClassHierarchyDCmd(NULL, false);
 963   if (dcmd != NULL) {
 964     DCmdMark mark(dcmd);
 965     return dcmd->_dcmdparser.num_arguments();
 966   } else {
 967     return 0;
 968   }
 969 }
 970 
 971 #endif
 972 
 973 class VM_DumpTouchedMethods : public VM_Operation {
 974 private:
 975   outputStream* _out;
 976 public:
 977   VM_DumpTouchedMethods(outputStream* out) {
 978     _out = out;
 979   }
 980 
 981   virtual VMOp_Type type() const { return VMOp_DumpTouchedMethods; }
 982 
 983   virtual void doit() {
 984     Method::print_touched_methods(_out);
 985   }
 986 };
 987 
 988 TouchedMethodsDCmd::TouchedMethodsDCmd(outputStream* output, bool heap) :
 989                                        DCmdWithParser(output, heap)
 990 {}
 991 
 992 void TouchedMethodsDCmd::execute(DCmdSource source, TRAPS) {
 993   if (!UnlockDiagnosticVMOptions) {
 994     output()->print_cr("VM.touched_methods command requires -XX:+UnlockDiagnosticVMOptions");
 995     return;
 996   }
 997   VM_DumpTouchedMethods dumper(output());
 998   VMThread::execute(&dumper);
 999 }
1000 
1001 int TouchedMethodsDCmd::num_arguments() {
1002   return 0;
1003 }