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