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