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