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