1 /*
   2  * Copyright (c) 2011, 2023, 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 "cds/cds_globals.hpp"
  27 #include "classfile/classLoaderHierarchyDCmd.hpp"
  28 #include "classfile/classLoaderStats.hpp"
  29 #include "classfile/classLoaderDataGraph.hpp"
  30 #include "classfile/javaClasses.hpp"
  31 #include "classfile/systemDictionary.hpp"
  32 #include "classfile/vmClasses.hpp"
  33 #include "code/codeCache.hpp"
  34 #include "compiler/compileBroker.hpp"
  35 #include "compiler/directivesParser.hpp"
  36 #include "gc/shared/gcVMOperations.hpp"
  37 #include "jvm.h"
  38 #include "memory/metaspace/metaspaceDCmd.hpp"
  39 #include "memory/resourceArea.hpp"
  40 #include "memory/universe.hpp"
  41 #include "oops/instanceKlass.hpp"
  42 #include "oops/objArrayOop.inline.hpp"
  43 #include "oops/oop.inline.hpp"
  44 #include "oops/typeArrayOop.inline.hpp"
  45 #include "prims/jvmtiAgentList.hpp"
  46 #include "runtime/fieldDescriptor.inline.hpp"
  47 #include "runtime/flags/jvmFlag.hpp"
  48 #include "runtime/handles.inline.hpp"
  49 #include "runtime/interfaceSupport.inline.hpp"
  50 #include "runtime/javaCalls.hpp"
  51 #include "runtime/jniHandles.hpp"
  52 #include "runtime/os.hpp"
  53 #include "runtime/vmOperations.hpp"
  54 #include "runtime/vm_version.hpp"
  55 #include "services/diagnosticArgument.hpp"
  56 #include "services/diagnosticCommand.hpp"
  57 #include "services/diagnosticFramework.hpp"
  58 #include "services/heapDumper.hpp"
  59 #include "services/management.hpp"
  60 #include "services/nmtDCmd.hpp"
  61 #include "services/writeableFlags.hpp"
  62 #include "utilities/debug.hpp"
  63 #include "utilities/events.hpp"
  64 #include "utilities/formatBuffer.hpp"
  65 #include "utilities/macros.hpp"
  66 #ifdef LINUX
  67 #include "trimCHeapDCmd.hpp"
  68 #include "mallocInfoDcmd.hpp"
  69 #endif
  70 
  71 static void loadAgentModule(TRAPS) {
  72   ResourceMark rm(THREAD);
  73   HandleMark hm(THREAD);
  74 
  75   JavaValue result(T_OBJECT);
  76   Handle h_module_name = java_lang_String::create_from_str("jdk.management.agent", CHECK);
  77   JavaCalls::call_static(&result,
  78                          vmClasses::module_Modules_klass(),
  79                          vmSymbols::loadModule_name(),
  80                          vmSymbols::loadModule_signature(),
  81                          h_module_name,
  82                          THREAD);
  83 }
  84 
  85 void DCmd::register_dcmds(){
  86   // Registration of the diagnostic commands
  87   // First argument specifies which interfaces will export the command
  88   // Second argument specifies if the command is enabled
  89   // Third  argument specifies if the command is hidden
  90   uint32_t full_export = DCmd_Source_Internal | DCmd_Source_AttachAPI
  91                          | DCmd_Source_MBean;
  92   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<HelpDCmd>(full_export, true, false));
  93   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<VersionDCmd>(full_export, true, false));
  94   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<CommandLineDCmd>(full_export, true, false));
  95   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<PrintSystemPropertiesDCmd>(full_export, true, false));
  96   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<PrintVMFlagsDCmd>(full_export, true, false));
  97   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<SetVMFlagDCmd>(full_export, true, false));
  98   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<VMDynamicLibrariesDCmd>(full_export, true, false));
  99   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<VMUptimeDCmd>(full_export, true, false));
 100   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<VMInfoDCmd>(full_export, true, false));
 101   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<SystemGCDCmd>(full_export, true, false));
 102   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<RunFinalizationDCmd>(full_export, true, false));
 103   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<HeapInfoDCmd>(full_export, true, false));
 104   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<FinalizerInfoDCmd>(full_export, true, false));
 105 #if INCLUDE_SERVICES
 106   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<HeapDumpDCmd>(DCmd_Source_Internal | DCmd_Source_AttachAPI, true, false));
 107   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<ClassHistogramDCmd>(full_export, true, false));
 108   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<SystemDictionaryDCmd>(full_export, true, false));
 109   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<ClassHierarchyDCmd>(full_export, true, false));
 110   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<ClassesDCmd>(full_export, true, false));
 111   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<SymboltableDCmd>(full_export, true, false));
 112   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<StringtableDCmd>(full_export, true, false));
 113   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<metaspace::MetaspaceDCmd>(full_export, true, false));
 114   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<PrintClassLayoutDCmd>(full_export, true, false));
 115   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<EventLogDCmd>(full_export, true, false));
 116 #if INCLUDE_JVMTI // Both JVMTI and SERVICES have to be enabled to have this dcmd
 117   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<JVMTIAgentLoadDCmd>(full_export, true, false));
 118 #endif // INCLUDE_JVMTI
 119 #endif // INCLUDE_SERVICES
 120 #if INCLUDE_JVMTI
 121   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<JVMTIDataDumpDCmd>(full_export, true, false));
 122 #endif // INCLUDE_JVMTI
 123   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<ThreadDumpDCmd>(full_export, true, false));
 124   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<ThreadDumpToFileDCmd>(full_export, true, false));
 125   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<ClassLoaderStatsDCmd>(full_export, true, false));
 126   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<ClassLoaderHierarchyDCmd>(full_export, true, false));
 127   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<CompileQueueDCmd>(full_export, true, false));
 128   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<CodeListDCmd>(full_export, true, false));
 129   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<CodeCacheDCmd>(full_export, true, false));
 130 #ifdef LINUX
 131   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<PerfMapDCmd>(full_export, true, false));
 132   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<TrimCLibcHeapDCmd>(full_export, true, false));
 133   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<MallocInfoDcmd>(full_export, true, false));
 134 #endif // LINUX
 135   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<CodeHeapAnalyticsDCmd>(full_export, true, false));
 136 
 137   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<CompilerDirectivesPrintDCmd>(full_export, true, false));
 138   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<CompilerDirectivesAddDCmd>(full_export, true, false));
 139   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<CompilerDirectivesRemoveDCmd>(full_export, true, false));
 140   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<CompilerDirectivesClearDCmd>(full_export, true, false));
 141 
 142   // Enhanced JMX Agent Support
 143   // These commands won't be exported via the DiagnosticCommandMBean until an
 144   // appropriate permission is created for them
 145   uint32_t jmx_agent_export_flags = DCmd_Source_Internal | DCmd_Source_AttachAPI;
 146   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<JMXStartRemoteDCmd>(jmx_agent_export_flags, true,false));
 147   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<JMXStartLocalDCmd>(jmx_agent_export_flags, true,false));
 148   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<JMXStopRemoteDCmd>(jmx_agent_export_flags, true,false));
 149   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<JMXStatusDCmd>(jmx_agent_export_flags, true,false));
 150   // Debug on cmd (only makes sense with JVMTI since the agentlib needs it).
 151 #if INCLUDE_JVMTI
 152   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<DebugOnCmdStartDCmd>(full_export, true, true));
 153 #endif // INCLUDE_JVMTI
 154 
 155 #if INCLUDE_CDS
 156   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<DumpSharedArchiveDCmd>(full_export, true, false));
 157 #endif // INCLUDE_CDS
 158 
 159   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<NMTDCmd>(full_export, true, false));
 160 }
 161 
 162 HelpDCmd::HelpDCmd(outputStream* output, bool heap) : DCmdWithParser(output, heap),
 163   _all("-all", "Show help for all commands", "BOOLEAN", false, "false"),
 164   _cmd("command name", "The name of the command for which we want help",
 165         "STRING", false) {
 166   _dcmdparser.add_dcmd_option(&_all);
 167   _dcmdparser.add_dcmd_argument(&_cmd);
 168 };
 169 
 170 
 171 static int compare_strings(const char** s1, const char** s2) {
 172   return ::strcmp(*s1, *s2);
 173 }
 174 
 175 void HelpDCmd::execute(DCmdSource source, TRAPS) {
 176   if (_all.value()) {
 177     GrowableArray<const char*>* cmd_list = DCmdFactory::DCmd_list(source);
 178     cmd_list->sort(compare_strings);
 179     for (int i = 0; i < cmd_list->length(); i++) {
 180       DCmdFactory* factory = DCmdFactory::factory(source, cmd_list->at(i),
 181                                                   strlen(cmd_list->at(i)));
 182       output()->print_cr("%s%s", factory->name(),
 183                          factory->is_enabled() ? "" : " [disabled]");
 184       output()->print_cr("\t%s", factory->description());
 185       output()->cr();
 186       factory = factory->next();
 187     }
 188   } else if (_cmd.has_value()) {
 189     DCmd* cmd = nullptr;
 190     DCmdFactory* factory = DCmdFactory::factory(source, _cmd.value(),
 191                                                 strlen(_cmd.value()));
 192     if (factory != nullptr) {
 193       output()->print_cr("%s%s", factory->name(),
 194                          factory->is_enabled() ? "" : " [disabled]");
 195       output()->print_cr("%s", factory->description());
 196       output()->print_cr("\nImpact: %s", factory->impact());
 197       output()->cr();
 198       cmd = factory->create_resource_instance(output());
 199       if (cmd != nullptr) {
 200         DCmdMark mark(cmd);
 201         cmd->print_help(factory->name());
 202       }
 203     } else {
 204       output()->print_cr("Help unavailable : '%s' : No such command", _cmd.value());
 205     }
 206   } else {
 207     output()->print_cr("The following commands are available:");
 208     GrowableArray<const char *>* cmd_list = DCmdFactory::DCmd_list(source);
 209     cmd_list->sort(compare_strings);
 210     for (int i = 0; i < cmd_list->length(); i++) {
 211       DCmdFactory* factory = DCmdFactory::factory(source, cmd_list->at(i),
 212                                                   strlen(cmd_list->at(i)));
 213       output()->print_cr("%s%s", factory->name(),
 214                          factory->is_enabled() ? "" : " [disabled]");
 215       factory = factory->_next;
 216     }
 217     output()->print_cr("\nFor more information about a specific command use 'help <command>'.");
 218   }
 219 }
 220 
 221 void VersionDCmd::execute(DCmdSource source, TRAPS) {
 222   output()->print_cr("%s version %s", VM_Version::vm_name(),
 223           VM_Version::vm_release());
 224   JDK_Version jdk_version = JDK_Version::current();
 225   if (jdk_version.patch_version() > 0) {
 226     output()->print_cr("JDK %d.%d.%d.%d", jdk_version.major_version(),
 227             jdk_version.minor_version(), jdk_version.security_version(),
 228             jdk_version.patch_version());
 229   } else {
 230     output()->print_cr("JDK %d.%d.%d", jdk_version.major_version(),
 231             jdk_version.minor_version(), jdk_version.security_version());
 232   }
 233 }
 234 
 235 PrintVMFlagsDCmd::PrintVMFlagsDCmd(outputStream* output, bool heap) :
 236                                    DCmdWithParser(output, heap),
 237   _all("-all", "Print all flags supported by the VM", "BOOLEAN", false, "false") {
 238   _dcmdparser.add_dcmd_option(&_all);
 239 }
 240 
 241 void PrintVMFlagsDCmd::execute(DCmdSource source, TRAPS) {
 242   if (_all.value()) {
 243     JVMFlag::printFlags(output(), true);
 244   } else {
 245     JVMFlag::printSetFlags(output());
 246   }
 247 }
 248 
 249 SetVMFlagDCmd::SetVMFlagDCmd(outputStream* output, bool heap) :
 250                                    DCmdWithParser(output, heap),
 251   _flag("flag name", "The name of the flag we want to set",
 252         "STRING", true),
 253   _value("string value", "The value we want to set", "STRING", false) {
 254   _dcmdparser.add_dcmd_argument(&_flag);
 255   _dcmdparser.add_dcmd_argument(&_value);
 256 }
 257 
 258 void SetVMFlagDCmd::execute(DCmdSource source, TRAPS) {
 259   const char* val = nullptr;
 260   if (_value.value() != nullptr) {
 261     val = _value.value();
 262   }
 263 
 264   FormatBuffer<80> err_msg("%s", "");
 265   int ret = WriteableFlags::set_flag(_flag.value(), val, JVMFlagOrigin::MANAGEMENT, err_msg);
 266 
 267   if (ret != JVMFlag::SUCCESS) {
 268     output()->print_cr("%s", err_msg.buffer());
 269   }
 270 }
 271 
 272 void JVMTIDataDumpDCmd::execute(DCmdSource source, TRAPS) {
 273   if (JvmtiExport::should_post_data_dump()) {
 274     JvmtiExport::post_data_dump();
 275   }
 276 }
 277 
 278 #if INCLUDE_SERVICES
 279 #if INCLUDE_JVMTI
 280 JVMTIAgentLoadDCmd::JVMTIAgentLoadDCmd(outputStream* output, bool heap) :
 281                                        DCmdWithParser(output, heap),
 282   _libpath("library path", "Absolute path of the JVMTI agent to load.",
 283            "STRING", true),
 284   _option("agent option", "Option string to pass the agent.", "STRING", false) {
 285   _dcmdparser.add_dcmd_argument(&_libpath);
 286   _dcmdparser.add_dcmd_argument(&_option);
 287 }
 288 
 289 void JVMTIAgentLoadDCmd::execute(DCmdSource source, TRAPS) {
 290 
 291   if (_libpath.value() == nullptr) {
 292     output()->print_cr("JVMTI.agent_load dcmd needs library path.");
 293     return;
 294   }
 295 
 296   char *suffix = strrchr(_libpath.value(), '.');
 297   bool is_java_agent = (suffix != nullptr) && (strncmp(".jar", suffix, 4) == 0);
 298 
 299   if (is_java_agent) {
 300     if (_option.value() == nullptr) {
 301       JvmtiAgentList::load_agent("instrument", "false", _libpath.value(), output());
 302     } else {
 303       size_t opt_len = strlen(_libpath.value()) + strlen(_option.value()) + 2;
 304       if (opt_len > 4096) {
 305         output()->print_cr("JVMTI agent attach failed: Options is too long.");
 306         return;
 307       }
 308 
 309       char *opt = (char *)os::malloc(opt_len, mtInternal);
 310       if (opt == nullptr) {
 311         output()->print_cr("JVMTI agent attach failed: "
 312                            "Could not allocate " SIZE_FORMAT " bytes for argument.",
 313                            opt_len);
 314         return;
 315       }
 316 
 317       jio_snprintf(opt, opt_len, "%s=%s", _libpath.value(), _option.value());
 318       JvmtiAgentList::load_agent("instrument", "false", opt, output());
 319 
 320       os::free(opt);
 321     }
 322   } else {
 323     JvmtiAgentList::load_agent(_libpath.value(), "true", _option.value(), output());
 324   }
 325 }
 326 
 327 #endif // INCLUDE_JVMTI
 328 #endif // INCLUDE_SERVICES
 329 
 330 void PrintSystemPropertiesDCmd::execute(DCmdSource source, TRAPS) {
 331   // load VMSupport
 332   Symbol* klass = vmSymbols::jdk_internal_vm_VMSupport();
 333   Klass* k = SystemDictionary::resolve_or_fail(klass, true, CHECK);
 334   InstanceKlass* ik = InstanceKlass::cast(k);
 335   if (ik->should_be_initialized()) {
 336     ik->initialize(THREAD);
 337   }
 338   if (HAS_PENDING_EXCEPTION) {
 339     java_lang_Throwable::print(PENDING_EXCEPTION, output());
 340     output()->cr();
 341     CLEAR_PENDING_EXCEPTION;
 342     return;
 343   }
 344 
 345   // invoke the serializePropertiesToByteArray method
 346   JavaValue result(T_OBJECT);
 347   JavaCallArguments args;
 348 
 349   Symbol* signature = vmSymbols::void_byte_array_signature();
 350   JavaCalls::call_static(&result,
 351                          ik,
 352                          vmSymbols::serializePropertiesToByteArray_name(),
 353                          signature,
 354                          &args,
 355                          THREAD);
 356   if (HAS_PENDING_EXCEPTION) {
 357     java_lang_Throwable::print(PENDING_EXCEPTION, output());
 358     output()->cr();
 359     CLEAR_PENDING_EXCEPTION;
 360     return;
 361   }
 362 
 363   // The result should be a [B
 364   oop res = result.get_oop();
 365   assert(res->is_typeArray(), "just checking");
 366   assert(TypeArrayKlass::cast(res->klass())->element_type() == T_BYTE, "just checking");
 367 
 368   // copy the bytes to the output stream
 369   typeArrayOop ba = typeArrayOop(res);
 370   jbyte* addr = typeArrayOop(res)->byte_at_addr(0);
 371   output()->print_raw((const char*)addr, ba->length());
 372 }
 373 
 374 VMUptimeDCmd::VMUptimeDCmd(outputStream* output, bool heap) :
 375                            DCmdWithParser(output, heap),
 376   _date("-date", "Add a prefix with current date", "BOOLEAN", false, "false") {
 377   _dcmdparser.add_dcmd_option(&_date);
 378 }
 379 
 380 void VMUptimeDCmd::execute(DCmdSource source, TRAPS) {
 381   if (_date.value()) {
 382     output()->date_stamp(true, "", ": ");
 383   }
 384   output()->time_stamp().update_to(tty->time_stamp().ticks());
 385   output()->stamp();
 386   output()->print_cr(" s");
 387 }
 388 
 389 void VMInfoDCmd::execute(DCmdSource source, TRAPS) {
 390   VMError::print_vm_info(_output);
 391 }
 392 
 393 void SystemGCDCmd::execute(DCmdSource source, TRAPS) {
 394   Universe::heap()->collect(GCCause::_dcmd_gc_run);
 395 }
 396 
 397 void RunFinalizationDCmd::execute(DCmdSource source, TRAPS) {
 398   Klass* k = vmClasses::System_klass();
 399   JavaValue result(T_VOID);
 400   JavaCalls::call_static(&result, k,
 401                          vmSymbols::run_finalization_name(),
 402                          vmSymbols::void_method_signature(), CHECK);
 403 }
 404 
 405 void HeapInfoDCmd::execute(DCmdSource source, TRAPS) {
 406   MutexLocker hl(THREAD, Heap_lock);
 407   Universe::heap()->print_on(output());
 408 }
 409 
 410 void FinalizerInfoDCmd::execute(DCmdSource source, TRAPS) {
 411   ResourceMark rm(THREAD);
 412 
 413   if (!InstanceKlass::is_finalization_enabled()) {
 414     output()->print_cr("Finalization is disabled");
 415     return;
 416   }
 417 
 418   Klass* k = SystemDictionary::resolve_or_fail(
 419     vmSymbols::finalizer_histogram_klass(), true, CHECK);
 420 
 421   JavaValue result(T_ARRAY);
 422 
 423   // We are calling lang.ref.FinalizerHistogram.getFinalizerHistogram() method
 424   // and expect it to return array of FinalizerHistogramEntry as Object[]
 425 
 426   JavaCalls::call_static(&result, k,
 427                          vmSymbols::get_finalizer_histogram_name(),
 428                          vmSymbols::void_finalizer_histogram_entry_array_signature(), CHECK);
 429 
 430   objArrayOop result_oop = (objArrayOop) result.get_oop();
 431   if (result_oop->length() == 0) {
 432     output()->print_cr("No instances waiting for finalization found");
 433     return;
 434   }
 435 
 436   oop foop = result_oop->obj_at(0);
 437   InstanceKlass* ik = InstanceKlass::cast(foop->klass());
 438 
 439   fieldDescriptor count_fd, name_fd;
 440 
 441   Klass* count_res = ik->find_field(
 442     vmSymbols::finalizer_histogram_entry_count_field(), vmSymbols::int_signature(), &count_fd);
 443 
 444   Klass* name_res = ik->find_field(
 445     vmSymbols::finalizer_histogram_entry_name_field(), vmSymbols::string_signature(), &name_fd);
 446 
 447   assert(count_res != nullptr && name_res != nullptr, "Unexpected layout of FinalizerHistogramEntry");
 448 
 449   output()->print_cr("Unreachable instances waiting for finalization");
 450   output()->print_cr("#instances  class name");
 451   output()->print_cr("-----------------------");
 452 
 453   for (int i = 0; i < result_oop->length(); ++i) {
 454     oop element_oop = result_oop->obj_at(i);
 455     oop str_oop = element_oop->obj_field(name_fd.offset());
 456     char *name = java_lang_String::as_utf8_string(str_oop);
 457     int count = element_oop->int_field(count_fd.offset());
 458     output()->print_cr("%10d  %s", count, name);
 459   }
 460 }
 461 
 462 #if INCLUDE_SERVICES // Heap dumping/inspection supported
 463 HeapDumpDCmd::HeapDumpDCmd(outputStream* output, bool heap) :
 464                            DCmdWithParser(output, heap),
 465   _filename("filename","Name of the dump file", "STRING",true),
 466   _all("-all", "Dump all objects, including unreachable objects",
 467        "BOOLEAN", false, "false"),
 468   _gzip("-gz", "If specified, the heap dump is written in gzipped format "
 469                "using the given compression level. 1 (recommended) is the fastest, "
 470                "9 the strongest compression.", "INT", false, "1"),
 471   _overwrite("-overwrite", "If specified, the dump file will be overwritten if it exists",
 472            "BOOLEAN", false, "false") {
 473   _dcmdparser.add_dcmd_option(&_all);
 474   _dcmdparser.add_dcmd_argument(&_filename);
 475   _dcmdparser.add_dcmd_option(&_gzip);
 476   _dcmdparser.add_dcmd_option(&_overwrite);
 477 }
 478 
 479 void HeapDumpDCmd::execute(DCmdSource source, TRAPS) {
 480   jlong level = -1; // -1 means no compression.
 481 
 482   if (_gzip.is_set()) {
 483     level = _gzip.value();
 484 
 485     if (level < 1 || level > 9) {
 486       output()->print_cr("Compression level out of range (1-9): " JLONG_FORMAT, level);
 487       return;
 488     }
 489   }
 490 
 491   // Request a full GC before heap dump if _all is false
 492   // This helps reduces the amount of unreachable objects in the dump
 493   // and makes it easier to browse.
 494   HeapDumper dumper(!_all.value() /* request GC if _all is false*/);
 495   dumper.dump(_filename.value(), output(), (int) level, _overwrite.value());
 496 }
 497 
 498 ClassHistogramDCmd::ClassHistogramDCmd(outputStream* output, bool heap) :
 499                                        DCmdWithParser(output, heap),
 500   _all("-all", "Inspect all objects, including unreachable objects",
 501        "BOOLEAN", false, "false"),
 502   _parallel_thread_num("-parallel",
 503        "Number of parallel threads to use for heap inspection. "
 504        "0 (the default) means let the VM determine the number of threads to use. "
 505        "1 means use one thread (disable parallelism). "
 506        "For any other value the VM will try to use the specified number of "
 507        "threads, but might use fewer.",
 508        "INT", false, "0") {
 509   _dcmdparser.add_dcmd_option(&_all);
 510   _dcmdparser.add_dcmd_option(&_parallel_thread_num);
 511 }
 512 
 513 void ClassHistogramDCmd::execute(DCmdSource source, TRAPS) {
 514   jlong num = _parallel_thread_num.value();
 515   if (num < 0) {
 516     output()->print_cr("Parallel thread number out of range (>=0): " JLONG_FORMAT, num);
 517     return;
 518   }
 519   uint parallel_thread_num = num == 0
 520       ? MAX2<uint>(1, (uint)os::initial_active_processor_count() * 3 / 8)
 521       : num;
 522   VM_GC_HeapInspection heapop(output(),
 523                               !_all.value(), /* request full gc if false */
 524                               parallel_thread_num);
 525   VMThread::execute(&heapop);
 526 }
 527 
 528 #endif // INCLUDE_SERVICES
 529 
 530 ThreadDumpDCmd::ThreadDumpDCmd(outputStream* output, bool heap) :
 531                                DCmdWithParser(output, heap),
 532   _locks("-l", "print java.util.concurrent locks", "BOOLEAN", false, "false"),
 533   _extended("-e", "print extended thread information", "BOOLEAN", false, "false") {
 534   _dcmdparser.add_dcmd_option(&_locks);
 535   _dcmdparser.add_dcmd_option(&_extended);
 536 }
 537 
 538 void ThreadDumpDCmd::execute(DCmdSource source, TRAPS) {
 539   // thread stacks and JNI global handles
 540   VM_PrintThreads op1(output(), _locks.value(), _extended.value(), true /* print JNI handle info */);
 541   VMThread::execute(&op1);
 542 
 543   // Deadlock detection
 544   VM_FindDeadlocks op2(output());
 545   VMThread::execute(&op2);
 546 }
 547 
 548 // Enhanced JMX Agent support
 549 
 550 JMXStartRemoteDCmd::JMXStartRemoteDCmd(outputStream *output, bool heap_allocated) :
 551 
 552   DCmdWithParser(output, heap_allocated),
 553 
 554   _config_file
 555   ("config.file",
 556    "set com.sun.management.config.file", "STRING", false),
 557 
 558   _jmxremote_host
 559   ("jmxremote.host",
 560    "set com.sun.management.jmxremote.host", "STRING", false),
 561 
 562   _jmxremote_port
 563   ("jmxremote.port",
 564    "set com.sun.management.jmxremote.port", "STRING", false),
 565 
 566   _jmxremote_rmi_port
 567   ("jmxremote.rmi.port",
 568    "set com.sun.management.jmxremote.rmi.port", "STRING", false),
 569 
 570   _jmxremote_ssl
 571   ("jmxremote.ssl",
 572    "set com.sun.management.jmxremote.ssl", "STRING", false),
 573 
 574   _jmxremote_registry_ssl
 575   ("jmxremote.registry.ssl",
 576    "set com.sun.management.jmxremote.registry.ssl", "STRING", false),
 577 
 578   _jmxremote_authenticate
 579   ("jmxremote.authenticate",
 580    "set com.sun.management.jmxremote.authenticate", "STRING", false),
 581 
 582   _jmxremote_password_file
 583   ("jmxremote.password.file",
 584    "set com.sun.management.jmxremote.password.file", "STRING", false),
 585 
 586   _jmxremote_access_file
 587   ("jmxremote.access.file",
 588    "set com.sun.management.jmxremote.access.file", "STRING", false),
 589 
 590   _jmxremote_login_config
 591   ("jmxremote.login.config",
 592    "set com.sun.management.jmxremote.login.config", "STRING", false),
 593 
 594   _jmxremote_ssl_enabled_cipher_suites
 595   ("jmxremote.ssl.enabled.cipher.suites",
 596    "set com.sun.management.jmxremote.ssl.enabled.cipher.suite", "STRING", false),
 597 
 598   _jmxremote_ssl_enabled_protocols
 599   ("jmxremote.ssl.enabled.protocols",
 600    "set com.sun.management.jmxremote.ssl.enabled.protocols", "STRING", false),
 601 
 602   _jmxremote_ssl_need_client_auth
 603   ("jmxremote.ssl.need.client.auth",
 604    "set com.sun.management.jmxremote.need.client.auth", "STRING", false),
 605 
 606   _jmxremote_ssl_config_file
 607   ("jmxremote.ssl.config.file",
 608    "set com.sun.management.jmxremote.ssl.config.file", "STRING", false),
 609 
 610 // JDP Protocol support
 611   _jmxremote_autodiscovery
 612   ("jmxremote.autodiscovery",
 613    "set com.sun.management.jmxremote.autodiscovery", "STRING", false),
 614 
 615    _jdp_port
 616   ("jdp.port",
 617    "set com.sun.management.jdp.port", "INT", false),
 618 
 619    _jdp_address
 620   ("jdp.address",
 621    "set com.sun.management.jdp.address", "STRING", false),
 622 
 623    _jdp_source_addr
 624   ("jdp.source_addr",
 625    "set com.sun.management.jdp.source_addr", "STRING", false),
 626 
 627    _jdp_ttl
 628   ("jdp.ttl",
 629    "set com.sun.management.jdp.ttl", "INT", false),
 630 
 631    _jdp_pause
 632   ("jdp.pause",
 633    "set com.sun.management.jdp.pause", "INT", false),
 634 
 635    _jdp_name
 636   ("jdp.name",
 637    "set com.sun.management.jdp.name", "STRING", false)
 638 
 639   {
 640     _dcmdparser.add_dcmd_option(&_config_file);
 641     _dcmdparser.add_dcmd_option(&_jmxremote_host);
 642     _dcmdparser.add_dcmd_option(&_jmxremote_port);
 643     _dcmdparser.add_dcmd_option(&_jmxremote_rmi_port);
 644     _dcmdparser.add_dcmd_option(&_jmxremote_ssl);
 645     _dcmdparser.add_dcmd_option(&_jmxremote_registry_ssl);
 646     _dcmdparser.add_dcmd_option(&_jmxremote_authenticate);
 647     _dcmdparser.add_dcmd_option(&_jmxremote_password_file);
 648     _dcmdparser.add_dcmd_option(&_jmxremote_access_file);
 649     _dcmdparser.add_dcmd_option(&_jmxremote_login_config);
 650     _dcmdparser.add_dcmd_option(&_jmxremote_ssl_enabled_cipher_suites);
 651     _dcmdparser.add_dcmd_option(&_jmxremote_ssl_enabled_protocols);
 652     _dcmdparser.add_dcmd_option(&_jmxremote_ssl_need_client_auth);
 653     _dcmdparser.add_dcmd_option(&_jmxremote_ssl_config_file);
 654     _dcmdparser.add_dcmd_option(&_jmxremote_autodiscovery);
 655     _dcmdparser.add_dcmd_option(&_jdp_port);
 656     _dcmdparser.add_dcmd_option(&_jdp_address);
 657     _dcmdparser.add_dcmd_option(&_jdp_source_addr);
 658     _dcmdparser.add_dcmd_option(&_jdp_ttl);
 659     _dcmdparser.add_dcmd_option(&_jdp_pause);
 660     _dcmdparser.add_dcmd_option(&_jdp_name);
 661 }
 662 
 663 void JMXStartRemoteDCmd::execute(DCmdSource source, TRAPS) {
 664     ResourceMark rm(THREAD);
 665     HandleMark hm(THREAD);
 666 
 667     // Load and initialize the jdk.internal.agent.Agent class
 668     // invoke startRemoteManagementAgent(string) method to start
 669     // the remote management server.
 670     // throw java.lang.NoSuchMethodError if the method doesn't exist
 671 
 672     loadAgentModule(CHECK);
 673     Handle loader = Handle(THREAD, SystemDictionary::java_system_loader());
 674     Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::jdk_internal_agent_Agent(), loader, Handle(), true, CHECK);
 675 
 676     JavaValue result(T_VOID);
 677 
 678     // Pass all command line arguments to java as key=value,...
 679     // All checks are done on java side
 680 
 681     int len = 0;
 682     stringStream options;
 683     char comma[2] = {0,0};
 684 
 685     // Leave default values on Agent.class side and pass only
 686     // arguments explicitly set by user. All arguments passed
 687     // to jcmd override properties with the same name set by
 688     // command line with -D or by managmenent.properties
 689     // file.
 690 #define PUT_OPTION(a) \
 691     do { \
 692         if ( (a).is_set() ){ \
 693             if ( *((a).type()) == 'I' ) { \
 694                 options.print("%scom.sun.management.%s=" JLONG_FORMAT, comma, (a).name(), (jlong)((a).value())); \
 695             } else { \
 696                 options.print("%scom.sun.management.%s=%s", comma, (a).name(), (char*)((a).value())); \
 697             } \
 698             comma[0] = ','; \
 699         }\
 700     } while(0);
 701 
 702 
 703     PUT_OPTION(_config_file);
 704     PUT_OPTION(_jmxremote_host);
 705     PUT_OPTION(_jmxremote_port);
 706     PUT_OPTION(_jmxremote_rmi_port);
 707     PUT_OPTION(_jmxremote_ssl);
 708     PUT_OPTION(_jmxremote_registry_ssl);
 709     PUT_OPTION(_jmxremote_authenticate);
 710     PUT_OPTION(_jmxremote_password_file);
 711     PUT_OPTION(_jmxremote_access_file);
 712     PUT_OPTION(_jmxremote_login_config);
 713     PUT_OPTION(_jmxremote_ssl_enabled_cipher_suites);
 714     PUT_OPTION(_jmxremote_ssl_enabled_protocols);
 715     PUT_OPTION(_jmxremote_ssl_need_client_auth);
 716     PUT_OPTION(_jmxremote_ssl_config_file);
 717     PUT_OPTION(_jmxremote_autodiscovery);
 718     PUT_OPTION(_jdp_port);
 719     PUT_OPTION(_jdp_address);
 720     PUT_OPTION(_jdp_source_addr);
 721     PUT_OPTION(_jdp_ttl);
 722     PUT_OPTION(_jdp_pause);
 723     PUT_OPTION(_jdp_name);
 724 
 725 #undef PUT_OPTION
 726 
 727     Handle str = java_lang_String::create_from_str(options.as_string(), CHECK);
 728     JavaCalls::call_static(&result, k, vmSymbols::startRemoteAgent_name(), vmSymbols::string_void_signature(), str, CHECK);
 729 }
 730 
 731 JMXStartLocalDCmd::JMXStartLocalDCmd(outputStream *output, bool heap_allocated) :
 732   DCmd(output, heap_allocated) {
 733   // do nothing
 734 }
 735 
 736 void JMXStartLocalDCmd::execute(DCmdSource source, TRAPS) {
 737     ResourceMark rm(THREAD);
 738     HandleMark hm(THREAD);
 739 
 740     // Load and initialize the jdk.internal.agent.Agent class
 741     // invoke startLocalManagementAgent(void) method to start
 742     // the local management server
 743     // throw java.lang.NoSuchMethodError if method doesn't exist
 744 
 745     loadAgentModule(CHECK);
 746     Handle loader = Handle(THREAD, SystemDictionary::java_system_loader());
 747     Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::jdk_internal_agent_Agent(), loader, Handle(), true, CHECK);
 748 
 749     JavaValue result(T_VOID);
 750     JavaCalls::call_static(&result, k, vmSymbols::startLocalAgent_name(), vmSymbols::void_method_signature(), CHECK);
 751 }
 752 
 753 void JMXStopRemoteDCmd::execute(DCmdSource source, TRAPS) {
 754     ResourceMark rm(THREAD);
 755     HandleMark hm(THREAD);
 756 
 757     // Load and initialize the jdk.internal.agent.Agent class
 758     // invoke stopRemoteManagementAgent method to stop the
 759     // management server
 760     // throw java.lang.NoSuchMethodError if method doesn't exist
 761 
 762     loadAgentModule(CHECK);
 763     Handle loader = Handle(THREAD, SystemDictionary::java_system_loader());
 764     Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::jdk_internal_agent_Agent(), loader, Handle(), true, CHECK);
 765 
 766     JavaValue result(T_VOID);
 767     JavaCalls::call_static(&result, k, vmSymbols::stopRemoteAgent_name(), vmSymbols::void_method_signature(), CHECK);
 768 }
 769 
 770 JMXStatusDCmd::JMXStatusDCmd(outputStream *output, bool heap_allocated) :
 771   DCmd(output, heap_allocated) {
 772   // do nothing
 773 }
 774 
 775 void JMXStatusDCmd::execute(DCmdSource source, TRAPS) {
 776   ResourceMark rm(THREAD);
 777   HandleMark hm(THREAD);
 778 
 779   // Load and initialize the jdk.internal.agent.Agent class
 780   // invoke getManagementAgentStatus() method to generate the status info
 781   // throw java.lang.NoSuchMethodError if method doesn't exist
 782 
 783   loadAgentModule(CHECK);
 784   Handle loader = Handle(THREAD, SystemDictionary::java_system_loader());
 785   Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::jdk_internal_agent_Agent(), loader, Handle(), true, CHECK);
 786 
 787   JavaValue result(T_OBJECT);
 788   JavaCalls::call_static(&result, k, vmSymbols::getAgentStatus_name(), vmSymbols::void_string_signature(), CHECK);
 789 
 790   jvalue* jv = (jvalue*) result.get_value_addr();
 791   oop str = cast_to_oop(jv->l);
 792   if (str != nullptr) {
 793       char* out = java_lang_String::as_utf8_string(str);
 794       if (out) {
 795           // Avoid using print_cr() because length maybe longer than O_BUFLEN
 796           output()->print_raw_cr(out);
 797           return;
 798       }
 799   }
 800   output()->print_cr("Error obtaining management agent status");
 801 }
 802 
 803 VMDynamicLibrariesDCmd::VMDynamicLibrariesDCmd(outputStream *output, bool heap_allocated) :
 804   DCmd(output, heap_allocated) {
 805   // do nothing
 806 }
 807 
 808 void VMDynamicLibrariesDCmd::execute(DCmdSource source, TRAPS) {
 809   os::print_dll_info(output());
 810   output()->cr();
 811 }
 812 
 813 void CompileQueueDCmd::execute(DCmdSource source, TRAPS) {
 814   VM_PrintCompileQueue printCompileQueueOp(output());
 815   VMThread::execute(&printCompileQueueOp);
 816 }
 817 
 818 void CodeListDCmd::execute(DCmdSource source, TRAPS) {
 819   CodeCache::print_codelist(output());
 820 }
 821 
 822 void CodeCacheDCmd::execute(DCmdSource source, TRAPS) {
 823   CodeCache::print_layout(output());
 824 }
 825 
 826 #ifdef LINUX
 827 void PerfMapDCmd::execute(DCmdSource source, TRAPS) {
 828   CodeCache::write_perf_map();
 829 }
 830 #endif // LINUX
 831 
 832 //---<  BEGIN  >--- CodeHeap State Analytics.
 833 CodeHeapAnalyticsDCmd::CodeHeapAnalyticsDCmd(outputStream* output, bool heap) :
 834                                              DCmdWithParser(output, heap),
 835   _function("function", "Function to be performed (aggregate, UsedSpace, FreeSpace, MethodCount, MethodSpace, MethodAge, MethodNames, discard", "STRING", false, "all"),
 836   _granularity("granularity", "Detail level - smaller value -> more detail", "INT", false, "4096") {
 837   _dcmdparser.add_dcmd_argument(&_function);
 838   _dcmdparser.add_dcmd_argument(&_granularity);
 839 }
 840 
 841 void CodeHeapAnalyticsDCmd::execute(DCmdSource source, TRAPS) {
 842   jlong granularity = _granularity.value();
 843   if (granularity < 1) {
 844     Exceptions::fthrow(THREAD_AND_LOCATION, vmSymbols::java_lang_IllegalArgumentException(),
 845                        "Invalid granularity value " JLONG_FORMAT  ". Should be positive.\n", granularity);
 846     return;
 847   }
 848 
 849   CompileBroker::print_heapinfo(output(), _function.value(), granularity);
 850 }
 851 //---<  END  >--- CodeHeap State Analytics.
 852 
 853 EventLogDCmd::EventLogDCmd(outputStream* output, bool heap) :
 854   DCmdWithParser(output, heap),
 855   _log("log", "Name of log to be printed. If omitted, all logs are printed.", "STRING", false, nullptr),
 856   _max("max", "Maximum number of events to be printed (newest first). If omitted, all events are printed.", "STRING", false, nullptr)
 857 {
 858   _dcmdparser.add_dcmd_option(&_log);
 859   _dcmdparser.add_dcmd_option(&_max);
 860 }
 861 
 862 void EventLogDCmd::execute(DCmdSource source, TRAPS) {
 863   const char* max_value = _max.value();
 864   long max = -1;
 865   if (max_value != nullptr) {
 866     char* endptr = nullptr;
 867     max = ::strtol(max_value, &endptr, 10);
 868     if (max == 0 && max_value == endptr) {
 869       output()->print_cr("Invalid max option: \"%s\".", max_value);
 870       return;
 871     }
 872   }
 873   const char* log_name = _log.value();
 874   if (log_name != nullptr) {
 875     Events::print_one(output(), log_name, max);
 876   } else {
 877     Events::print_all(output(), max);
 878   }
 879 }
 880 
 881 void CompilerDirectivesPrintDCmd::execute(DCmdSource source, TRAPS) {
 882   DirectivesStack::print(output());
 883 }
 884 
 885 CompilerDirectivesAddDCmd::CompilerDirectivesAddDCmd(outputStream* output, bool heap) :
 886                            DCmdWithParser(output, heap),
 887   _filename("filename","Name of the directives file", "STRING",true) {
 888   _dcmdparser.add_dcmd_argument(&_filename);
 889 }
 890 
 891 void CompilerDirectivesAddDCmd::execute(DCmdSource source, TRAPS) {
 892   DirectivesParser::parse_from_file(_filename.value(), output(), true);
 893 }
 894 
 895 void CompilerDirectivesRemoveDCmd::execute(DCmdSource source, TRAPS) {
 896   DirectivesStack::pop(1);
 897 }
 898 
 899 void CompilerDirectivesClearDCmd::execute(DCmdSource source, TRAPS) {
 900   DirectivesStack::clear();
 901 }
 902 #if INCLUDE_SERVICES
 903 ClassHierarchyDCmd::ClassHierarchyDCmd(outputStream* output, bool heap) :
 904                                        DCmdWithParser(output, heap),
 905   _print_interfaces("-i", "Inherited interfaces should be printed.", "BOOLEAN", false, "false"),
 906   _print_subclasses("-s", "If a classname is specified, print its subclasses "
 907                     "in addition to its superclasses. Without this option only the "
 908                     "superclasses will be printed.", "BOOLEAN", false, "false"),
 909   _classname("classname", "Name of class whose hierarchy should be printed. "
 910              "If not specified, all class hierarchies are printed.",
 911              "STRING", false) {
 912   _dcmdparser.add_dcmd_option(&_print_interfaces);
 913   _dcmdparser.add_dcmd_option(&_print_subclasses);
 914   _dcmdparser.add_dcmd_argument(&_classname);
 915 }
 916 
 917 void ClassHierarchyDCmd::execute(DCmdSource source, TRAPS) {
 918   VM_PrintClassHierarchy printClassHierarchyOp(output(), _print_interfaces.value(),
 919                                                _print_subclasses.value(), _classname.value());
 920   VMThread::execute(&printClassHierarchyOp);
 921 }
 922 
 923 PrintClassLayoutDCmd::PrintClassLayoutDCmd(outputStream* output, bool heap) :
 924                                        DCmdWithParser(output, heap),
 925   _classname("classname", "Name of class whose layout should be printed. ",
 926              "STRING", true) {
 927   _dcmdparser.add_dcmd_argument(&_classname);
 928 }
 929 
 930 void PrintClassLayoutDCmd::execute(DCmdSource source, TRAPS) {
 931   VM_PrintClassLayout printClassLayoutOp(output(), _classname.value());
 932   VMThread::execute(&printClassLayoutOp);
 933 }
 934 
 935 int PrintClassLayoutDCmd::num_arguments() {
 936   ResourceMark rm;
 937   PrintClassLayoutDCmd* dcmd = new PrintClassLayoutDCmd(nullptr, false);
 938   if (dcmd != nullptr) {
 939     DCmdMark mark(dcmd);
 940     return dcmd->_dcmdparser.num_arguments();
 941   } else {
 942     return 0;
 943   }
 944 }
 945 
 946 #endif // INCLUDE_SERVICES
 947 
 948 ClassesDCmd::ClassesDCmd(outputStream* output, bool heap) :
 949                                      DCmdWithParser(output, heap),
 950   _verbose("-verbose",
 951            "Dump the detailed content of a Java class. "
 952            "Some classes are annotated with flags: "
 953            "F = has, or inherits, a non-empty finalize method, "
 954            "f = has final method, "
 955            "W = methods rewritten, "
 956            "C = marked with @Contended annotation, "
 957            "R = has been redefined, "
 958            "S = is shared class",
 959            "BOOLEAN", false, "false") {
 960   _dcmdparser.add_dcmd_option(&_verbose);
 961 }
 962 
 963 class VM_PrintClasses : public VM_Operation {
 964 private:
 965   outputStream* _out;
 966   bool _verbose;
 967 public:
 968   VM_PrintClasses(outputStream* out, bool verbose) : _out(out), _verbose(verbose) {}
 969 
 970   virtual VMOp_Type type() const { return VMOp_PrintClasses; }
 971 
 972   virtual void doit() {
 973     PrintClassClosure closure(_out, _verbose);
 974     ClassLoaderDataGraph::classes_do(&closure);
 975   }
 976 };
 977 
 978 void ClassesDCmd::execute(DCmdSource source, TRAPS) {
 979   VM_PrintClasses vmop(output(), _verbose.is_set());
 980   VMThread::execute(&vmop);
 981 }
 982 
 983 #if INCLUDE_CDS
 984 DumpSharedArchiveDCmd::DumpSharedArchiveDCmd(outputStream* output, bool heap) :
 985                                      DCmdWithParser(output, heap),
 986   _suboption("subcmd", "static_dump | dynamic_dump", "STRING", true),
 987   _filename("filename", "Name of shared archive to be dumped", "STRING", false)
 988 {
 989   _dcmdparser.add_dcmd_argument(&_suboption);
 990   _dcmdparser.add_dcmd_argument(&_filename);
 991 }
 992 
 993 void DumpSharedArchiveDCmd::execute(DCmdSource source, TRAPS) {
 994   jboolean is_static;
 995   const char* scmd = _suboption.value();
 996   const char* file = _filename.value();
 997 
 998   if (strcmp(scmd, "static_dump") == 0) {
 999     is_static = JNI_TRUE;
1000     output()->print("Static dump: ");
1001   } else if (strcmp(scmd, "dynamic_dump") == 0) {
1002     is_static = JNI_FALSE;
1003     output()->print("Dynamic dump: ");
1004     if (!UseSharedSpaces) {
1005       output()->print_cr("Dynamic dump is unsupported when base CDS archive is not loaded");
1006       return;
1007     }
1008     if (!RecordDynamicDumpInfo) {
1009       output()->print_cr("Dump dynamic should run with -XX:+RecordDynamicDumpInfo");
1010       return;
1011     }
1012   } else {
1013     output()->print_cr("Invalid command for VM.cds, valid input is static_dump or dynamic_dump");
1014     return;
1015   }
1016 
1017   // call CDS.dumpSharedArchive
1018   Handle fileh;
1019   if (file != nullptr) {
1020     fileh =  java_lang_String::create_from_str(_filename.value(), CHECK);
1021   }
1022   Symbol* cds_name  = vmSymbols::jdk_internal_misc_CDS();
1023   Klass*  cds_klass = SystemDictionary::resolve_or_fail(cds_name, true /*throw error*/,  CHECK);
1024   JavaValue result(T_OBJECT);
1025   JavaCallArguments args;
1026   args.push_int(is_static);
1027   args.push_oop(fileh);
1028   JavaCalls::call_static(&result,
1029                          cds_klass,
1030                          vmSymbols::dumpSharedArchive(),
1031                          vmSymbols::dumpSharedArchive_signature(),
1032                          &args, CHECK);
1033   if (!HAS_PENDING_EXCEPTION) {
1034     assert(result.get_type() == T_OBJECT, "Sanity check");
1035     // result contains the archive name
1036     char* archive_name = java_lang_String::as_utf8_string(result.get_oop());
1037     output()->print_cr("%s", archive_name);
1038   }
1039 }
1040 #endif // INCLUDE_CDS
1041 
1042 #if INCLUDE_JVMTI
1043 extern "C" typedef char const* (JNICALL *debugInit_startDebuggingViaCommandPtr)(JNIEnv* env, jthread thread, char const** transport_name,
1044                                                                                 char const** address, jboolean* first_start);
1045 static debugInit_startDebuggingViaCommandPtr dvc_start_ptr = nullptr;
1046 
1047 void DebugOnCmdStartDCmd::execute(DCmdSource source, TRAPS) {
1048   char const* transport = nullptr;
1049   char const* addr = nullptr;
1050   jboolean is_first_start = JNI_FALSE;
1051   JavaThread* thread = THREAD;
1052   jthread jt = JNIHandles::make_local(thread->threadObj());
1053   ThreadToNativeFromVM ttn(thread);
1054   const char *error = "Could not find jdwp agent.";
1055 
1056   if (!dvc_start_ptr) {
1057     JvmtiAgentList::Iterator it = JvmtiAgentList::agents();
1058     while (it.has_next()) {
1059       JvmtiAgent* agent = it.next();
1060       if ((strcmp("jdwp", agent->name()) == 0) && (dvc_start_ptr == nullptr)) {
1061         char const* func = "debugInit_startDebuggingViaCommand";
1062         dvc_start_ptr = (debugInit_startDebuggingViaCommandPtr) os::find_agent_function(agent, false, &func, 1);
1063       }
1064     }
1065   }
1066 
1067   if (dvc_start_ptr) {
1068     error = dvc_start_ptr(thread->jni_environment(), jt, &transport, &addr, &is_first_start);
1069   }
1070 
1071   if (error != nullptr) {
1072     output()->print_cr("Debugging has not been started: %s", error);
1073   } else {
1074     output()->print_cr(is_first_start ? "Debugging has been started." : "Debugging is already active.");
1075     output()->print_cr("Transport : %s", transport ? transport : "#unknown");
1076     output()->print_cr("Address : %s", addr ? addr : "#unknown");
1077   }
1078 }
1079 #endif // INCLUDE_JVMTI
1080 
1081 ThreadDumpToFileDCmd::ThreadDumpToFileDCmd(outputStream* output, bool heap) :
1082                                            DCmdWithParser(output, heap),
1083   _overwrite("-overwrite", "May overwrite existing file", "BOOLEAN", false, "false"),
1084   _format("-format", "Output format (\"plain\" or \"json\")", "STRING", false, "plain"),
1085   _filepath("filepath", "The file path to the output file", "STRING", true) {
1086   _dcmdparser.add_dcmd_option(&_overwrite);
1087   _dcmdparser.add_dcmd_option(&_format);
1088   _dcmdparser.add_dcmd_argument(&_filepath);
1089 }
1090 
1091 void ThreadDumpToFileDCmd::execute(DCmdSource source, TRAPS) {
1092   bool json = (_format.value() != nullptr) && (strcmp(_format.value(), "json") == 0);
1093   char* path = _filepath.value();
1094   bool overwrite = _overwrite.value();
1095   Symbol* name = (json) ? vmSymbols::dumpThreadsToJson_name() : vmSymbols::dumpThreads_name();
1096   dumpToFile(name, vmSymbols::string_bool_byte_array_signature(), path, overwrite, CHECK);
1097 }
1098 
1099 void ThreadDumpToFileDCmd::dumpToFile(Symbol* name, Symbol* signature, const char* path, bool overwrite, TRAPS) {
1100   ResourceMark rm(THREAD);
1101   HandleMark hm(THREAD);
1102 
1103   Handle h_path = java_lang_String::create_from_str(path, CHECK);
1104 
1105   Symbol* sym = vmSymbols::jdk_internal_vm_ThreadDumper();
1106   Klass* k = SystemDictionary::resolve_or_fail(sym, true, CHECK);
1107   InstanceKlass* ik = InstanceKlass::cast(k);
1108   if (HAS_PENDING_EXCEPTION) {
1109     java_lang_Throwable::print(PENDING_EXCEPTION, output());
1110     output()->cr();
1111     CLEAR_PENDING_EXCEPTION;
1112     return;
1113   }
1114 
1115   // invoke the ThreadDump method to dump to file
1116   JavaValue result(T_OBJECT);
1117   JavaCallArguments args;
1118   args.push_oop(h_path);
1119   args.push_int(overwrite ? JNI_TRUE : JNI_FALSE);
1120   JavaCalls::call_static(&result,
1121                          k,
1122                          name,
1123                          signature,
1124                          &args,
1125                          THREAD);
1126   if (HAS_PENDING_EXCEPTION) {
1127     java_lang_Throwable::print(PENDING_EXCEPTION, output());
1128     output()->cr();
1129     CLEAR_PENDING_EXCEPTION;
1130     return;
1131   }
1132 
1133   // check that result is byte array
1134   oop res = cast_to_oop(result.get_jobject());
1135   assert(res->is_typeArray(), "just checking");
1136   assert(TypeArrayKlass::cast(res->klass())->element_type() == T_BYTE, "just checking");
1137 
1138   // copy the bytes to the output stream
1139   typeArrayOop ba = typeArrayOop(res);
1140   jbyte* addr = typeArrayOop(res)->byte_at_addr(0);
1141   output()->print_raw((const char*)addr, ba->length());
1142 }