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