1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  * Copyright (c) 1994, 2020, Oracle and/or its affiliates. All rights reserved.
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This code is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License version 2 only, as
8  * published by the Free Software Foundation.  Oracle designates this
9  * particular file as subject to the "Classpath" exception as provided
10  * by Oracle in the LICENSE file that accompanied this code.
11  *
12  * This code is distributed in the hope that it will be useful, but WITHOUT
13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15  * version 2 for more details (a copy is included in the LICENSE file that
16  * accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License version
19  * 2 along with this work; if not, write to the Free Software Foundation,
20  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21  *
22  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
23  * or visit www.oracle.com if you need additional information or have any
24  * questions.
25  */
26 
27 package java.lang;
28 
29 import dalvik.annotation.optimization.FastNative;
30 import dalvik.annotation.optimization.NeverInline;
31 
32 import java.io.*;
33 import java.util.*;
34 
35 /**
36  * The {@code Throwable} class is the superclass of all errors and
37  * exceptions in the Java language. Only objects that are instances of this
38  * class (or one of its subclasses) are thrown by the Java Virtual Machine or
39  * can be thrown by the Java {@code throw} statement. Similarly, only
40  * this class or one of its subclasses can be the argument type in a
41  * {@code catch} clause.
42  *
43  * For the purposes of compile-time checking of exceptions, {@code
44  * Throwable} and any subclass of {@code Throwable} that is not also a
45  * subclass of either {@link RuntimeException} or {@link Error} are
46  * regarded as checked exceptions.
47  *
48  * <p>Instances of two subclasses, {@link java.lang.Error} and
49  * {@link java.lang.Exception}, are conventionally used to indicate
50  * that exceptional situations have occurred. Typically, these instances
51  * are freshly created in the context of the exceptional situation so
52  * as to include relevant information (such as stack trace data).
53  *
54  * <p>A throwable contains a snapshot of the execution stack of its
55  * thread at the time it was created. It can also contain a message
56  * string that gives more information about the error. Over time, a
57  * throwable can {@linkplain Throwable#addSuppressed suppress} other
58  * throwables from being propagated.  Finally, the throwable can also
59  * contain a <i>cause</i>: another throwable that caused this
60  * throwable to be constructed.  The recording of this causal information
61  * is referred to as the <i>chained exception</i> facility, as the
62  * cause can, itself, have a cause, and so on, leading to a "chain" of
63  * exceptions, each caused by another.
64  *
65  * <p>One reason that a throwable may have a cause is that the class that
66  * throws it is built atop a lower layered abstraction, and an operation on
67  * the upper layer fails due to a failure in the lower layer.  It would be bad
68  * design to let the throwable thrown by the lower layer propagate outward, as
69  * it is generally unrelated to the abstraction provided by the upper layer.
70  * Further, doing so would tie the API of the upper layer to the details of
71  * its implementation, assuming the lower layer's exception was a checked
72  * exception.  Throwing a "wrapped exception" (i.e., an exception containing a
73  * cause) allows the upper layer to communicate the details of the failure to
74  * its caller without incurring either of these shortcomings.  It preserves
75  * the flexibility to change the implementation of the upper layer without
76  * changing its API (in particular, the set of exceptions thrown by its
77  * methods).
78  *
79  * <p>A second reason that a throwable may have a cause is that the method
80  * that throws it must conform to a general-purpose interface that does not
81  * permit the method to throw the cause directly.  For example, suppose
82  * a persistent collection conforms to the {@link java.util.Collection
83  * Collection} interface, and that its persistence is implemented atop
84  * {@code java.io}.  Suppose the internals of the {@code add} method
85  * can throw an {@link java.io.IOException IOException}.  The implementation
86  * can communicate the details of the {@code IOException} to its caller
87  * while conforming to the {@code Collection} interface by wrapping the
88  * {@code IOException} in an appropriate unchecked exception.  (The
89  * specification for the persistent collection should indicate that it is
90  * capable of throwing such exceptions.)
91  *
92  * <p>A cause can be associated with a throwable in two ways: via a
93  * constructor that takes the cause as an argument, or via the
94  * {@link #initCause(Throwable)} method.  New throwable classes that
95  * wish to allow causes to be associated with them should provide constructors
96  * that take a cause and delegate (perhaps indirectly) to one of the
97  * {@code Throwable} constructors that takes a cause.
98  *
99  * Because the {@code initCause} method is public, it allows a cause to be
100  * associated with any throwable, even a "legacy throwable" whose
101  * implementation predates the addition of the exception chaining mechanism to
102  * {@code Throwable}.
103  *
104  * <p>By convention, class {@code Throwable} and its subclasses have two
105  * constructors, one that takes no arguments and one that takes a
106  * {@code String} argument that can be used to produce a detail message.
107  * Further, those subclasses that might likely have a cause associated with
108  * them should have two more constructors, one that takes a
109  * {@code Throwable} (the cause), and one that takes a
110  * {@code String} (the detail message) and a {@code Throwable} (the
111  * cause).
112  *
113  * @author  Josh Bloch (Added exception chaining and programmatic access to
114  *          stack trace in 1.4.)
115  * @jls 11.2 Compile-Time Checking of Exceptions
116  * @since 1.0
117  */
118 public class Throwable implements Serializable {
119     /** use serialVersionUID from JDK 1.0.2 for interoperability */
120     @java.io.Serial
121     private static final long serialVersionUID = -3042686055658047285L;
122 
123     /**
124      * The JVM saves some indication of the stack backtrace in this slot.
125      */
126     private transient Object backtrace;
127 
128     /**
129      * Specific details about the Throwable.  For example, for
130      * {@code FileNotFoundException}, this contains the name of
131      * the file that could not be found.
132      *
133      * @serial
134      */
135     private String detailMessage;
136 
137 
138     /**
139      * Holder class to defer initializing sentinel objects only used
140      * for serialization.
141      */
142     private static class SentinelHolder {
143         /**
144          * {@linkplain #setStackTrace(StackTraceElement[]) Setting the
145          * stack trace} to a one-element array containing this sentinel
146          * value indicates future attempts to set the stack trace will be
147          * ignored.  The sentinel is equal to the result of calling:<br>
148          * {@code new StackTraceElement("", "", null, Integer.MIN_VALUE)}
149          */
150         public static final StackTraceElement STACK_TRACE_ELEMENT_SENTINEL =
151             new StackTraceElement("", "", null, Integer.MIN_VALUE);
152 
153         /**
154          * Sentinel value used in the serial form to indicate an immutable
155          * stack trace.
156          */
157         public static final StackTraceElement[] STACK_TRACE_SENTINEL =
158             new StackTraceElement[] {STACK_TRACE_ELEMENT_SENTINEL};
159     }
160 
161     // Android-removed: Use libcore.util.EmptyArray for the empty stack trace.
162     // Adding the constant UNASSIGNED_STACK breaks serialization of some subclasses
163     // /**
164     //  * A shared value for an empty stack.
165     //  */
166     // private static final StackTraceElement[] UNASSIGNED_STACK = new StackTraceElement[0];
167 
168     /*
169      * To allow Throwable objects to be made immutable and safely
170      * reused by the JVM, such as OutOfMemoryErrors, fields of
171      * Throwable that are writable in response to user actions, cause,
172      * stackTrace, and suppressedExceptions obey the following
173      * protocol:
174      *
175      * 1) The fields are initialized to a non-null sentinel value
176      * which indicates the value has logically not been set.
177      *
178      * 2) Writing a null to the field indicates further writes
179      * are forbidden
180      *
181      * 3) The sentinel value may be replaced with another non-null
182      * value.
183      *
184      * For example, implementations of the HotSpot JVM have
185      * preallocated OutOfMemoryError objects to provide for better
186      * diagnosability of that situation.  These objects are created
187      * without calling the constructor for that class and the fields
188      * in question are initialized to null.  To support this
189      * capability, any new fields added to Throwable that require
190      * being initialized to a non-null value require a coordinated JVM
191      * change.
192      */
193 
194     /**
195      * The throwable that caused this throwable to get thrown, or null if this
196      * throwable was not caused by another throwable, or if the causative
197      * throwable is unknown.  If this field is equal to this throwable itself,
198      * it indicates that the cause of this throwable has not yet been
199      * initialized.
200      *
201      * @serial
202      * @since 1.4
203      */
204     private Throwable cause = this;
205 
206     /**
207      * The stack trace, as returned by {@link #getStackTrace()}.
208      *
209      * The field is initialized to a zero-length array.  A {@code
210      * null} value of this field indicates subsequent calls to {@link
211      * #setStackTrace(StackTraceElement[])} and {@link
212      * #fillInStackTrace()} will be no-ops.
213      *
214      * @serial
215      * @since 1.4
216      */
217     // Android-changed: Use libcore.util.EmptyArray for the empty stack trace.
218     // private StackTraceElement[] stackTrace = UNASSIGNED_STACK;
219     private StackTraceElement[] stackTrace = libcore.util.EmptyArray.STACK_TRACE_ELEMENT;
220 
221     /**
222      * The JVM code sets the depth of the backtrace for later retrieval
223      */
224     // Android-removed: native getStackTrace is used instead.
225     // private transient int depth;
226 
227     // Android-removed: Use empty collection in place of SUPPRESSED_SENTINEL.
228     // Adding this constant breaks serialization of some subclasses
229     /*
230     // Setting this static field introduces an acceptable
231     // initialization dependency on a few java.util classes.
232     private static final List<Throwable> SUPPRESSED_SENTINEL = Collections.emptyList();
233     */
234 
235     /**
236      * The list of suppressed exceptions, as returned by {@link
237      * #getSuppressed()}.  The list is initialized to a zero-element
238      * unmodifiable sentinel list.  When a serialized Throwable is
239      * read in, if the {@code suppressedExceptions} field points to a
240      * zero-element list, the field is reset to the sentinel value.
241      *
242      * @serial
243      * @since 1.7
244      */
245      // Android-changed: Use empty collection in place of SUPPRESSED_SENTINEL.
246      // @SuppressWarnings("serial") // Not statically typed as Serializable
247      // private List<Throwable> suppressedExceptions = SUPPRESSED_SENTINEL;
248      private List<Throwable> suppressedExceptions = Collections.emptyList();
249 
250     /** Message for trying to suppress a null exception. */
251     private static final String NULL_CAUSE_MESSAGE = "Cannot suppress a null exception.";
252 
253     /** Message for trying to suppress oneself. */
254     private static final String SELF_SUPPRESSION_MESSAGE = "Self-suppression not permitted";
255 
256     /** Caption  for labeling causative exception stack traces */
257     private static final String CAUSE_CAPTION = "Caused by: ";
258 
259     /** Caption for labeling suppressed exception stack traces */
260     private static final String SUPPRESSED_CAPTION = "Suppressed: ";
261 
262     /**
263      * Constructs a new throwable with {@code null} as its detail message.
264      * The cause is not initialized, and may subsequently be initialized by a
265      * call to {@link #initCause}.
266      *
267      * <p>The {@link #fillInStackTrace()} method is called to initialize
268      * the stack trace data in the newly created throwable.
269      */
Throwable()270     public Throwable() {
271         fillInStackTrace();
272     }
273 
274     /**
275      * Constructs a new throwable with the specified detail message.  The
276      * cause is not initialized, and may subsequently be initialized by
277      * a call to {@link #initCause}.
278      *
279      * <p>The {@link #fillInStackTrace()} method is called to initialize
280      * the stack trace data in the newly created throwable.
281      *
282      * @param   message   the detail message. The detail message is saved for
283      *          later retrieval by the {@link #getMessage()} method.
284      */
Throwable(String message)285     public Throwable(String message) {
286         fillInStackTrace();
287         detailMessage = message;
288     }
289 
290     /**
291      * Constructs a new throwable with the specified detail message and
292      * cause.  <p>Note that the detail message associated with
293      * {@code cause} is <i>not</i> automatically incorporated in
294      * this throwable's detail message.
295      *
296      * <p>The {@link #fillInStackTrace()} method is called to initialize
297      * the stack trace data in the newly created throwable.
298      *
299      * @param  message the detail message (which is saved for later retrieval
300      *         by the {@link #getMessage()} method).
301      * @param  cause the cause (which is saved for later retrieval by the
302      *         {@link #getCause()} method).  (A {@code null} value is
303      *         permitted, and indicates that the cause is nonexistent or
304      *         unknown.)
305      * @since  1.4
306      */
Throwable(String message, Throwable cause)307     public Throwable(String message, Throwable cause) {
308         fillInStackTrace();
309         detailMessage = message;
310         this.cause = cause;
311     }
312 
313     /**
314      * Constructs a new throwable with the specified cause and a detail
315      * message of {@code (cause==null ? null : cause.toString())} (which
316      * typically contains the class and detail message of {@code cause}).
317      * This constructor is useful for throwables that are little more than
318      * wrappers for other throwables (for example, {@link
319      * java.security.PrivilegedActionException}).
320      *
321      * <p>The {@link #fillInStackTrace()} method is called to initialize
322      * the stack trace data in the newly created throwable.
323      *
324      * @param  cause the cause (which is saved for later retrieval by the
325      *         {@link #getCause()} method).  (A {@code null} value is
326      *         permitted, and indicates that the cause is nonexistent or
327      *         unknown.)
328      * @since  1.4
329      */
Throwable(Throwable cause)330     public Throwable(Throwable cause) {
331         fillInStackTrace();
332         detailMessage = (cause==null ? null : cause.toString());
333         this.cause = cause;
334     }
335 
336     /**
337      * Constructs a new throwable with the specified detail message,
338      * cause, {@linkplain #addSuppressed suppression} enabled or
339      * disabled, and writable stack trace enabled or disabled.  If
340      * suppression is disabled, {@link #getSuppressed} for this object
341      * will return a zero-length array and calls to {@link
342      * #addSuppressed} that would otherwise append an exception to the
343      * suppressed list will have no effect.  If the writable stack
344      * trace is false, this constructor will not call {@link
345      * #fillInStackTrace()}, a {@code null} will be written to the
346      * {@code stackTrace} field, and subsequent calls to {@code
347      * fillInStackTrace} and {@link
348      * #setStackTrace(StackTraceElement[])} will not set the stack
349      * trace.  If the writable stack trace is false, {@link
350      * #getStackTrace} will return a zero length array.
351      *
352      * <p>Note that the other constructors of {@code Throwable} treat
353      * suppression as being enabled and the stack trace as being
354      * writable.  Subclasses of {@code Throwable} should document any
355      * conditions under which suppression is disabled and document
356      * conditions under which the stack trace is not writable.
357      * Disabling of suppression should only occur in exceptional
358      * circumstances where special requirements exist, such as a
359      * virtual machine reusing exception objects under low-memory
360      * situations.  Circumstances where a given exception object is
361      * repeatedly caught and rethrown, such as to implement control
362      * flow between two sub-systems, is another situation where
363      * immutable throwable objects would be appropriate.
364      *
365      * @param  message the detail message.
366      * @param cause the cause.  (A {@code null} value is permitted,
367      * and indicates that the cause is nonexistent or unknown.)
368      * @param enableSuppression whether or not suppression is enabled or disabled
369      * @param writableStackTrace whether or not the stack trace should be
370      *                           writable
371      *
372      * @see OutOfMemoryError
373      * @see NullPointerException
374      * @see ArithmeticException
375      * @since 1.7
376      */
Throwable(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace)377     protected Throwable(String message, Throwable cause,
378                         boolean enableSuppression,
379                         boolean writableStackTrace) {
380         if (writableStackTrace) {
381             fillInStackTrace();
382         } else {
383             stackTrace = null;
384         }
385         detailMessage = message;
386         this.cause = cause;
387         if (!enableSuppression)
388             suppressedExceptions = null;
389     }
390 
391     /**
392      * Returns the detail message string of this throwable.
393      *
394      * @return  the detail message string of this {@code Throwable} instance
395      *          (which may be {@code null}).
396      */
getMessage()397     public String getMessage() {
398         return detailMessage;
399     }
400 
401     /**
402      * Creates a localized description of this throwable.
403      * Subclasses may override this method in order to produce a
404      * locale-specific message.  For subclasses that do not override this
405      * method, the default implementation returns the same result as
406      * {@code getMessage()}.
407      *
408      * @return  The localized description of this throwable.
409      * @since   1.1
410      */
getLocalizedMessage()411     public String getLocalizedMessage() {
412         return getMessage();
413     }
414 
415     /**
416      * Returns the cause of this throwable or {@code null} if the
417      * cause is nonexistent or unknown.  (The cause is the throwable that
418      * caused this throwable to get thrown.)
419      *
420      * <p>This implementation returns the cause that was supplied via one of
421      * the constructors requiring a {@code Throwable}, or that was set after
422      * creation with the {@link #initCause(Throwable)} method.  While it is
423      * typically unnecessary to override this method, a subclass can override
424      * it to return a cause set by some other means.  This is appropriate for
425      * a "legacy chained throwable" that predates the addition of chained
426      * exceptions to {@code Throwable}.  Note that it is <i>not</i>
427      * necessary to override any of the {@code PrintStackTrace} methods,
428      * all of which invoke the {@code getCause} method to determine the
429      * cause of a throwable.
430      *
431      * @return  the cause of this throwable or {@code null} if the
432      *          cause is nonexistent or unknown.
433      * @since 1.4
434      */
getCause()435     public synchronized Throwable getCause() {
436         return (cause==this ? null : cause);
437     }
438 
439     /**
440      * Initializes the <i>cause</i> of this throwable to the specified value.
441      * (The cause is the throwable that caused this throwable to get thrown.)
442      *
443      * <p>This method can be called at most once.  It is generally called from
444      * within the constructor, or immediately after creating the
445      * throwable.  If this throwable was created
446      * with {@link #Throwable(Throwable)} or
447      * {@link #Throwable(String,Throwable)}, this method cannot be called
448      * even once.
449      *
450      * <p>An example of using this method on a legacy throwable type
451      * without other support for setting the cause is:
452      *
453      * <pre>
454      * try {
455      *     lowLevelOp();
456      * } catch (LowLevelException le) {
457      *     throw (HighLevelException)
458      *           new HighLevelException().initCause(le); // Legacy constructor
459      * }
460      * </pre>
461      *
462      * @param  cause the cause (which is saved for later retrieval by the
463      *         {@link #getCause()} method).  (A {@code null} value is
464      *         permitted, and indicates that the cause is nonexistent or
465      *         unknown.)
466      * @return  a reference to this {@code Throwable} instance.
467      * @throws IllegalArgumentException if {@code cause} is this
468      *         throwable.  (A throwable cannot be its own cause.)
469      * @throws IllegalStateException if this throwable was
470      *         created with {@link #Throwable(Throwable)} or
471      *         {@link #Throwable(String,Throwable)}, or this method has already
472      *         been called on this throwable.
473      * @since  1.4
474      */
initCause(Throwable cause)475     public synchronized Throwable initCause(Throwable cause) {
476         if (this.cause != this)
477             throw new IllegalStateException("Can't overwrite cause with " +
478                                             Objects.toString(cause, "a null"), this);
479         if (cause == this)
480             throw new IllegalArgumentException("Self-causation not permitted", this);
481         this.cause = cause;
482         return this;
483     }
484 
485     /*
486      * This is called by readObject of a few exceptions such as
487      * ClassNotFoundException and ExceptionInInitializerError to deserialize
488      * a stream output from an older runtime version where the cause may
489      * have set to null.
490      */
setCause(Throwable t)491     final void setCause(Throwable t) {
492         this.cause = t;
493     }
494 
495     /**
496      * Returns a short description of this throwable.
497      * The result is the concatenation of:
498      * <ul>
499      * <li> the {@linkplain Class#getName() name} of the class of this object
500      * <li> ": " (a colon and a space)
501      * <li> the result of invoking this object's {@link #getLocalizedMessage}
502      *      method
503      * </ul>
504      * If {@code getLocalizedMessage} returns {@code null}, then just
505      * the class name is returned.
506      *
507      * @return a string representation of this throwable.
508      */
toString()509     public String toString() {
510         String s = getClass().getName();
511         String message = getLocalizedMessage();
512         return (message != null) ? (s + ": " + message) : s;
513     }
514 
515     /**
516      * Prints this throwable and its backtrace to the
517      * standard error stream. This method prints a stack trace for this
518      * {@code Throwable} object on the error output stream that is
519      * the value of the field {@code System.err}. The first line of
520      * output contains the result of the {@link #toString()} method for
521      * this object.  Remaining lines represent data previously recorded by
522      * the method {@link #fillInStackTrace()}. The format of this
523      * information depends on the implementation, but the following
524      * example may be regarded as typical:
525      * <blockquote><pre>
526      * java.lang.NullPointerException
527      *         at MyClass.mash(MyClass.java:9)
528      *         at MyClass.crunch(MyClass.java:6)
529      *         at MyClass.main(MyClass.java:3)
530      * </pre></blockquote>
531      * This example was produced by running the program:
532      * <pre>
533      * class MyClass {
534      *     public static void main(String[] args) {
535      *         crunch(null);
536      *     }
537      *     static void crunch(int[] a) {
538      *         mash(a);
539      *     }
540      *     static void mash(int[] b) {
541      *         System.out.println(b[0]);
542      *     }
543      * }
544      * </pre>
545      * The backtrace for a throwable with an initialized, non-null cause
546      * should generally include the backtrace for the cause.  The format
547      * of this information depends on the implementation, but the following
548      * example may be regarded as typical:
549      * <pre>
550      * HighLevelException: MidLevelException: LowLevelException
551      *         at Junk.a(Junk.java:13)
552      *         at Junk.main(Junk.java:4)
553      * Caused by: MidLevelException: LowLevelException
554      *         at Junk.c(Junk.java:23)
555      *         at Junk.b(Junk.java:17)
556      *         at Junk.a(Junk.java:11)
557      *         ... 1 more
558      * Caused by: LowLevelException
559      *         at Junk.e(Junk.java:30)
560      *         at Junk.d(Junk.java:27)
561      *         at Junk.c(Junk.java:21)
562      *         ... 3 more
563      * </pre>
564      * Note the presence of lines containing the characters {@code "..."}.
565      * These lines indicate that the remainder of the stack trace for this
566      * exception matches the indicated number of frames from the bottom of the
567      * stack trace of the exception that was caused by this exception (the
568      * "enclosing" exception).  This shorthand can greatly reduce the length
569      * of the output in the common case where a wrapped exception is thrown
570      * from same method as the "causative exception" is caught.  The above
571      * example was produced by running the program:
572      * <pre>
573      * public class Junk {
574      *     public static void main(String args[]) {
575      *         try {
576      *             a();
577      *         } catch(HighLevelException e) {
578      *             e.printStackTrace();
579      *         }
580      *     }
581      *     static void a() throws HighLevelException {
582      *         try {
583      *             b();
584      *         } catch(MidLevelException e) {
585      *             throw new HighLevelException(e);
586      *         }
587      *     }
588      *     static void b() throws MidLevelException {
589      *         c();
590      *     }
591      *     static void c() throws MidLevelException {
592      *         try {
593      *             d();
594      *         } catch(LowLevelException e) {
595      *             throw new MidLevelException(e);
596      *         }
597      *     }
598      *     static void d() throws LowLevelException {
599      *        e();
600      *     }
601      *     static void e() throws LowLevelException {
602      *         throw new LowLevelException();
603      *     }
604      * }
605      *
606      * class HighLevelException extends Exception {
607      *     HighLevelException(Throwable cause) { super(cause); }
608      * }
609      *
610      * class MidLevelException extends Exception {
611      *     MidLevelException(Throwable cause)  { super(cause); }
612      * }
613      *
614      * class LowLevelException extends Exception {
615      * }
616      * </pre>
617      * As of release 7, the platform supports the notion of
618      * <i>suppressed exceptions</i> (in conjunction with the {@code
619      * try}-with-resources statement). Any exceptions that were
620      * suppressed in order to deliver an exception are printed out
621      * beneath the stack trace.  The format of this information
622      * depends on the implementation, but the following example may be
623      * regarded as typical:
624      *
625      * <pre>
626      * Exception in thread "main" java.lang.Exception: Something happened
627      *  at Foo.bar(Foo.java:10)
628      *  at Foo.main(Foo.java:5)
629      *  Suppressed: Resource$CloseFailException: Resource ID = 0
630      *          at Resource.close(Resource.java:26)
631      *          at Foo.bar(Foo.java:9)
632      *          ... 1 more
633      * </pre>
634      * Note that the "... n more" notation is used on suppressed exceptions
635      * just as it is used on causes. Unlike causes, suppressed exceptions are
636      * indented beyond their "containing exceptions."
637      *
638      * <p>An exception can have both a cause and one or more suppressed
639      * exceptions:
640      * <pre>
641      * Exception in thread "main" java.lang.Exception: Main block
642      *  at Foo3.main(Foo3.java:7)
643      *  Suppressed: Resource$CloseFailException: Resource ID = 2
644      *          at Resource.close(Resource.java:26)
645      *          at Foo3.main(Foo3.java:5)
646      *  Suppressed: Resource$CloseFailException: Resource ID = 1
647      *          at Resource.close(Resource.java:26)
648      *          at Foo3.main(Foo3.java:5)
649      * Caused by: java.lang.Exception: I did it
650      *  at Foo3.main(Foo3.java:8)
651      * </pre>
652      * Likewise, a suppressed exception can have a cause:
653      * <pre>
654      * Exception in thread "main" java.lang.Exception: Main block
655      *  at Foo4.main(Foo4.java:6)
656      *  Suppressed: Resource2$CloseFailException: Resource ID = 1
657      *          at Resource2.close(Resource2.java:20)
658      *          at Foo4.main(Foo4.java:5)
659      *  Caused by: java.lang.Exception: Rats, you caught me
660      *          at Resource2$CloseFailException.&lt;init&gt;(Resource2.java:45)
661      *          ... 2 more
662      * </pre>
663      */
printStackTrace()664     public void printStackTrace() {
665         printStackTrace(System.err);
666     }
667 
668     /**
669      * Prints this throwable and its backtrace to the specified print stream.
670      *
671      * @param s {@code PrintStream} to use for output
672      */
printStackTrace(PrintStream s)673     public void printStackTrace(PrintStream s) {
674         printStackTrace(new WrappedPrintStream(s));
675     }
676 
printStackTrace(PrintStreamOrWriter s)677     private void printStackTrace(PrintStreamOrWriter s) {
678         // Guard against malicious overrides of Throwable.equals by
679         // using a Set with identity equality semantics.
680         Set<Throwable> dejaVu = Collections.newSetFromMap(new IdentityHashMap<>());
681         dejaVu.add(this);
682 
683         synchronized (s.lock()) {
684             // Print our stack trace
685             s.println(this);
686             StackTraceElement[] trace = getOurStackTrace();
687             for (StackTraceElement traceElement : trace)
688                 s.println("\tat " + traceElement);
689 
690             // Print suppressed exceptions, if any
691             for (Throwable se : getSuppressed())
692                 se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION, "\t", dejaVu);
693 
694             // Print cause, if any
695             Throwable ourCause = getCause();
696             if (ourCause != null)
697                 ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, "", dejaVu);
698         }
699     }
700 
701     /**
702      * Print our stack trace as an enclosed exception for the specified
703      * stack trace.
704      */
printEnclosedStackTrace(PrintStreamOrWriter s, StackTraceElement[] enclosingTrace, String caption, String prefix, Set<Throwable> dejaVu)705     private void printEnclosedStackTrace(PrintStreamOrWriter s,
706                                          StackTraceElement[] enclosingTrace,
707                                          String caption,
708                                          String prefix,
709                                          Set<Throwable> dejaVu) {
710         // Android-removed: Use of assert keyword which breaks serialization of some subclasses.
711         // (Using assert adds a static field that determines whether assertions are enabled.)
712         // assert Thread.holdsLock(s.lock());
713         if (dejaVu.contains(this)) {
714             s.println(prefix + caption + "[CIRCULAR REFERENCE: " + this + "]");
715         } else {
716             dejaVu.add(this);
717             // Compute number of frames in common between this and enclosing trace
718             StackTraceElement[] trace = getOurStackTrace();
719             int m = trace.length - 1;
720             int n = enclosingTrace.length - 1;
721             while (m >= 0 && n >=0 && trace[m].equals(enclosingTrace[n])) {
722                 m--; n--;
723             }
724             int framesInCommon = trace.length - 1 - m;
725 
726             // Print our stack trace
727             s.println(prefix + caption + this);
728             for (int i = 0; i <= m; i++)
729                 s.println(prefix + "\tat " + trace[i]);
730             if (framesInCommon != 0)
731                 s.println(prefix + "\t... " + framesInCommon + " more");
732 
733             // Print suppressed exceptions, if any
734             for (Throwable se : getSuppressed())
735                 se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION,
736                                            prefix +"\t", dejaVu);
737 
738             // Print cause, if any
739             Throwable ourCause = getCause();
740             if (ourCause != null)
741                 ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, prefix, dejaVu);
742         }
743     }
744 
745     /**
746      * Prints this throwable and its backtrace to the specified
747      * print writer.
748      *
749      * @param s {@code PrintWriter} to use for output
750      * @since   1.1
751      */
printStackTrace(PrintWriter s)752     public void printStackTrace(PrintWriter s) {
753         printStackTrace(new WrappedPrintWriter(s));
754     }
755 
756     /**
757      * Wrapper class for PrintStream and PrintWriter to enable a single
758      * implementation of printStackTrace.
759      */
760     private abstract static class PrintStreamOrWriter {
761         /** Returns the object to be locked when using this StreamOrWriter */
lock()762         abstract Object lock();
763 
764         /** Prints the specified string as a line on this StreamOrWriter */
println(Object o)765         abstract void println(Object o);
766     }
767 
768     private static class WrappedPrintStream extends PrintStreamOrWriter {
769         private final PrintStream printStream;
770 
WrappedPrintStream(PrintStream printStream)771         WrappedPrintStream(PrintStream printStream) {
772             this.printStream = printStream;
773         }
774 
lock()775         Object lock() {
776             return printStream;
777         }
778 
println(Object o)779         void println(Object o) {
780             printStream.println(o);
781         }
782     }
783 
784     private static class WrappedPrintWriter extends PrintStreamOrWriter {
785         private final PrintWriter printWriter;
786 
WrappedPrintWriter(PrintWriter printWriter)787         WrappedPrintWriter(PrintWriter printWriter) {
788             this.printWriter = printWriter;
789         }
790 
lock()791         Object lock() {
792             return printWriter;
793         }
794 
println(Object o)795         void println(Object o) {
796             printWriter.println(o);
797         }
798     }
799 
800     /**
801      * Fills in the execution stack trace. This method records within this
802      * {@code Throwable} object information about the current state of
803      * the stack frames for the current thread.
804      *
805      * <p>If the stack trace of this {@code Throwable} {@linkplain
806      * Throwable#Throwable(String, Throwable, boolean, boolean) is not
807      * writable}, calling this method has no effect.
808      *
809      * @return  a reference to this {@code Throwable} instance.
810      * @see     java.lang.Throwable#printStackTrace()
811      */
812     // Android-changed: Add @NeverInline to keep code size low.
813     @NeverInline
fillInStackTrace()814     public synchronized Throwable fillInStackTrace() {
815         if (stackTrace != null ||
816             backtrace != null /* Out of protocol state */ ) {
817             // Android-changed: Use Android-specific nativeFillInStackTrace.
818             // fillInStackTrace(0);
819             backtrace = nativeFillInStackTrace();
820             // Android-changed: Use libcore.util.EmptyArray for the empty stack trace.
821             // stackTrace = UNASSIGNED_STACK;
822             stackTrace = libcore.util.EmptyArray.STACK_TRACE_ELEMENT;
823         }
824         return this;
825     }
826 
827     // Android-changed: Use Android-specific nativeFillInStackTrace.
828     // private native Throwable fillInStackTrace(int dummy);
829     @FastNative
nativeFillInStackTrace()830     private static native Object nativeFillInStackTrace();
831 
832     /**
833      * Provides programmatic access to the stack trace information printed by
834      * {@link #printStackTrace()}.  Returns an array of stack trace elements,
835      * each representing one stack frame.  The zeroth element of the array
836      * (assuming the array's length is non-zero) represents the top of the
837      * stack, which is the last method invocation in the sequence.  Typically,
838      * this is the point at which this throwable was created and thrown.
839      * The last element of the array (assuming the array's length is non-zero)
840      * represents the bottom of the stack, which is the first method invocation
841      * in the sequence.
842      *
843      * <p>Some virtual machines may, under some circumstances, omit one
844      * or more stack frames from the stack trace.  In the extreme case,
845      * a virtual machine that has no stack trace information concerning
846      * this throwable is permitted to return a zero-length array from this
847      * method.  Generally speaking, the array returned by this method will
848      * contain one element for every frame that would be printed by
849      * {@code printStackTrace}.  Writes to the returned array do not
850      * affect future calls to this method.
851      *
852      * @return an array of stack trace elements representing the stack trace
853      *         pertaining to this throwable.
854      * @since  1.4
855      */
getStackTrace()856     public StackTraceElement[] getStackTrace() {
857         return getOurStackTrace().clone();
858     }
859 
getOurStackTrace()860     private synchronized StackTraceElement[] getOurStackTrace() {
861         // Initialize stack trace field with information from
862         // backtrace if this is the first call to this method
863         // Android-changed: Use libcore.util.EmptyArray for the empty stack trace.
864         // if (stackTrace == UNASSIGNED_STACK ||
865         if (stackTrace == libcore.util.EmptyArray.STACK_TRACE_ELEMENT ||
866             (stackTrace == null && backtrace != null) /* Out of protocol state */) {
867             // BEGIN Android-changed: Use Android-specific nativeGetStackTrace.
868             // stackTrace = StackTraceElement.of(this, depth);
869             stackTrace = nativeGetStackTrace(backtrace);
870             backtrace = null;
871             if (stackTrace == null) {
872                 return libcore.util.EmptyArray.STACK_TRACE_ELEMENT;
873             }
874             // END Android-changed: Use Android-specific nativeGetStackTrace.
875         } else if (stackTrace == null) {
876             // Android-changed: Use libcore.util.EmptyArray for the empty stack trace.
877             // return UNASSIGNED_STACK;
878             return libcore.util.EmptyArray.STACK_TRACE_ELEMENT;
879         }
880         return stackTrace;
881     }
882 
883     /**
884      * Sets the stack trace elements that will be returned by
885      * {@link #getStackTrace()} and printed by {@link #printStackTrace()}
886      * and related methods.
887      *
888      * This method, which is designed for use by RPC frameworks and other
889      * advanced systems, allows the client to override the default
890      * stack trace that is either generated by {@link #fillInStackTrace()}
891      * when a throwable is constructed or deserialized when a throwable is
892      * read from a serialization stream.
893      *
894      * <p>If the stack trace of this {@code Throwable} {@linkplain
895      * Throwable#Throwable(String, Throwable, boolean, boolean) is not
896      * writable}, calling this method has no effect other than
897      * validating its argument.
898      *
899      * @param   stackTrace the stack trace elements to be associated with
900      * this {@code Throwable}.  The specified array is copied by this
901      * call; changes in the specified array after the method invocation
902      * returns will have no affect on this {@code Throwable}'s stack
903      * trace.
904      *
905      * @throws NullPointerException if {@code stackTrace} is
906      *         {@code null} or if any of the elements of
907      *         {@code stackTrace} are {@code null}
908      *
909      * @since  1.4
910      */
setStackTrace(StackTraceElement[] stackTrace)911     public void setStackTrace(StackTraceElement[] stackTrace) {
912         // Validate argument
913         StackTraceElement[] defensiveCopy = stackTrace.clone();
914         for (int i = 0; i < defensiveCopy.length; i++) {
915             if (defensiveCopy[i] == null)
916                 throw new NullPointerException("stackTrace[" + i + "]");
917         }
918 
919         synchronized (this) {
920             if (this.stackTrace == null && // Immutable stack
921                 backtrace == null) // Test for out of protocol state
922                 return;
923             this.stackTrace = defensiveCopy;
924         }
925     }
926 
927     /**
928      * Returns the specified element of the stack trace.
929      *
930      * package-protection for use by SharedSecrets.
931      *
932      * @param index index of the element to return.
933      * @throws IndexOutOfBoundsException if {@code index < 0 ||
934      *         index >= getStackTraceDepth() }
935      */
936     // Android-changed: Use Android-specific nativeGetStackTrace.
937     // native StackTraceElement getStackTraceElement(int index);
938     @FastNative
nativeGetStackTrace(Object stackState)939     private static native StackTraceElement[] nativeGetStackTrace(Object stackState);
940 
941     /**
942      * Reads a {@code Throwable} from a stream, enforcing
943      * well-formedness constraints on fields.  Null entries and
944      * self-pointers are not allowed in the list of {@code
945      * suppressedExceptions}.  Null entries are not allowed for stack
946      * trace elements.  A null stack trace in the serial form results
947      * in a zero-length stack element array. A single-element stack
948      * trace whose entry is equal to {@code new StackTraceElement("",
949      * "", null, Integer.MIN_VALUE)} results in a {@code null} {@code
950      * stackTrace} field.
951      *
952      * Note that there are no constraints on the value the {@code
953      * cause} field can hold; both {@code null} and {@code this} are
954      * valid values for the field.
955      *
956      * @param  s the {@code ObjectInputStream} from which data is read
957      * @throws IOException if an I/O error occurs
958      * @throws ClassNotFoundException if a serialized class cannot be loaded
959      */
960     @java.io.Serial
readObject(ObjectInputStream s)961     private void readObject(ObjectInputStream s)
962         throws IOException, ClassNotFoundException {
963         s.defaultReadObject();     // read in all fields
964 
965         // Set suppressed exceptions and stack trace elements fields
966         // to marker values until the contents from the serial stream
967         // are validated.
968         List<Throwable> candidateSuppressedExceptions = suppressedExceptions;
969         // Android-changed: Use empty collection in place of SUPPRESSED_SENTINEL.
970         // suppressedExceptions = SUPPRESSED_SENTINEL;
971         suppressedExceptions = Collections.emptyList();
972 
973         StackTraceElement[] candidateStackTrace = stackTrace;
974         // Android-changed: Directly create empty array instead of cloning UNASSIGNED_STACK.
975         // stackTrace = UNASSIGNED_STACK.clone();
976         stackTrace = new StackTraceElement[0];
977 
978         if (candidateSuppressedExceptions != null) {
979             int suppressedSize = validateSuppressedExceptionsList(candidateSuppressedExceptions);
980             if (suppressedSize > 0) { // Copy valid Throwables to new list
981                 var suppList  = new ArrayList<Throwable>(Math.min(100, suppressedSize));
982 
983                 for (Throwable t : candidateSuppressedExceptions) {
984                     // Enforce constraints on suppressed exceptions in
985                     // case of corrupt or malicious stream.
986                     Objects.requireNonNull(t, NULL_CAUSE_MESSAGE);
987                     if (t == this)
988                         throw new IllegalArgumentException(SELF_SUPPRESSION_MESSAGE);
989                     suppList.add(t);
990                 }
991                 // If there are any invalid suppressed exceptions,
992                 // implicitly use the sentinel value assigned earlier.
993                 suppressedExceptions = suppList;
994             }
995         } else {
996             suppressedExceptions = null;
997         }
998 
999         /*
1000          * For zero-length stack traces, use a clone of
1001          * UNASSIGNED_STACK rather than UNASSIGNED_STACK itself to
1002          * allow identity comparison against UNASSIGNED_STACK in
1003          * getOurStackTrace.  The identity of UNASSIGNED_STACK in
1004          * stackTrace indicates to the getOurStackTrace method that
1005          * the stackTrace needs to be constructed from the information
1006          * in backtrace.
1007          */
1008         if (candidateStackTrace != null) {
1009             // Work from a clone of the candidateStackTrace to ensure
1010             // consistency of checks.
1011             candidateStackTrace = candidateStackTrace.clone();
1012             if (candidateStackTrace.length >= 1) {
1013                 if (candidateStackTrace.length == 1 &&
1014                         // Check for the marker of an immutable stack trace
1015                         SentinelHolder.STACK_TRACE_ELEMENT_SENTINEL.equals(candidateStackTrace[0])) {
1016                     stackTrace = null;
1017                 } else { // Verify stack trace elements are non-null.
1018                     for (StackTraceElement ste : candidateStackTrace) {
1019                         Objects.requireNonNull(ste, "null StackTraceElement in serial stream.");
1020                     }
1021                     stackTrace = candidateStackTrace;
1022                 }
1023             }
1024         }
1025         // A null stackTrace field in the serial form can result from
1026         // an exception serialized without that field in older JDK
1027         // releases; treat such exceptions as having empty stack
1028         // traces by leaving stackTrace assigned to a clone of
1029         // UNASSIGNED_STACK.
1030     }
1031 
validateSuppressedExceptionsList(List<Throwable> deserSuppressedExceptions)1032     private int validateSuppressedExceptionsList(List<Throwable> deserSuppressedExceptions)
1033         throws IOException {
1034         // BEGIN Android-changed: Object class hasn't implemented the module system and getModule().
1035         /*
1036         if (!Object.class.getModule().
1037             equals(deserSuppressedExceptions.getClass().getModule())) {
1038             throw new StreamCorruptedException("List implementation not in base module.");
1039         } else {
1040         */
1041         {
1042         // END Android-changed: Object class hasn't implemented the module system and getModule().
1043             int size = deserSuppressedExceptions.size();
1044             if (size < 0) {
1045                 throw new StreamCorruptedException("Negative list size reported.");
1046             }
1047             return size;
1048         }
1049     }
1050 
1051     /**
1052      * Write a {@code Throwable} object to a stream.
1053      *
1054      * A {@code null} stack trace field is represented in the serial
1055      * form as a one-element array whose element is equal to {@code
1056      * new StackTraceElement("", "", null, Integer.MIN_VALUE)}.
1057      *
1058      * @param  s the {@code ObjectOutputStream} to which data is written
1059      * @throws IOException if an I/O error occurs
1060      */
1061     @java.io.Serial
writeObject(ObjectOutputStream s)1062     private synchronized void writeObject(ObjectOutputStream s)
1063         throws IOException {
1064         // Ensure that the stackTrace field is initialized to a
1065         // non-null value, if appropriate.  As of JDK 7, a null stack
1066         // trace field is a valid value indicating the stack trace
1067         // should not be set.
1068         getOurStackTrace();
1069 
1070         StackTraceElement[] oldStackTrace = stackTrace;
1071         try {
1072             if (stackTrace == null)
1073                 stackTrace = SentinelHolder.STACK_TRACE_SENTINEL;
1074             s.defaultWriteObject();
1075         } finally {
1076             stackTrace = oldStackTrace;
1077         }
1078     }
1079 
1080     /**
1081      * Appends the specified exception to the exceptions that were
1082      * suppressed in order to deliver this exception. This method is
1083      * thread-safe and typically called (automatically and implicitly)
1084      * by the {@code try}-with-resources statement.
1085      *
1086      * <p>The suppression behavior is enabled <em>unless</em> disabled
1087      * {@linkplain #Throwable(String, Throwable, boolean, boolean) via
1088      * a constructor}.  When suppression is disabled, this method does
1089      * nothing other than to validate its argument.
1090      *
1091      * <p>Note that when one exception {@linkplain
1092      * #initCause(Throwable) causes} another exception, the first
1093      * exception is usually caught and then the second exception is
1094      * thrown in response.  In other words, there is a causal
1095      * connection between the two exceptions.
1096      *
1097      * In contrast, there are situations where two independent
1098      * exceptions can be thrown in sibling code blocks, in particular
1099      * in the {@code try} block of a {@code try}-with-resources
1100      * statement and the compiler-generated {@code finally} block
1101      * which closes the resource.
1102      *
1103      * In these situations, only one of the thrown exceptions can be
1104      * propagated.  In the {@code try}-with-resources statement, when
1105      * there are two such exceptions, the exception originating from
1106      * the {@code try} block is propagated and the exception from the
1107      * {@code finally} block is added to the list of exceptions
1108      * suppressed by the exception from the {@code try} block.  As an
1109      * exception unwinds the stack, it can accumulate multiple
1110      * suppressed exceptions.
1111      *
1112      * <p>An exception may have suppressed exceptions while also being
1113      * caused by another exception.  Whether or not an exception has a
1114      * cause is semantically known at the time of its creation, unlike
1115      * whether or not an exception will suppress other exceptions
1116      * which is typically only determined after an exception is
1117      * thrown.
1118      *
1119      * <p>Note that programmer written code is also able to take
1120      * advantage of calling this method in situations where there are
1121      * multiple sibling exceptions and only one can be propagated.
1122      *
1123      * @param exception the exception to be added to the list of
1124      *        suppressed exceptions
1125      * @throws IllegalArgumentException if {@code exception} is this
1126      *         throwable; a throwable cannot suppress itself.
1127      * @throws NullPointerException if {@code exception} is {@code null}
1128      * @since 1.7
1129      */
addSuppressed(Throwable exception)1130     public final synchronized void addSuppressed(Throwable exception) {
1131         if (exception == this)
1132             throw new IllegalArgumentException(SELF_SUPPRESSION_MESSAGE, exception);
1133 
1134         Objects.requireNonNull(exception, NULL_CAUSE_MESSAGE);
1135 
1136         if (suppressedExceptions == null) // Suppressed exceptions not recorded
1137             return;
1138 
1139         // Android-changed: Use empty collection in place of SUPPRESSED_SENTINEL.
1140         // if (suppressedExceptions == SUPPRESSED_SENTINEL)
1141         if (suppressedExceptions.isEmpty())
1142             suppressedExceptions = new ArrayList<>(1);
1143 
1144         suppressedExceptions.add(exception);
1145     }
1146 
1147     // Android-changed: Lazily initialize EMPTY_THROWABLE_ARRAY.
1148     // private static final Throwable[] EMPTY_THROWABLE_ARRAY = new Throwable[0];
1149     private static Throwable[] EMPTY_THROWABLE_ARRAY;
1150 
1151     /**
1152      * Returns an array containing all of the exceptions that were
1153      * suppressed, typically by the {@code try}-with-resources
1154      * statement, in order to deliver this exception.
1155      *
1156      * If no exceptions were suppressed or {@linkplain
1157      * #Throwable(String, Throwable, boolean, boolean) suppression is
1158      * disabled}, an empty array is returned.  This method is
1159      * thread-safe.  Writes to the returned array do not affect future
1160      * calls to this method.
1161      *
1162      * @return an array containing all of the exceptions that were
1163      *         suppressed to deliver this exception.
1164      * @since 1.7
1165      */
getSuppressed()1166     public final synchronized Throwable[] getSuppressed() {
1167         // Android-added: Lazily initialize EMPTY_THROWABLE_ARRAY.
1168         if (EMPTY_THROWABLE_ARRAY == null) {
1169             EMPTY_THROWABLE_ARRAY = new Throwable[0];
1170         }
1171 
1172         // Android-changed: Use empty collection in place of SUPPRESSED_SENTINEL.
1173         // if (suppressedExceptions == SUPPRESSED_SENTINEL ||
1174         //    suppressedExceptions == null)
1175         if (suppressedExceptions == null || suppressedExceptions.isEmpty())
1176             return EMPTY_THROWABLE_ARRAY;
1177         else
1178             return suppressedExceptions.toArray(EMPTY_THROWABLE_ARRAY);
1179     }
1180 }
1181