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