1 /*
2 * Copyright (c) 2020, 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. 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 * @return the UTF-8 encoded thread dump or message to return to the tool user
68 */
69 public static byte[] dumpThreads(String file, boolean okayToOverwrite) {
70 if (file == null || file.equals("-")) {
71 return dumpThreadsToByteArray(false, MAX_BYTE_ARRAY_SIZE);
72 } else {
73 return dumpThreadsToFile(file, okayToOverwrite, false);
74 }
75 }
76
77 /**
78 * Generate a thread dump in JSON format to a file or byte array, UTF-8 encoded.
79 * This method is invoked by the VM for the Thread.dump_to_file diagnostic command.
80 *
81 * @param file the file path to the file, null or "-" to return a byte array
82 * @param okayToOverwrite true to overwrite an existing file
83 * @return the UTF-8 encoded thread dump or message to return to the tool user
84 */
85 public static byte[] dumpThreadsToJson(String file, boolean okayToOverwrite) {
86 if (file == null || file.equals("-")) {
87 return dumpThreadsToByteArray(true, MAX_BYTE_ARRAY_SIZE);
88 } else {
89 return dumpThreadsToFile(file, okayToOverwrite, true);
90 }
91 }
92
93 /**
94 * Generate a thread dump in plain text or JSON format to a byte array, UTF-8 encoded.
95 * This method is the implementation of the Thread.dump_to_file diagnostic command
96 * when a file path is not specified. It returns the thread dump and/or message to
97 * send to the tool user.
98 */
99 private static byte[] dumpThreadsToByteArray(boolean json, int maxSize) {
100 var out = new BoundedByteArrayOutputStream(maxSize);
101 try (out; var writer = new TextWriter(out)) {
102 if (json) {
103 dumpThreadsToJson(writer);
104 } else {
105 dumpThreads(writer);
106 }
107 } catch (Exception ex) {
108 if (ex instanceof UncheckedIOException ioe) {
109 ex = ioe.getCause();
110 }
111 String reply = String.format("Failed: %s%n", ex);
112 return reply.getBytes(StandardCharsets.UTF_8);
113 }
114 return out.toByteArray();
115 }
116
117 /**
118 * Generate a thread dump in plain text or JSON format to the given file, UTF-8 encoded.
119 * This method is the implementation of the Thread.dump_to_file diagnostic command.
120 * It returns the thread dump and/or message to send to the tool user.
121 */
122 private static byte[] dumpThreadsToFile(String file, boolean okayToOverwrite, boolean json) {
123 Path path = Path.of(file).toAbsolutePath();
124 OpenOption[] options = (okayToOverwrite)
125 ? new OpenOption[0]
126 : new OpenOption[] { StandardOpenOption.CREATE_NEW };
127 String reply;
128 try (OutputStream out = Files.newOutputStream(path, options)) {
129 try (var writer = new TextWriter(out)) {
130 if (json) {
131 dumpThreadsToJson(writer);
132 } else {
133 dumpThreads(writer);
134 }
135 reply = String.format("Created %s%n", path);
136 } catch (UncheckedIOException e) {
137 reply = String.format("Failed: %s%n", e.getCause());
138 }
139 } catch (FileAlreadyExistsException _) {
140 reply = String.format("%s exists, use -overwrite to overwrite%n", path);
141 } catch (Exception ex) {
142 reply = String.format("Failed: %s%n", ex);
143 }
144 return reply.getBytes(StandardCharsets.UTF_8);
145 }
146
147 /**
148 * Generate a thread dump in plain text format to the given output stream, UTF-8
149 * encoded. This method is invoked by HotSpotDiagnosticMXBean.dumpThreads.
150 * @throws IOException if an I/O error occurs
151 */
152 public static void dumpThreads(OutputStream out) throws IOException {
153 var writer = new TextWriter(out);
154 try {
155 dumpThreads(writer);
156 writer.flush();
157 } catch (UncheckedIOException e) {
158 IOException ioe = e.getCause();
159 throw ioe;
160 }
161 }
162
163 /**
164 * Generate a thread dump in plain text format to the given text stream.
165 * @throws UncheckedIOException if an I/O error occurs
166 */
167 private static void dumpThreads(TextWriter writer) {
168 writer.println(processId());
169 writer.println(Instant.now());
170 writer.println(Runtime.version());
171 writer.println();
172 dumpThreads(ThreadContainers.root(), writer);
173 }
174
175 private static void dumpThreads(ThreadContainer container, TextWriter writer) {
176 container.threads().forEach(t -> dumpThread(t, writer));
177 container.children().forEach(c -> dumpThreads(c, writer));
178 }
179
180 private static boolean dumpThread(Thread thread, TextWriter writer) {
181 ThreadSnapshot snapshot = ThreadSnapshot.of(thread);
182 if (snapshot == null) {
183 return false; // thread not alive
184 }
185 Instant now = Instant.now();
186 Thread.State state = snapshot.threadState();
187 writer.println("#" + thread.threadId() + " \"" + snapshot.threadName()
188 + "\" " + (thread.isVirtual() ? "virtual " : "") + state + " " + now);
189
190 StackTraceElement[] stackTrace = snapshot.stackTrace();
191 int depth = 0;
192 while (depth < stackTrace.length) {
193 writer.print(" at ");
194 writer.println(stackTrace[depth]);
195 snapshot.ownedMonitorsAt(depth).forEach(o -> {
196 if (o != null) {
197 writer.println(" - locked " + decorateObject(o));
198 } else {
199 writer.println(" - lock is eliminated");
200 }
201 });
202
203 // if parkBlocker set, or blocked/waiting on monitor, then print after top frame
204 if (depth == 0) {
205 // park blocker
206 Object parkBlocker = snapshot.parkBlocker();
207 if (parkBlocker != null) {
208 String suffix = (snapshot.parkBlockerOwner() instanceof Thread owner)
209 ? ", owner #" + owner.threadId()
210 : "";
211 writer.println(" - parking to wait for " + decorateObject(parkBlocker) + suffix);
212 }
213
214 // blocked on monitor enter or Object.wait
215 if (state == Thread.State.BLOCKED && snapshot.blockedOn() instanceof Object obj) {
216 writer.println(" - waiting to lock " + decorateObject(obj));
217 } else if ((state == Thread.State.WAITING || state == Thread.State.TIMED_WAITING)
218 && snapshot.waitingOn() instanceof Object obj) {
219 writer.println(" - waiting on " + decorateObject(obj));
220 }
221 }
222
223 depth++;
224 }
225 writer.println();
226 return true;
227 }
228
229 /**
230 * Returns the identity string for the given object in a form suitable for the plain
231 * text format thread dump.
232 */
233 private static String decorateObject(Object obj) {
234 return "<" + Objects.toIdentityString(obj) + ">";
235 }
236
237 /**
238 * Generate a thread dump in JSON format to the given output stream, UTF-8 encoded.
239 * This method is invoked by HotSpotDiagnosticMXBean.dumpThreads.
240 * @throws IOException if an I/O error occurs
241 */
242 public static void dumpThreadsToJson(OutputStream out) throws IOException {
243 var writer = new TextWriter(out);
244 try {
245 dumpThreadsToJson(writer);
246 writer.flush();
247 } catch (UncheckedIOException e) {
248 IOException ioe = e.getCause();
249 throw ioe;
250 }
251 }
252
253 /**
254 * Generate a thread dump to the given text stream in JSON format.
255 * @throws UncheckedIOException if an I/O error occurs
256 */
257 private static void dumpThreadsToJson(TextWriter textWriter) {
258 var jsonWriter = new JsonWriter(textWriter);
259
260 jsonWriter.startObject(); // top-level object
261
262 jsonWriter.startObject("threadDump");
263
264 jsonWriter.writeProperty("processId", processId());
265 jsonWriter.writeProperty("time", Instant.now());
266 jsonWriter.writeProperty("runtimeVersion", Runtime.version());
267
268 jsonWriter.startArray("threadContainers");
269 dumpThreads(ThreadContainers.root(), jsonWriter);
270 jsonWriter.endArray();
271
272 jsonWriter.endObject(); // threadDump
273
274 jsonWriter.endObject(); // end of top-level object
275 }
276
277 /**
278 * Write a thread container to the given JSON writer.
279 * @throws UncheckedIOException if an I/O error occurs
280 */
281 private static void dumpThreads(ThreadContainer container, JsonWriter jsonWriter) {
282 jsonWriter.startObject();
283 jsonWriter.writeProperty("container", container);
284 jsonWriter.writeProperty("parent", container.parent());
285
286 Thread owner = container.owner();
287 jsonWriter.writeProperty("owner", (owner != null) ? owner.threadId() : null);
288
289 long threadCount = 0;
290 jsonWriter.startArray("threads");
291 Iterator<Thread> threads = container.threads().iterator();
292 while (threads.hasNext()) {
293 Thread thread = threads.next();
294 if (dumpThread(thread, jsonWriter)) {
295 threadCount++;
296 }
297 }
298 jsonWriter.endArray(); // threads
299
300 // thread count
301 if (!ThreadContainers.trackAllThreads()) {
302 threadCount = Long.max(threadCount, container.threadCount());
303 }
304 jsonWriter.writeProperty("threadCount", threadCount);
305
306 jsonWriter.endObject();
307
308 // the children of the thread container follow
309 container.children().forEach(c -> dumpThreads(c, jsonWriter));
310 }
311
312 /**
313 * Write a thread to the given JSON writer.
314 * @return true if the thread dump was written, false otherwise
315 * @throws UncheckedIOException if an I/O error occurs
316 */
317 private static boolean dumpThread(Thread thread, JsonWriter jsonWriter) {
318 Instant now = Instant.now();
319 ThreadSnapshot snapshot = ThreadSnapshot.of(thread);
320 if (snapshot == null) {
321 return false; // thread not alive
322 }
323 Thread.State state = snapshot.threadState();
324 StackTraceElement[] stackTrace = snapshot.stackTrace();
325
326 jsonWriter.startObject();
327 jsonWriter.writeProperty("tid", thread.threadId());
328 jsonWriter.writeProperty("time", now);
329 if (thread.isVirtual()) {
330 jsonWriter.writeProperty("virtual", Boolean.TRUE);
331 }
332 jsonWriter.writeProperty("name", snapshot.threadName());
333 jsonWriter.writeProperty("state", state);
334
335 // park blocker
336 Object parkBlocker = snapshot.parkBlocker();
337 if (parkBlocker != null) {
338 // parkBlocker is an object to allow for exclusiveOwnerThread in the future
339 jsonWriter.startObject("parkBlocker");
340 jsonWriter.writeProperty("object", Objects.toIdentityString(parkBlocker));
341 if (snapshot.parkBlockerOwner() instanceof Thread owner) {
342 jsonWriter.writeProperty("owner", owner.threadId());
343 }
344 jsonWriter.endObject();
345 }
346
347 // blocked on monitor enter or Object.wait
348 if (state == Thread.State.BLOCKED && snapshot.blockedOn() instanceof Object obj) {
349 jsonWriter.writeProperty("blockedOn", Objects.toIdentityString(obj));
350 } else if ((state == Thread.State.WAITING || state == Thread.State.TIMED_WAITING)
351 && snapshot.waitingOn() instanceof Object obj) {
352 jsonWriter.writeProperty("waitingOn", Objects.toIdentityString(obj));
353 }
354
355 // stack trace
356 jsonWriter.startArray("stack");
357 Arrays.stream(stackTrace).forEach(jsonWriter::writeProperty);
358 jsonWriter.endArray();
359
360 // monitors owned, skip if none
361 if (snapshot.ownsMonitors()) {
362 jsonWriter.startArray("monitorsOwned");
363 int depth = 0;
364 while (depth < stackTrace.length) {
365 List<Object> objs = snapshot.ownedMonitorsAt(depth).toList();
366 if (!objs.isEmpty()) {
367 jsonWriter.startObject();
368 jsonWriter.writeProperty("depth", depth);
369 jsonWriter.startArray("locks");
370 snapshot.ownedMonitorsAt(depth)
371 .map(o -> (o != null) ? Objects.toIdentityString(o) : null)
372 .forEach(jsonWriter::writeProperty);
373 jsonWriter.endArray();
374 jsonWriter.endObject();
375 }
376 depth++;
377 }
378 jsonWriter.endArray();
379 }
380
381 // thread identifier of carrier, when mounted
382 if (thread.isVirtual() && snapshot.carrierThread() instanceof Thread carrier) {
383 jsonWriter.writeProperty("carrier", carrier.threadId());
384 }
385
386 jsonWriter.endObject();
387 return true;
388 }
389
390 /**
391 * Simple JSON writer to stream objects/arrays to a TextWriter with formatting.
392 * This class is not intended to be a fully featured JSON writer.
393 */
394 private static class JsonWriter {
395 private static class Node {
396 final boolean isArray;
397 int propertyCount;
398 Node(boolean isArray) {
399 this.isArray = isArray;
400 }
401 boolean isArray() {
402 return isArray;
403 }
404 int propertyCount() {
405 return propertyCount;
406 }
407 int getAndIncrementPropertyCount() {
408 int old = propertyCount;
409 propertyCount++;
410 return old;
411 }
412 }
413 private final Deque<Node> stack = new ArrayDeque<>();
414 private final TextWriter writer;
415
416 JsonWriter(TextWriter writer) {
417 this.writer = writer;
418 }
419
420 private void indent() {
421 int indent = stack.size() * 2;
422 writer.print(" ".repeat(indent));
423 }
424
425 /**
426 * Start of object or array.
427 */
428 private void startObject(String name, boolean isArray) {
429 if (!stack.isEmpty()) {
430 Node node = stack.peek();
431 if (node.getAndIncrementPropertyCount() > 0) {
432 writer.println(",");
433 }
434 }
435 indent();
436 if (name != null) {
437 writer.print("\"" + name + "\": ");
438 }
439 writer.println(isArray ? "[" : "{");
440 stack.push(new Node(isArray));
441 }
442
443 /**
444 * End of object or array.
445 */
446 private void endObject(boolean isArray) {
447 Node node = stack.pop();
448 if (node.isArray() != isArray)
449 throw new IllegalStateException();
450 if (node.propertyCount() > 0) {
451 writer.println();
452 }
453 indent();
454 writer.print(isArray ? "]" : "}");
455 }
456
457 /**
458 * Write a property.
459 * @param name the property name, null for an unnamed property
460 * @param obj the value or null
461 */
462 void writeProperty(String name, Object obj) {
463 Node node = stack.peek();
464 if (node.getAndIncrementPropertyCount() > 0) {
465 writer.println(",");
466 }
467 indent();
468 if (name != null) {
469 writer.print("\"" + name + "\": ");
470 }
471 switch (obj) {
472 // Long may be larger than safe range of JSON integer value
473 case Long _ -> writer.print("\"" + obj + "\"");
474 case Number _ -> writer.print(obj);
475 case Boolean _ -> writer.print(obj);
476 case null -> writer.print("null");
477 default -> writer.print("\"" + escape(obj.toString()) + "\"");
478 }
479 }
480
481 /**
482 * Write an unnamed property.
483 */
484 void writeProperty(Object obj) {
485 writeProperty(null, obj);
486 }
487
488 /**
489 * Start named object.
490 */
491 void startObject(String name) {
492 startObject(name, false);
493 }
494
495 /**
496 * Start unnamed object.
497 */
498 void startObject() {
499 startObject(null);
500 }
501
502 /**
503 * End of object.
504 */
505 void endObject() {
506 endObject(false);
507 }
508
509 /**
510 * Start named array.
511 */
512 void startArray(String name) {
513 startObject(name, true);
514 }
515
516 /**
517 * End of array.
518 */
519 void endArray() {
520 endObject(true);
521 }
522
523 /**
524 * Escape any characters that need to be escape in the JSON output.
525 */
526 private static String escape(String value) {
527 StringBuilder sb = new StringBuilder();
528 for (int i = 0; i < value.length(); i++) {
529 char c = value.charAt(i);
530 switch (c) {
531 case '"' -> sb.append("\\\"");
532 case '\\' -> sb.append("\\\\");
533 case '/' -> sb.append("\\/");
534 case '\b' -> sb.append("\\b");
535 case '\f' -> sb.append("\\f");
536 case '\n' -> sb.append("\\n");
537 case '\r' -> sb.append("\\r");
538 case '\t' -> sb.append("\\t");
539 default -> {
540 if (c <= 0x1f) {
541 sb.append(String.format("\\u%04x", c));
542 } else {
543 sb.append(c);
544 }
545 }
546 }
547 }
548 return sb.toString();
549 }
550 }
551
552 /**
553 * A ByteArrayOutputStream of bounded size. Once the maximum number of bytes is
554 * written the subsequent bytes are discarded.
555 */
556 private static class BoundedByteArrayOutputStream extends ByteArrayOutputStream {
557 final int max;
558 BoundedByteArrayOutputStream(int max) {
559 this.max = max;
560 }
561 @Override
562 public void write(int b) {
563 if (max < count) {
564 super.write(b);
565 }
566 }
567 @Override
568 public void write(byte[] b, int off, int len) {
569 int remaining = max - count;
570 if (remaining > 0) {
571 super.write(b, off, Integer.min(len, remaining));
572 }
573 }
574 @Override
575 public void close() {
576 }
577 }
578
579 /**
580 * Simple Writer implementation for printing text. The print/println methods
581 * throw UncheckedIOException if an I/O error occurs.
582 */
583 private static class TextWriter extends Writer {
584 private final Writer delegate;
585
586 TextWriter(OutputStream out) {
587 delegate = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8));
588 }
589
590 @Override
591 public void write(char[] cbuf, int off, int len) throws IOException {
592 delegate.write(cbuf, off, len);
593 }
594
595 void print(Object obj) {
596 String s = String.valueOf(obj);
597 try {
598 write(s, 0, s.length());
599 } catch (IOException ioe) {
600 throw new UncheckedIOException(ioe);
601 }
602 }
603
604 void println() {
605 print(System.lineSeparator());
606 }
607
608 void println(String s) {
609 print(s);
610 println();
611 }
612
613 void println(Object obj) {
614 print(obj);
615 println();
616 }
617
618 @Override
619 public void flush() throws IOException {
620 delegate.flush();
621 }
622
623 @Override
624 public void close() throws IOException {
625 delegate.close();
626 }
627 }
628
629 /**
630 * Returns the process ID or -1 if not supported.
631 */
632 private static long processId() {
633 try {
634 return ProcessHandle.current().pid();
635 } catch (UnsupportedOperationException e) {
636 return -1L;
637 }
638 }
639 }