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