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