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