1 /*
2 * Copyright (c) 2020, 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. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25 package jdk.internal.vm;
26
27 import java.io.BufferedWriter;
28 import java.io.ByteArrayOutputStream;
29 import java.io.IOException;
30 import java.io.OutputStream;
31 import java.io.OutputStreamWriter;
32 import java.io.UncheckedIOException;
33 import java.io.Writer;
34 import java.nio.charset.StandardCharsets;
35 import java.nio.file.FileAlreadyExistsException;
36 import java.nio.file.Files;
37 import java.nio.file.OpenOption;
38 import java.nio.file.Path;
39 import java.nio.file.StandardOpenOption;
40 import java.time.Instant;
41 import java.util.ArrayDeque;
42 import java.util.Arrays;
43 import java.util.Deque;
44 import java.util.Iterator;
45 import java.util.List;
46 import java.util.Objects;
47
48 /**
49 * Thread dump support.
50 *
51 * This class defines static methods to support the Thread.dump_to_file diagnostic command
52 * and the HotSpotDiagnosticMXBean.dumpThreads API. It defines methods to generate a
53 * thread dump to a file or byte array in plain text or JSON format.
54 */
55 public class ThreadDumper {
56 private ThreadDumper() { }
57
58 // the maximum byte array to return when generating the thread dump to a byte array
59 private static final int MAX_BYTE_ARRAY_SIZE = 16_000;
60
61 /**
62 * Generate a thread dump in plain text format to a file or byte array, UTF-8 encoded.
63 * This method is invoked by the VM for the Thread.dump_to_file diagnostic command.
64 *
65 * @param file the file path to the file, null or "-" to return a byte array
66 * @param okayToOverwrite true to overwrite an existing file
67 * @param ignore not used
68 * @return the UTF-8 encoded thread dump or message to return to the tool user
69 */
70 public static byte[] dumpThreads(String file, boolean okayToOverwrite, boolean ignore) {
71 if (file == null || file.equals("-")) {
72 return dumpThreadsToByteArray(false, false, MAX_BYTE_ARRAY_SIZE);
73 } else {
74 return dumpThreadsToFile(file, okayToOverwrite, false, false);
75 }
76 }
77
78 /**
79 * Generate a thread dump in JSON format to a file or byte array, UTF-8 encoded.
80 * This method is invoked by the VM for the Thread.dump_to_file diagnostic command.
81 *
82 * @param file the file path to the file, null or "-" to return a byte array
83 * @param okayToOverwrite true to overwrite an existing file
84 * @return the UTF-8 encoded thread dump or message to return to the tool user
85 */
86 public static byte[] dumpThreadsToJson(String file, boolean okayToOverwrite, boolean prettyPrint) {
87 if (file == null || file.equals("-")) {
88 return dumpThreadsToByteArray(true, prettyPrint, MAX_BYTE_ARRAY_SIZE);
89 } else {
90 return dumpThreadsToFile(file, okayToOverwrite, true, prettyPrint);
91 }
92 }
93
94 /**
95 * Generate a thread dump in plain text or JSON format to a byte array, UTF-8 encoded.
96 * This method is the implementation of the Thread.dump_to_file diagnostic command
97 * when a file path is not specified. It returns the thread dump and/or message to
98 * send to the tool user.
99 */
100 private static byte[] dumpThreadsToByteArray(boolean json, boolean prettyPrint, int maxSize) {
101 var out = new BoundedByteArrayOutputStream(maxSize);
102 try (out; var writer = new TextWriter(out)) {
103 if (json) {
104 dumpThreadsToJson(writer, prettyPrint);
105 } else {
106 dumpThreads(writer);
107 }
108 } catch (Exception ex) {
109 if (ex instanceof UncheckedIOException ioe) {
110 ex = ioe.getCause();
111 }
112 String reply = String.format("Failed: %s%n", ex);
113 return reply.getBytes(StandardCharsets.UTF_8);
114 }
115 return out.toByteArray();
116 }
117
118 /**
119 * Generate a thread dump in plain text or JSON format to the given file, UTF-8 encoded.
120 * This method is the implementation of the Thread.dump_to_file diagnostic command.
121 * It returns the thread dump and/or message to send to the tool user.
122 */
123 private static byte[] dumpThreadsToFile(String file,
124 boolean okayToOverwrite,
125 boolean json,
126 boolean prettyPrint) {
127 Path path = Path.of(file).toAbsolutePath();
128 OpenOption[] options = (okayToOverwrite)
129 ? new OpenOption[0]
130 : new OpenOption[] { StandardOpenOption.CREATE_NEW };
131 String reply;
132 try (OutputStream out = Files.newOutputStream(path, options)) {
133 try (var writer = new TextWriter(out)) {
134 if (json) {
135 dumpThreadsToJson(writer, prettyPrint);
136 } else {
137 dumpThreads(writer);
138 }
139 reply = String.format("Created %s%n", path);
140 } catch (UncheckedIOException e) {
141 reply = String.format("Failed: %s%n", e.getCause());
142 }
143 } catch (FileAlreadyExistsException _) {
144 reply = String.format("%s exists, use -overwrite to overwrite%n", path);
145 } catch (Exception ex) {
146 reply = String.format("Failed: %s%n", ex);
147 }
148 return reply.getBytes(StandardCharsets.UTF_8);
149 }
150
151 /**
152 * Generate a thread dump in plain text format to the given output stream, UTF-8
153 * encoded. This method is invoked by HotSpotDiagnosticMXBean.dumpThreads.
154 * @throws IOException if an I/O error occurs
155 */
156 public static void dumpThreads(OutputStream out) throws IOException {
157 var writer = new TextWriter(out);
158 try {
159 dumpThreads(writer);
160 writer.flush();
161 } catch (UncheckedIOException e) {
162 IOException ioe = e.getCause();
163 throw ioe;
164 }
165 }
166
167 /**
168 * Generate a thread dump in plain text format to the given text stream.
169 * @throws UncheckedIOException if an I/O error occurs
170 */
171 private static void dumpThreads(TextWriter writer) {
172 writer.println(processId());
173 writer.println(Instant.now());
174 writer.println(Runtime.version());
175 writer.println();
176 dumpThreads(ThreadContainers.root(), writer);
177 }
178
179 private static void dumpThreads(ThreadContainer container, TextWriter writer) {
180 container.threads().forEach(t -> dumpThread(t, writer));
181 container.children().forEach(c -> dumpThreads(c, writer));
182 }
183
184 private static boolean dumpThread(Thread thread, TextWriter writer) {
185 ThreadSnapshot snapshot = ThreadSnapshot.of(thread);
186 if (snapshot == null) {
187 return false; // thread not alive
188 }
189 Instant now = Instant.now();
190 Thread.State state = snapshot.threadState();
191 writer.println("#" + thread.threadId() + " \"" + escape(snapshot.threadName())
192 + "\" " + (thread.isVirtual() ? "virtual " : "")
193 + decorateObject(thread)
194 + " " + state
195 + " cpuTime=" + snapshot.cpuTime()
196 + " " + now);
197 StackTraceElement[] stackTrace = snapshot.stackTrace();
198 int depth = 0;
199 while (depth < stackTrace.length) {
200 writer.print(" at ");
201 writer.println(stackTrace[depth]);
202 snapshot.ownedMonitorsAt(depth).forEach(o -> {
203 if (o != null) {
204 writer.println(" - locked " + decorateObject(o));
205 } else {
206 writer.println(" - lock is eliminated");
207 }
208 });
209
210 // if parkBlocker set, or blocked/waiting on monitor, then print after top frame
211 if (depth == 0) {
212 // park blocker
213 Object parkBlocker = snapshot.parkBlocker();
214 if (parkBlocker != null) {
215 String suffix = (snapshot.parkBlockerOwner() instanceof Thread owner)
216 ? ", owner #" + owner.threadId()
217 : "";
218 writer.println(" - parking to wait for " + decorateObject(parkBlocker) + suffix);
219 }
220
221 // blocked on monitor enter or Object.wait
222 if (state == Thread.State.BLOCKED && snapshot.blockedOn() instanceof Object obj) {
223 writer.println(" - waiting to lock " + decorateObject(obj));
224 } else if ((state == Thread.State.WAITING || state == Thread.State.TIMED_WAITING)
225 && snapshot.waitingOn() instanceof Object obj) {
226 writer.println(" - waiting on " + decorateObject(obj));
227 }
228 }
229
230 depth++;
231 }
232 writer.println();
233 return true;
234 }
235
236 /**
237 * Returns the identity string for the given object in a form suitable for the plain
238 * text format thread dump.
239 */
240 private static String decorateObject(Object obj) {
241 return "<" + Objects.toIdentityString(obj) + ">";
242 }
243
244 /**
245 * Generate a thread dump in JSON format to the given output stream, UTF-8 encoded.
246 * This method is invoked by HotSpotDiagnosticMXBean.dumpThreads.
247 * @throws IOException if an I/O error occurs
248 */
249 public static void dumpThreadsToJson(OutputStream out) throws IOException {
250 var writer = new TextWriter(out);
251 try {
252 dumpThreadsToJson(writer, /*prettyPrint*/true);
253 writer.flush();
254 } catch (UncheckedIOException e) {
255 IOException ioe = e.getCause();
256 throw ioe;
257 }
258 }
259
260 /**
261 * JSON is schema-less and the thread dump format will evolve over time.
262 * {@code HotSpotDiagnosticMXBean.dumpThreads} links to a JSON file that documents
263 * the latest/current format. A system property can be used to generate the thread
264 * dump in older formats if necessary.
265 */
266 private static class JsonFormat {
267 private static final String JSON_FORMAT_VERSION_PROP =
268 "com.sun.management.HotSpotDiagnosticMXBean.dumpThreads.format";
269 static final int JSON_FORMAT_V1 = 1;
270 static final int JSON_FORMAT_V2 = 2;
271 private static final int JSON_FORMAT_LATEST = JSON_FORMAT_V2;
272 private static final int JSON_FORMAT;
273 static {
274 int ver = Integer.getInteger(JSON_FORMAT_VERSION_PROP, JSON_FORMAT_LATEST);
275 JSON_FORMAT = Math.clamp(ver, JSON_FORMAT_V1, JSON_FORMAT_LATEST);
276 }
277
278 static int formatVersion() {
279 return JSON_FORMAT;
280 }
281 }
282
283 /**
284 * Generate a thread dump to the given text stream in JSON format.
285 * @throws UncheckedIOException if an I/O error occurs
286 */
287 private static void dumpThreadsToJson(TextWriter textWriter, boolean prettyPrint) {
288 int format = JsonFormat.formatVersion();
289 boolean generateLongsAsString = (format == JsonFormat.JSON_FORMAT_V1);
290 var jsonWriter = new JsonWriter(textWriter, prettyPrint, generateLongsAsString);
291 jsonWriter.startObject(); // top-level object
292 jsonWriter.startObject("threadDump");
293 if (format > JsonFormat.JSON_FORMAT_V1) {
294 jsonWriter.writeProperty("formatVersion", format);
295 }
296
297 jsonWriter.writeLongProperty("processId", processId());
298 jsonWriter.writeProperty("time", Instant.now());
299 jsonWriter.writeProperty("runtimeVersion", Runtime.version());
300
301 jsonWriter.startArray("threadContainers");
302 dumpThreads(ThreadContainers.root(), jsonWriter);
303 jsonWriter.endArray();
304
305 jsonWriter.endObject(); // threadDump
306
307 jsonWriter.endObject(); // end of top-level object
308 }
309
310 /**
311 * Write a thread container to the given JSON writer.
312 * @throws UncheckedIOException if an I/O error occurs
313 */
314 private static void dumpThreads(ThreadContainer container, JsonWriter jsonWriter) {
315 jsonWriter.startObject();
316 jsonWriter.writeProperty("container", container);
317 jsonWriter.writeProperty("parent", container.parent());
318
319 Thread owner = container.owner();
320 if (owner != null) {
321 jsonWriter.writeLongProperty("owner", owner.threadId());
322 } else {
323 jsonWriter.writeProperty("owner", null); // owner is not optional
324 }
325
326 long threadCount = 0;
327 jsonWriter.startArray("threads");
328 Iterator<Thread> threads = container.threads().iterator();
329 while (threads.hasNext()) {
330 Thread thread = threads.next();
331 if (dumpThread(thread, jsonWriter)) {
332 threadCount++;
333 }
334 }
335 jsonWriter.endArray(); // threads
336
337 // thread count
338 if (!ThreadContainers.trackAllThreads()) {
339 threadCount = Long.max(threadCount, container.threadCount());
340 }
341 jsonWriter.writeLongProperty("threadCount", threadCount);
342
343 jsonWriter.endObject();
344
345 // the children of the thread container follow
346 container.children().forEach(c -> dumpThreads(c, jsonWriter));
347 }
348
349 /**
350 * Write a thread to the given JSON writer.
351 * @return true if the thread dump was written, false otherwise
352 * @throws UncheckedIOException if an I/O error occurs
353 */
354 private static boolean dumpThread(Thread thread, JsonWriter jsonWriter) {
355 Instant now = Instant.now();
356 ThreadSnapshot snapshot = ThreadSnapshot.of(thread);
357 if (snapshot == null) {
358 return false; // thread not alive
359 }
360 Thread.State state = snapshot.threadState();
361 StackTraceElement[] stackTrace = snapshot.stackTrace();
362
363 jsonWriter.startObject();
364 jsonWriter.writeLongProperty("tid", thread.threadId());
365 jsonWriter.writeProperty("time", now);
366 if (thread.isVirtual()) {
367 jsonWriter.writeProperty("virtual", Boolean.TRUE);
368 }
369 jsonWriter.writeProperty("name", snapshot.threadName());
370 jsonWriter.writeProperty("threadObj", Objects.toIdentityString(thread));
371 jsonWriter.writeProperty("state", state);
372 if (snapshot.cpuTime() != -1L) {
373 jsonWriter.writeLongProperty("cpuTime", snapshot.cpuTime());
374 }
375
376 // park blocker
377 Object parkBlocker = snapshot.parkBlocker();
378 if (parkBlocker != null) {
379 // parkBlocker is an object to allow for exclusiveOwnerThread in the future
380 jsonWriter.startObject("parkBlocker");
381 jsonWriter.writeProperty("object", Objects.toIdentityString(parkBlocker));
382 if (snapshot.parkBlockerOwner() instanceof Thread owner) {
383 jsonWriter.writeLongProperty("owner", owner.threadId());
384 }
385 jsonWriter.endObject();
386 }
387
388 // blocked on monitor enter or Object.wait
389 if (state == Thread.State.BLOCKED && snapshot.blockedOn() instanceof Object obj) {
390 jsonWriter.writeProperty("blockedOn", Objects.toIdentityString(obj));
391 } else if ((state == Thread.State.WAITING || state == Thread.State.TIMED_WAITING)
392 && snapshot.waitingOn() instanceof Object obj) {
393 jsonWriter.writeProperty("waitingOn", Objects.toIdentityString(obj));
394 }
395
396 // stack trace
397 jsonWriter.startArray("stack");
398 Arrays.stream(stackTrace).forEach(jsonWriter::writeProperty);
399 jsonWriter.endArray();
400
401 // monitors owned, skip if none
402 if (snapshot.ownsMonitors()) {
403 jsonWriter.startArray("monitorsOwned");
404 int depth = 0;
405 while (depth < stackTrace.length) {
406 List<Object> objs = snapshot.ownedMonitorsAt(depth).toList();
407 if (!objs.isEmpty()) {
408 jsonWriter.startObject();
409 jsonWriter.writeProperty("depth", depth);
410 jsonWriter.startArray("locks");
411 snapshot.ownedMonitorsAt(depth)
412 .map(o -> (o != null) ? Objects.toIdentityString(o) : null)
413 .forEach(jsonWriter::writeProperty);
414 jsonWriter.endArray();
415 jsonWriter.endObject();
416 }
417 depth++;
418 }
419 jsonWriter.endArray();
420 }
421
422 // thread identifier of carrier, when mounted
423 if (thread.isVirtual() && snapshot.carrierThread() instanceof Thread carrier) {
424 jsonWriter.writeLongProperty("carrier", carrier.threadId());
425 }
426
427 jsonWriter.endObject();
428 return true;
429 }
430
431 /**
432 * Simple JSON writer to stream objects/arrays to a TextWriter with formatting.
433 * This class is not intended to be a fully featured JSON writer.
434 */
435 private static class JsonWriter {
436 private static class Node {
437 final boolean isArray;
438 int propertyCount;
439 Node(boolean isArray) {
440 this.isArray = isArray;
441 }
442 boolean isArray() {
443 return isArray;
444 }
445 int propertyCount() {
446 return propertyCount;
447 }
448 int getAndIncrementPropertyCount() {
449 int old = propertyCount;
450 propertyCount++;
451 return old;
452 }
453 }
454 private final Deque<Node> stack = new ArrayDeque<>();
455 private final TextWriter writer;
456 private final boolean prettyPrint; // pretty print or minify
457 private final boolean generateLongsAsString;
458
459 JsonWriter(TextWriter writer, boolean prettyPrint, boolean generateLongsAsString) {
460 this.writer = writer;
461 this.prettyPrint = prettyPrint;
462 this.generateLongsAsString = generateLongsAsString;
463 }
464
465 private void print(Object obj) {
466 writer.print(obj);
467 }
468
469 private void println(Object obj) {
470 if (prettyPrint) {
471 writer.println(obj);
472 } else {
473 writer.print(obj);
474 }
475 }
476
477 private void println() {
478 if (prettyPrint) {
479 writer.println();
480 }
481 }
482
483 private void indent() {
484 if (prettyPrint) {
485 int indent = stack.size() * 2;
486 writer.print(" ".repeat(indent));
487 }
488 }
489
490 /**
491 * Start of object or array.
492 */
493 private void startObject(String name, boolean isArray) {
494 if (!stack.isEmpty()) {
495 Node node = stack.peek();
496 if (node.getAndIncrementPropertyCount() > 0) {
497 println(",");
498 }
499 }
500 indent();
501 if (name != null) {
502 String gap = prettyPrint ? " " : "";
503 print("\"" + name + "\":" + gap);
504 }
505 println(isArray ? "[" : "{");
506 stack.push(new Node(isArray));
507 }
508
509 /**
510 * End of object or array.
511 */
512 private void endObject(boolean isArray) {
513 Node node = stack.pop();
514 if (node.isArray() != isArray)
515 throw new IllegalStateException();
516 if (node.propertyCount() > 0) {
517 println();
518 }
519 indent();
520 print(isArray ? "]" : "}");
521 }
522
523 /**
524 * Write a property.
525 * @param name the property name, null for an unnamed property
526 * @param obj the value or null
527 */
528 void writeProperty(String name, Object obj) {
529 Node node = stack.peek();
530 assert node != null;
531 if (node.getAndIncrementPropertyCount() > 0) {
532 println(",");
533 }
534 indent();
535 if (name != null) {
536 print("\"" + name + "\": ");
537 }
538 switch (obj) {
539 case Number _ -> print(obj);
540 case Boolean _ -> print(obj);
541 case null -> print("null");
542 default -> print("\"" + escape(obj.toString()) + "\"");
543 }
544 }
545
546 /**
547 * Write a property with a long value. If the value is outside the "interop"
548 * range of IEEE-754 double-precision floating point (64-bit) then it is
549 * written as a string.
550 */
551 void writeLongProperty(String name, long value) {
552 if (generateLongsAsString || value < -0x1FFFFFFFFFFFFFL || value > 0x1FFFFFFFFFFFFFL) {
553 writeProperty(name, Long.toString(value));
554 } else {
555 writeProperty(name, value);
556 }
557 }
558
559 /**
560 * Write an unnamed property.
561 */
562 void writeProperty(Object obj) {
563 writeProperty(null, obj);
564 }
565
566 /**
567 * Start named object.
568 */
569 void startObject(String name) {
570 startObject(name, false);
571 }
572
573 /**
574 * Start unnamed object.
575 */
576 void startObject() {
577 startObject(null);
578 }
579
580 /**
581 * End of object.
582 */
583 void endObject() {
584 endObject(false);
585 }
586
587 /**
588 * Start named array.
589 */
590 void startArray(String name) {
591 startObject(name, true);
592 }
593
594 /**
595 * End of array.
596 */
597 void endArray() {
598 endObject(true);
599 }
600 }
601
602 /**
603 * Escapes characters for JSON strings and quoted thread names in plain text dumps.
604 */
605 private static String escape(String value) {
606 StringBuilder sb = new StringBuilder();
607 for (int i = 0; i < value.length(); i++) {
608 char c = value.charAt(i);
609 switch (c) {
610 case '"' -> sb.append("\\\"");
611 case '\\' -> sb.append("\\\\");
612 case '\b' -> sb.append("\\b");
613 case '\f' -> sb.append("\\f");
614 case '\n' -> sb.append("\\n");
615 case '\r' -> sb.append("\\r");
616 case '\t' -> sb.append("\\t");
617 default -> {
618 if (c <= 0x1f) {
619 sb.append(String.format("\\u%04x", (int) c));
620 } else {
621 sb.append(c);
622 }
623 }
624 }
625 }
626 return sb.toString();
627 }
628
629 /**
630 * A ByteArrayOutputStream of bounded size. Once the maximum number of bytes is
631 * written the subsequent bytes are discarded.
632 */
633 private static class BoundedByteArrayOutputStream extends ByteArrayOutputStream {
634 final int max;
635 BoundedByteArrayOutputStream(int max) {
636 this.max = max;
637 }
638 @Override
639 public void write(int b) {
640 if (count < max) {
641 super.write(b);
642 }
643 }
644 @Override
645 public void write(byte[] b, int off, int len) {
646 int remaining = max - count;
647 if (remaining > 0) {
648 super.write(b, off, Integer.min(len, remaining));
649 }
650 }
651 @Override
652 public void close() {
653 }
654 }
655
656 /**
657 * Simple Writer implementation for printing text. The print/println methods
658 * throw UncheckedIOException if an I/O error occurs.
659 */
660 private static class TextWriter extends Writer {
661 private final Writer delegate;
662
663 TextWriter(OutputStream out) {
664 delegate = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8));
665 }
666
667 @Override
668 public void write(char[] cbuf, int off, int len) throws IOException {
669 delegate.write(cbuf, off, len);
670 }
671
672 void print(Object obj) {
673 String s = String.valueOf(obj);
674 try {
675 write(s, 0, s.length());
676 } catch (IOException ioe) {
677 throw new UncheckedIOException(ioe);
678 }
679 }
680
681 void println() {
682 print(System.lineSeparator());
683 }
684
685 void println(String s) {
686 print(s);
687 println();
688 }
689
690 void println(Object obj) {
691 print(obj);
692 println();
693 }
694
695 @Override
696 public void flush() throws IOException {
697 delegate.flush();
698 }
699
700 @Override
701 public void close() throws IOException {
702 delegate.close();
703 }
704 }
705
706 /**
707 * Returns the process ID or -1 if not supported.
708 */
709 private static long processId() {
710 try {
711 return ProcessHandle.current().pid();
712 } catch (UnsupportedOperationException e) {
713 return -1L;
714 }
715 }
716 }