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