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      * @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 terminated
184         }
185         Instant now = Instant.now();
186         Thread.State state = snapshot.threadState();
187         writer.println("#" + thread.threadId() + " \"" + escape(snapshot.threadName())
188                 + "\" " + (thread.isVirtual() ? "virtual " : "")
189                 + decorateObject(thread)
190                 + " " + state
191                 + " cpuTime=" + snapshot.cpuTime()
192                 + " " + now);
193         StackTraceElement[] stackTrace = snapshot.stackTrace();
194         int depth = 0;
195         while (depth < stackTrace.length) {
196             writer.print("    at ");
197             writer.println(stackTrace[depth]);
198             snapshot.ownedMonitorsAt(depth).forEach(o -> {
199                 if (o != null) {
200                     writer.println("    - locked " + decorateObject(o));
201                 } else {
202                     writer.println("    - lock is eliminated");
203                 }
204             });
205 
206             // if parkBlocker set, or blocked/waiting on monitor, then print after top frame
207             if (depth == 0) {
208                 // park blocker
209                 Object parkBlocker = snapshot.parkBlocker();
210                 if (parkBlocker != null) {
211                     String suffix = (snapshot.parkBlockerOwner() instanceof Thread owner)
212                             ? ", owner #"  + owner.threadId()
213                             : "";
214                     writer.println("    - parking to wait for " + decorateObject(parkBlocker) + suffix);
215                 }
216 
217                 // blocked on monitor enter or Object.wait
218                 if (state == Thread.State.BLOCKED && snapshot.blockedOn() instanceof Object obj) {
219                     writer.println("    - waiting to lock " + decorateObject(obj));
220                 } else if ((state == Thread.State.WAITING || state == Thread.State.TIMED_WAITING)
221                         && snapshot.waitingOn() instanceof Object obj) {
222                     writer.println("    - waiting on " + decorateObject(obj));
223                 }
224             }
225 
226             depth++;
227         }
228         writer.println();
229         return true;
230     }
231 
232     /**
233      * Returns the identity string for the given object in a form suitable for the plain
234      * text format thread dump.
235      */
236     private static String decorateObject(Object obj) {
237         return "<" + Objects.toIdentityString(obj) + ">";
238     }
239 
240     /**
241      * Generate a thread dump in JSON format to the given output stream, UTF-8 encoded.
242      * This method is invoked by HotSpotDiagnosticMXBean.dumpThreads.
243      * @throws IOException if an I/O error occurs
244      */
245     public static void dumpThreadsToJson(OutputStream out) throws IOException {
246         var writer = new TextWriter(out);
247         try {
248             dumpThreadsToJson(writer);
249             writer.flush();
250         } catch (UncheckedIOException e) {
251             IOException ioe = e.getCause();
252             throw ioe;
253         }
254     }
255 
256     /**
257      * JSON is schema-less and the thread dump format will evolve over time.
258      * {@code HotSpotDiagnosticMXBean.dumpThreads} links to a JSON file that documents
259      * the latest/current format. A system property can be used to generate the thread
260      * dump in older formats if necessary.
261      */
262     private static class JsonFormat {
263         private static final String JSON_FORMAT_VERSION_PROP =
264                 "com.sun.management.HotSpotDiagnosticMXBean.dumpThreads.format";
265         static final int JSON_FORMAT_V1 = 1;
266         static final int JSON_FORMAT_V2 = 2;
267         private static final int JSON_FORMAT_LATEST = JSON_FORMAT_V2;
268         private static final int JSON_FORMAT;
269         static {
270             int ver = Integer.getInteger(JSON_FORMAT_VERSION_PROP, JSON_FORMAT_LATEST);
271             JSON_FORMAT = Math.clamp(ver, JSON_FORMAT_V1, JSON_FORMAT_LATEST);
272         }
273 
274         static int formatVersion() {
275             return JSON_FORMAT;
276         }
277     }
278 
279     /**
280      * Generate a thread dump to the given text stream in JSON format.
281      * @throws UncheckedIOException if an I/O error occurs
282      */
283     private static void dumpThreadsToJson(TextWriter textWriter) {
284         int format = JsonFormat.formatVersion();
285         var jsonWriter = new JsonWriter(textWriter, (format == JsonFormat.JSON_FORMAT_V1));
286         jsonWriter.startObject();  // top-level object
287         jsonWriter.startObject("threadDump");
288         if (format > JsonFormat.JSON_FORMAT_V1) {
289             jsonWriter.writeProperty("formatVersion", format);
290         }
291 
292         jsonWriter.writeLongProperty("processId", processId());
293         jsonWriter.writeProperty("time", Instant.now());
294         jsonWriter.writeProperty("runtimeVersion", Runtime.version());
295 
296         jsonWriter.startArray("threadContainers");
297         dumpThreads(ThreadContainers.root(), jsonWriter);
298         jsonWriter.endArray();
299 
300         jsonWriter.endObject();  // threadDump
301 
302         jsonWriter.endObject();  // end of top-level object
303     }
304 
305     /**
306      * Write a thread container to the given JSON writer.
307      * @throws UncheckedIOException if an I/O error occurs
308      */
309     private static void dumpThreads(ThreadContainer container, JsonWriter jsonWriter) {
310         jsonWriter.startObject();
311         jsonWriter.writeProperty("container", container);
312         jsonWriter.writeProperty("parent", container.parent());
313 
314         Thread owner = container.owner();
315         if (owner != null) {
316             jsonWriter.writeLongProperty("owner", owner.threadId());
317         } else {
318             jsonWriter.writeProperty("owner", null);  // owner is not optional
319         }
320 
321         long threadCount = 0;
322         jsonWriter.startArray("threads");
323         Iterator<Thread> threads = container.threads().iterator();
324         while (threads.hasNext()) {
325             Thread thread = threads.next();
326             if (dumpThread(thread, jsonWriter)) {
327                 threadCount++;
328             }
329         }
330         jsonWriter.endArray(); // threads
331 
332         // thread count
333         if (!ThreadContainers.trackAllThreads()) {
334             threadCount = Long.max(threadCount, container.threadCount());
335         }
336         jsonWriter.writeLongProperty("threadCount", threadCount);
337 
338         jsonWriter.endObject();
339 
340         // the children of the thread container follow
341         container.children().forEach(c -> dumpThreads(c, jsonWriter));
342     }
343 
344     /**
345      * Write a thread to the given JSON writer.
346      * @return true if the thread dump was written, false otherwise
347      * @throws UncheckedIOException if an I/O error occurs
348      */
349     private static boolean dumpThread(Thread thread, JsonWriter jsonWriter) {
350         Instant now = Instant.now();
351         ThreadSnapshot snapshot = ThreadSnapshot.of(thread);
352         if (snapshot == null) {
353             return false; // thread terminated
354         }
355         Thread.State state = snapshot.threadState();
356         StackTraceElement[] stackTrace = snapshot.stackTrace();
357 
358         jsonWriter.startObject();
359         jsonWriter.writeLongProperty("tid", thread.threadId());
360         jsonWriter.writeProperty("time", now);
361         if (thread.isVirtual()) {
362             jsonWriter.writeProperty("virtual", Boolean.TRUE);
363         }
364         jsonWriter.writeProperty("name", snapshot.threadName());
365         jsonWriter.writeProperty("threadObj", Objects.toIdentityString(thread));
366         jsonWriter.writeProperty("state", state);
367         if (snapshot.cpuTime() != -1L) {
368             jsonWriter.writeLongProperty("cpuTime", snapshot.cpuTime());
369         }
370 
371         // park blocker
372         Object parkBlocker = snapshot.parkBlocker();
373         if (parkBlocker != null) {
374             // parkBlocker is an object to allow for exclusiveOwnerThread in the future
375             jsonWriter.startObject("parkBlocker");
376             jsonWriter.writeProperty("object", Objects.toIdentityString(parkBlocker));
377             if (snapshot.parkBlockerOwner() instanceof Thread owner) {
378                 jsonWriter.writeLongProperty("owner", owner.threadId());
379             }
380             jsonWriter.endObject();
381         }
382 
383         // blocked on monitor enter or Object.wait
384         if (state == Thread.State.BLOCKED && snapshot.blockedOn() instanceof Object obj) {
385             jsonWriter.writeProperty("blockedOn", Objects.toIdentityString(obj));
386         } else if ((state == Thread.State.WAITING || state == Thread.State.TIMED_WAITING)
387                 && snapshot.waitingOn() instanceof Object obj) {
388             jsonWriter.writeProperty("waitingOn", Objects.toIdentityString(obj));
389         }
390 
391         // stack trace
392         jsonWriter.startArray("stack");
393         Arrays.stream(stackTrace).forEach(jsonWriter::writeProperty);
394         jsonWriter.endArray();
395 
396         // monitors owned, skip if none
397         if (snapshot.ownsMonitors()) {
398             jsonWriter.startArray("monitorsOwned");
399             int depth = 0;
400             while (depth < stackTrace.length) {
401                 List<Object> objs = snapshot.ownedMonitorsAt(depth).toList();
402                 if (!objs.isEmpty()) {
403                     jsonWriter.startObject();
404                     jsonWriter.writeProperty("depth", depth);
405                     jsonWriter.startArray("locks");
406                     snapshot.ownedMonitorsAt(depth)
407                             .map(o -> (o != null) ? Objects.toIdentityString(o) : null)
408                             .forEach(jsonWriter::writeProperty);
409                     jsonWriter.endArray();
410                     jsonWriter.endObject();
411                 }
412                 depth++;
413             }
414             jsonWriter.endArray();
415         }
416 
417         // thread identifier of carrier, when mounted
418         if (thread.isVirtual() && snapshot.carrierThread() instanceof Thread carrier) {
419             jsonWriter.writeLongProperty("carrier", carrier.threadId());
420         }
421 
422         jsonWriter.endObject();
423         return true;
424     }
425 
426     /**
427      * Simple JSON writer to stream objects/arrays to a TextWriter with formatting.
428      * This class is not intended to be a fully featured JSON writer.
429      */
430     private static class JsonWriter {
431         private static class Node {
432             final boolean isArray;
433             int propertyCount;
434             Node(boolean isArray) {
435                 this.isArray = isArray;
436             }
437             boolean isArray() {
438                 return isArray;
439             }
440             int propertyCount() {
441                 return propertyCount;
442             }
443             int getAndIncrementPropertyCount() {
444                 int old = propertyCount;
445                 propertyCount++;
446                 return old;
447             }
448         }
449         private final Deque<Node> stack = new ArrayDeque<>();
450         private final boolean generateLongsAsString;
451         private final TextWriter writer;
452 
453         JsonWriter(TextWriter writer, boolean generateLongsAsString) {
454             this.writer = writer;
455             this.generateLongsAsString = generateLongsAsString;
456         }
457 
458         private void indent() {
459             int indent = stack.size() * 2;
460             writer.print(" ".repeat(indent));
461         }
462 
463         /**
464          * Start of object or array.
465          */
466         private void startObject(String name, boolean isArray) {
467             if (!stack.isEmpty()) {
468                 Node node = stack.peek();
469                 if (node.getAndIncrementPropertyCount() > 0) {
470                     writer.println(",");
471                 }
472             }
473             indent();
474             if (name != null) {
475                 writer.print("\"" + name + "\": ");
476             }
477             writer.println(isArray ? "[" : "{");
478             stack.push(new Node(isArray));
479         }
480 
481         /**
482          * End of object or array.
483          */
484         private void endObject(boolean isArray) {
485             Node node = stack.pop();
486             if (node.isArray() != isArray)
487                 throw new IllegalStateException();
488             if (node.propertyCount() > 0) {
489                 writer.println();
490             }
491             indent();
492             writer.print(isArray ? "]" : "}");
493         }
494 
495         /**
496          * Write a property.
497          * @param name the property name, null for an unnamed property
498          * @param obj the value or null
499          */
500         void writeProperty(String name, Object obj) {
501             Node node = stack.peek();
502             assert node != null;
503             if (node.getAndIncrementPropertyCount() > 0) {
504                 writer.println(",");
505             }
506             indent();
507             if (name != null) {
508                 writer.print("\"" + name + "\": ");
509             }
510             switch (obj) {
511                 case Number _  -> writer.print(obj);
512                 case Boolean _ -> writer.print(obj);
513                 case null      -> writer.print("null");
514                 default        -> writer.print("\"" + escape(obj.toString()) + "\"");
515             }
516         }
517 
518         /**
519          * Write a property with a long value. If the value is outside the "interop"
520          * range of IEEE-754 double-precision floating point (64-bit) then it is
521          * written as a string.
522          */
523         void writeLongProperty(String name, long value) {
524             if (generateLongsAsString || value < -0x1FFFFFFFFFFFFFL || value > 0x1FFFFFFFFFFFFFL) {
525                 writeProperty(name, Long.toString(value));
526             } else {
527                 writeProperty(name, value);
528             }
529         }
530 
531         /**
532          * Write an unnamed property.
533          */
534         void writeProperty(Object obj) {
535             writeProperty(null, obj);
536         }
537 
538         /**
539          * Start named object.
540          */
541         void startObject(String name) {
542             startObject(name, false);
543         }
544 
545         /**
546          * Start unnamed object.
547          */
548         void startObject() {
549             startObject(null);
550         }
551 
552         /**
553          * End of object.
554          */
555         void endObject() {
556             endObject(false);
557         }
558 
559         /**
560          * Start named array.
561          */
562         void startArray(String name) {
563             startObject(name, true);
564         }
565 
566         /**
567          * End of array.
568          */
569         void endArray() {
570             endObject(true);
571         }
572     }
573 
574     /**
575      * Escapes characters for JSON strings and quoted thread names in plain text dumps.
576      */
577     private static String escape(String value) {
578         StringBuilder sb = new StringBuilder();
579         for (int i = 0; i < value.length(); i++) {
580             char c = value.charAt(i);
581             switch (c) {
582                 case '"'  -> sb.append("\\\"");
583                 case '\\' -> sb.append("\\\\");
584                 case '\b' -> sb.append("\\b");
585                 case '\f' -> sb.append("\\f");
586                 case '\n' -> sb.append("\\n");
587                 case '\r' -> sb.append("\\r");
588                 case '\t' -> sb.append("\\t");
589                 default -> {
590                     if (c <= 0x1f) {
591                         sb.append(String.format("\\u%04x", (int) c));
592                     } else {
593                         sb.append(c);
594                     }
595                 }
596             }
597         }
598         return sb.toString();
599     }
600 
601     /**
602      * A ByteArrayOutputStream of bounded size. Once the maximum number of bytes is
603      * written the subsequent bytes are discarded.
604      */
605     private static class BoundedByteArrayOutputStream extends ByteArrayOutputStream {
606         final int max;
607         BoundedByteArrayOutputStream(int max) {
608             this.max = max;
609         }
610         @Override
611         public void write(int b) {
612             if (count < max) {
613                 super.write(b);
614             }
615         }
616         @Override
617         public void write(byte[] b, int off, int len) {
618             int remaining = max - count;
619             if (remaining > 0) {
620                 super.write(b, off, Integer.min(len, remaining));
621             }
622         }
623         @Override
624         public void close() {
625         }
626     }
627 
628     /**
629      * Simple Writer implementation for printing text. The print/println methods
630      * throw UncheckedIOException if an I/O error occurs.
631      */
632     private static class TextWriter extends Writer {
633         private final Writer delegate;
634 
635         TextWriter(OutputStream out) {
636             delegate = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8));
637         }
638 
639         @Override
640         public void write(char[] cbuf, int off, int len) throws IOException {
641             delegate.write(cbuf, off, len);
642         }
643 
644         void print(Object obj) {
645             String s = String.valueOf(obj);
646             try {
647                 write(s, 0, s.length());
648             } catch (IOException ioe) {
649                 throw new UncheckedIOException(ioe);
650             }
651         }
652 
653         void println() {
654             print(System.lineSeparator());
655         }
656 
657         void println(String s) {
658             print(s);
659             println();
660         }
661 
662         void println(Object obj) {
663             print(obj);
664             println();
665         }
666 
667         @Override
668         public void flush() throws IOException {
669             delegate.flush();
670         }
671 
672         @Override
673         public void close() throws IOException {
674             delegate.close();
675         }
676     }
677 
678     /**
679      * Returns the process ID or -1 if not supported.
680      */
681     private static long processId() {
682         try {
683             return ProcessHandle.current().pid();
684         } catch (UnsupportedOperationException e) {
685             return -1L;
686         }
687     }
688 }