      1 /*
      2  * Copyright (c) 2000, 2020, 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
     26 package java.lang;
     27
     28 import jdk.internal.loader.BuiltinClassLoader;
     29 import jdk.internal.misc.VM;
     30 import jdk.internal.module.ModuleHashes;
     31 import jdk.internal.module.ModuleReferenceImpl;
     32
     33 import java.lang.module.ModuleDescriptor.Version;
     34 import java.lang.module.ModuleReference;
     35 import java.lang.module.ResolvedModule;
     36 import java.util.HashSet;
     37 import java.util.Objects;
     38 import java.util.Optional;
     39 import java.util.Set;
     40
     41 /**
     42  * An element in a stack trace, as returned by {@link
     43  * Throwable#getStackTrace()}.  Each element represents a single stack frame.
     44  * All stack frames except for the one at the top of the stack represent
     45  * a method invocation.  The frame at the top of the stack represents the
     46  * execution point at which the stack trace was generated.  Typically,
     47  * this is the point at which the throwable corresponding to the stack trace
     48  * was created.
     49  *
     50  * @since  1.4
     51  * @author Josh Bloch
     52  */
     53 public final class StackTraceElement implements java.io.Serializable {
     54
     55     // For Throwables and StackWalker, the VM initially sets this field to a
     56     // reference to the declaring Class.  The Class reference is used to
     57     // construct the 'format' bitmap, and then is cleared.
     58     //
     59     // For STEs constructed using the public constructors, this field is not used.
     60     private transient Class<?> declaringClassObject;
     61
     62     // Normally initialized by VM
     63     /**
     64      * The name of the class loader.
     65      */
     66     private String classLoaderName;
     67     /**
     68      * The module name.
     69      */
     70     private String moduleName;
     71     /**
     72      * The module version.
     73      */
     74     private String moduleVersion;
     75     /**
     76      * The declaring class.
     77      */
     78     private String declaringClass;
     79     /**
     80      * The method name.
     81      */
     82     private String methodName;
     83     /**
     84      * The source file name.
     85      */
     86     private String fileName;
     87     /**
     88      * The source line number.
     89      */
     90     private int    lineNumber;
     91     /**
     92      * Control to show full or partial module, package, and class names.
     93      */
     94     private byte   format = 0; // Default to show all
     95
     96     /**
     97      * Creates a stack trace element representing the specified execution
     98      * point. The {@link #getModuleName module name} and {@link
     99      * #getModuleVersion module version} of the stack trace element will
    100      * be {@code null}.
    101      *
    102      * @param declaringClass the fully qualified name of the class containing
    103      *        the execution point represented by the stack trace element
    104      * @param methodName the name of the method containing the execution point
    105      *        represented by the stack trace element
    106      * @param fileName the name of the file containing the execution point
    107      *         represented by the stack trace element, or {@code null} if
    108      *         this information is unavailable
    109      * @param lineNumber the line number of the source line containing the
    110      *         execution point represented by this stack trace element, or
    111      *         a negative number if this information is unavailable. A value
    112      *         of -2 indicates that the method containing the execution point
    113      *         is a native method
    114      * @throws NullPointerException if {@code declaringClass} or
    115      *         {@code methodName} is null
    116      * @since 1.5
    117      * @revised 9
    118      * @spec JPMS
    119      */
    120     public StackTraceElement(String declaringClass, String methodName,
    121                              String fileName, int lineNumber) {
    122         this(null, null, null, declaringClass, methodName, fileName, lineNumber);
    123     }
    124
    125     /**
    126      * Creates a stack trace element representing the specified execution
    127      * point.
    128      *
    129      * @param classLoaderName the class loader name if the class loader of
    130      *        the class containing the execution point represented by
    131      *        the stack trace is named; otherwise {@code null}
    132      * @param moduleName the module name if the class containing the
    133      *        execution point represented by the stack trace is in a named
    134      *        module; otherwise {@code null}
    135      * @param moduleVersion the module version if the class containing the
    136      *        execution point represented by the stack trace is in a named
    137      *        module that has a version; otherwise {@code null}
    138      * @param declaringClass the fully qualified name of the class containing
    139      *        the execution point represented by the stack trace element
    140      * @param methodName the name of the method containing the execution point
    141      *        represented by the stack trace element
    142      * @param fileName the name of the file containing the execution point
    143      *        represented by the stack trace element, or {@code null} if
    144      *        this information is unavailable
    145      * @param lineNumber the line number of the source line containing the
    146      *        execution point represented by this stack trace element, or
    147      *        a negative number if this information is unavailable. A value
    148      *        of -2 indicates that the method containing the execution point
    149      *        is a native method
    150      *
    151      * @throws NullPointerException if {@code declaringClass} is {@code null}
    152      *         or {@code methodName} is {@code null}
    153      *
    154      * @since 9
    155      * @spec JPMS
    156      */
    157     public StackTraceElement(String classLoaderName,
    158                              String moduleName, String moduleVersion,
    159                              String declaringClass, String methodName,
    160                              String fileName, int lineNumber) {
    161         this.classLoaderName = classLoaderName;
    162         this.moduleName      = moduleName;
    163         this.moduleVersion   = moduleVersion;
    164         this.declaringClass  = Objects.requireNonNull(declaringClass, "Declaring class is null");
    165         this.methodName      = Objects.requireNonNull(methodName, "Method name is null");
    166         this.fileName        = fileName;
    167         this.lineNumber      = lineNumber;
    168     }
    169
    170     /*
    171      * Private constructor for the factory methods to create StackTraceElement
    172      * for Throwable and StackFrameInfo
    173      */
    174     private StackTraceElement() {}
    175
    176     /**
    177      * Returns the name of the source file containing the execution point
    178      * represented by this stack trace element.  Generally, this corresponds
    179      * to the {@code SourceFile} attribute of the relevant {@code class}
    180      * file (as per <cite>The Java Virtual Machine Specification</cite>, Section
    181      * {@jvms 4.7.7}).  In some systems, the name may refer to some source code unit
    182      * other than a file, such as an entry in source repository.
    183      *
    184      * @return the name of the file containing the execution point
    185      *         represented by this stack trace element, or {@code null} if
    186      *         this information is unavailable.
    187      */
    188     public String getFileName() {
    189         return fileName;
    190     }
    191
    192     /**
    193      * Returns the line number of the source line containing the execution
    194      * point represented by this stack trace element.  Generally, this is
    195      * derived from the {@code LineNumberTable} attribute of the relevant
    196      * {@code class} file (as per <cite>The Java Virtual Machine
    197      * Specification</cite>, Section {@jvms 4.7.8}).
    198      *
    199      * @return the line number of the source line containing the execution
    200      *         point represented by this stack trace element, or a negative
    201      *         number if this information is unavailable.
    202      */
    203     public int getLineNumber() {
    204         return lineNumber;
    205     }
    206
    207     /**
    208      * Returns the module name of the module containing the execution point
    209      * represented by this stack trace element.
    210      *
    211      * @return the module name of the {@code Module} containing the execution
    212      *         point represented by this stack trace element; {@code null}
    213      *         if the module name is not available.
    214      * @since 9
    215      * @spec JPMS
    216      * @see Module#getName()
    217      */
    218     public String getModuleName() {
    219         return moduleName;
    220     }
    221
    222     /**
    223      * Returns the module version of the module containing the execution point
    224      * represented by this stack trace element.
    225      *
    226      * @return the module version of the {@code Module} containing the execution
    227      *         point represented by this stack trace element; {@code null}
    228      *         if the module version is not available.
    229      * @since 9
    230      * @spec JPMS
    231      * @see java.lang.module.ModuleDescriptor.Version
    232      */
    233     public String getModuleVersion() {
    234         return moduleVersion;
    235     }
    236
    237     /**
    238      * Returns the name of the class loader of the class containing the
    239      * execution point represented by this stack trace element.
    240      *
    241      * @return the name of the class loader of the class containing the execution
    242      *         point represented by this stack trace element; {@code null}
    243      *         if the class loader is not named.
    244      *
    245      * @since 9
    246      * @spec JPMS
    247      * @see java.lang.ClassLoader#getName()
    248      */
    249     public String getClassLoaderName() {
    250         return classLoaderName;
    251     }
    252
    253     /**
    254      * Returns the fully qualified name of the class containing the
    255      * execution point represented by this stack trace element.
    256      *
    257      * @return the fully qualified name of the {@code Class} containing
    258      *         the execution point represented by this stack trace element.
    259      */
    260     public String getClassName() {
    261         return declaringClass;
    262     }
    263
    264     /**
    265      * Returns the name of the method containing the execution point
    266      * represented by this stack trace element.  If the execution point is
    267      * contained in an instance or class initializer, this method will return
    268      * the appropriate <i>special method name</i>, {@code <init>} or
    269      * {@code <clinit>}, as per Section {@jvms 3.9} of <cite>The Java Virtual
    270      * Machine Specification</cite>.
    271      *
    272      * @return the name of the method containing the execution point
    273      *         represented by this stack trace element.
    274      */
    275     public String getMethodName() {
    276         return methodName;
    277     }
    278
    279     /**
    280      * Returns true if the method containing the execution point
    281      * represented by this stack trace element is a native method.
    282      *
    283      * @return {@code true} if the method containing the execution point
    284      *         represented by this stack trace element is a native method.
    285      */
    286     public boolean isNativeMethod() {
    287         return lineNumber == -2;
    288     }
    289
    290     /**
    291      * Returns a string representation of this stack trace element.
    292      *
    293      * @apiNote The format of this string depends on the implementation, but the
    294      * following examples may be regarded as typical:
    295      * <ul>
    296      * <li>
    297      *     "{@code com.foo.loader/foo@9.0/com.foo.Main.run(Main.java:101)}"
    298      * - See the description below.
    299      * </li>
    300      * <li>
    301      *     "{@code com.foo.loader/foo@9.0/com.foo.Main.run(Main.java)}"
    302      * - The line number is unavailable.
    303      * </li>
    304      * <li>
    305      *     "{@code com.foo.loader/foo@9.0/com.foo.Main.run(Unknown Source)}"
    306      * - Neither the file name nor the line number is available.
    307      * </li>
    308      * <li>
    309      *     "{@code com.foo.loader/foo@9.0/com.foo.Main.run(Native Method)}"
    310      * - The method containing the execution point is a native method.
    311      * </li>
    312      * <li>
    313      *     "{@code com.foo.loader//com.foo.bar.App.run(App.java:12)}"
    314      * - The class of the execution point is defined in the unnamed module of
    315      * the class loader named {@code com.foo.loader}.
    316      * </li>
    317      * <li>
    318      *     "{@code acme@2.1/org.acme.Lib.test(Lib.java:80)}"
    319      * - The class of the execution point is defined in {@code acme} module
    320      * loaded by a built-in class loader such as the application class loader.
    321      * </li>
    322      * <li>
    323      *     "{@code MyClass.mash(MyClass.java:9)}"
    324      * - {@code MyClass} class is on the application class path.
    325      * </li>
    326      * </ul>
    327      *
    328      * <p> The first example shows a stack trace element consisting of
    329      * three elements, each separated by {@code "/"}, followed by
    330      * the source file name and the line number of the source line
    331      * containing the execution point.
    332      *
    333      * The first element "{@code com.foo.loader}" is
    334      * the name of the class loader.  The second element "{@code foo@9.0}"
    335      * is the module name and version.  The third element is the method
    336      * containing the execution point; "{@code com.foo.Main"}" is the
    337      * fully-qualified class name and "{@code run}" is the name of the method.
    338      * "{@code Main.java}" is the source file name and "{@code 101}" is
    339      * the line number.
    340      *
    341      * <p> If a class is defined in an <em>unnamed module</em>
    342      * then the second element is omitted as shown in
    343      * "{@code com.foo.loader//com.foo.bar.App.run(App.java:12)}".
    344      *
    345      * <p> If the class loader is a <a href="ClassLoader.html#builtinLoaders">
    346      * built-in class loader</a> or is not named then the first element
    347      * and its following {@code "/"} are omitted as shown in
    348      * "{@code acme@2.1/org.acme.Lib.test(Lib.java:80)}".
    349      * If the first element is omitted and the module is an unnamed module,
    350      * the second element and its following {@code "/"} are also omitted
    351      * as shown in "{@code MyClass.mash(MyClass.java:9)}".
    352      *
    353      * <p> The {@code toString} method may return two different values on two
    354      * {@code StackTraceElement} instances that are
    355      * {@linkplain #equals(Object) equal}, for example one created via the
    356      * constructor, and one obtained from {@link java.lang.Throwable} or
    357      * {@link java.lang.StackWalker.StackFrame}, where an implementation may
    358      * choose to omit some element in the returned string.
    359      *
    360      * @revised 9
    361      * @spec JPMS
    362      * @see    Throwable#printStackTrace()
    363      */
    364     public String toString() {
    365         String s = "";
    366         if (!dropClassLoaderName() && classLoaderName != null &&
    367                 !classLoaderName.isEmpty()) {
    368             s += classLoaderName + "/";
    369         }
    370         if (moduleName != null && !moduleName.isEmpty()) {
    371             s += moduleName;
    372
    373             if (!dropModuleVersion() && moduleVersion != null &&
    374                     !moduleVersion.isEmpty()) {
    375                 s += "@" + moduleVersion;
    376             }
    377         }
    378         s = s.isEmpty() ? declaringClass : s + "/" + declaringClass;
    379
    380         return s + "." + methodName + "(" +
    381              (isNativeMethod() ? "Native Method)" :
    382               (fileName != null && lineNumber >= 0 ?
    383                fileName + ":" + lineNumber + ")" :
    384                 (fileName != null ?  ""+fileName+")" : "Unknown Source)")));
    385     }
    386
    387     /**
    388      * Returns true if the specified object is another
    389      * {@code StackTraceElement} instance representing the same execution
    390      * point as this instance.  Two stack trace elements {@code a} and
    391      * {@code b} are equal if and only if:
    392      * <pre>{@code
    393      *     equals(a.getClassLoaderName(), b.getClassLoaderName()) &&
    394      *     equals(a.getModuleName(), b.getModuleName()) &&
    395      *     equals(a.getModuleVersion(), b.getModuleVersion()) &&
    396      *     equals(a.getClassName(), b.getClassName()) &&
    397      *     equals(a.getMethodName(), b.getMethodName())
    398      *     equals(a.getFileName(), b.getFileName()) &&
    399      *     a.getLineNumber() == b.getLineNumber()
    400      *
    401      * }</pre>
    402      * where {@code equals} has the semantics of {@link
    403      * java.util.Objects#equals(Object, Object) Objects.equals}.
    404      *
    405      * @param  obj the object to be compared with this stack trace element.
    406      * @return true if the specified object is another
    407      *         {@code StackTraceElement} instance representing the same
    408      *         execution point as this instance.
    409      *
    410      * @revised 9
    411      * @spec JPMS
    412      */
    413     public boolean equals(Object obj) {
    414         if (obj==this)
    415             return true;
    416         if (!(obj instanceof StackTraceElement))
    417             return false;
    418         StackTraceElement e = (StackTraceElement)obj;
    419         return Objects.equals(classLoaderName, e.classLoaderName) &&
    420             Objects.equals(moduleName, e.moduleName) &&
    421             Objects.equals(moduleVersion, e.moduleVersion) &&
    422             e.declaringClass.equals(declaringClass) &&
    423             e.lineNumber == lineNumber &&
    424             Objects.equals(methodName, e.methodName) &&
    425             Objects.equals(fileName, e.fileName);
    426     }
    427
    428     /**
    429      * Returns a hash code value for this stack trace element.
    430      */
    431     public int hashCode() {
    432         int result = 31*declaringClass.hashCode() + methodName.hashCode();
    433         result = 31*result + Objects.hashCode(classLoaderName);
    434         result = 31*result + Objects.hashCode(moduleName);
    435         result = 31*result + Objects.hashCode(moduleVersion);
    436         result = 31*result + Objects.hashCode(fileName);
    437         result = 31*result + lineNumber;
    438         return result;
    439     }
    440
    441
    442     /**
    443      * Called from of() methods to set the 'format' bitmap using the Class
    444      * reference stored in declaringClassObject, and then clear the reference.
    445      *
    446      * <p>
    447      * If the module is a non-upgradeable JDK module, then set
    448      * JDK_NON_UPGRADEABLE_MODULE to omit its version string.
    449      * <p>
    450      * If the loader is one of the built-in loaders (`boot`, `platform`, or `app`)
    451      * then set BUILTIN_CLASS_LOADER to omit the first element (`<loader>/`).
    452      */
    453     private synchronized void computeFormat() {
    454         try {
    455             Class<?> cls = (Class<?>) declaringClassObject;
    456             ClassLoader loader = cls.getClassLoader0();
    457             Module m = cls.getModule();
    458             byte bits = 0;
    459
    460             // First element - class loader name
    461             // Call package-private ClassLoader::name method
    462
    463             if (loader instanceof BuiltinClassLoader) {
    464                 bits |= BUILTIN_CLASS_LOADER;
    465             }
    466
    467             // Second element - module name and version
    468
    469             // Omit if is a JDK non-upgradeable module (recorded in the hashes
    470             // in java.base)
    471             if (isHashedInJavaBase(m)) {
    472                 bits |= JDK_NON_UPGRADEABLE_MODULE;
    473             }
    474             format = bits;
    475         } finally {
    476             // Class reference no longer needed, clear it
    477             declaringClassObject = null;
    478         }
    479     }
    480
    481     private static final byte BUILTIN_CLASS_LOADER       = 0x1;
    482     private static final byte JDK_NON_UPGRADEABLE_MODULE = 0x2;
    483
    484     private boolean dropClassLoaderName() {
    485         return (format & BUILTIN_CLASS_LOADER) == BUILTIN_CLASS_LOADER;
    486     }
    487
    488     private boolean dropModuleVersion() {
    489         return (format & JDK_NON_UPGRADEABLE_MODULE) == JDK_NON_UPGRADEABLE_MODULE;
    490     }
    491
    492     /**
    493      * Returns true if the module is hashed with java.base.
    494      * <p>
    495      * This method returns false when running on the exploded image
    496      * since JDK modules are not hashed. They have no Version attribute
    497      * and so "@<version>" part will be omitted anyway.
    498      */
    499     private static boolean isHashedInJavaBase(Module m) {
    500         // return true if module system is not initialized as the code
    501         // must be in java.base
    502         if (!VM.isModuleSystemInited())
    503             return true;
    504
    505         return ModuleLayer.boot() == m.getLayer() && HashedModules.contains(m);
    506     }
    507
    508     /*
    509      * Finds JDK non-upgradeable modules, i.e. the modules that are
    510      * included in the hashes in java.base.
    511      */
    512     private static class HashedModules {
    513         static Set<String> HASHED_MODULES = hashedModules();
    514
    515         static Set<String> hashedModules() {
    516
    517             Optional<ResolvedModule> resolvedModule = ModuleLayer.boot()
    518                     .configuration()
    519                     .findModule("java.base");
    520             assert resolvedModule.isPresent();
    521             ModuleReference mref = resolvedModule.get().reference();
    522             assert mref instanceof ModuleReferenceImpl;
    523             ModuleHashes hashes = ((ModuleReferenceImpl)mref).recordedHashes();
    524             if (hashes != null) {
    525                 Set<String> names = new HashSet<>(hashes.names());
    526                 names.add("java.base");
    527                 return names;
    528             }
    529
    530             return Set.of();
    531         }
    532
    533         static boolean contains(Module m) {
    534             return HASHED_MODULES.contains(m.getName());
    535         }
    536     }
    537
    538
    539     /*
    540      * Returns an array of StackTraceElements of the given depth
    541      * filled from the backtrace of a given Throwable.
    542      */
    543     static StackTraceElement[] of(Throwable x, int depth) {
    544         StackTraceElement[] stackTrace = new StackTraceElement[depth];
    545         for (int i = 0; i < depth; i++) {
    546             stackTrace[i] = new StackTraceElement();
    547         }
    548
    549         // VM to fill in StackTraceElement
    550         initStackTraceElements(stackTrace, x);
    551
    552         // ensure the proper StackTraceElement initialization
    553         for (StackTraceElement ste : stackTrace) {
    554             ste.computeFormat();
    555         }
    556         return stackTrace;
    557     }
    558
    559     /*
    560      * Returns a StackTraceElement from a given StackFrameInfo.
    561      */
    562     static StackTraceElement of(StackFrameInfo sfi) {
    563         StackTraceElement ste = new StackTraceElement();
    564         initStackTraceElement(ste, sfi);
    565
    566         ste.computeFormat();
    567         return ste;
    568     }
    569
    570     /*
    571      * Sets the given stack trace elements with the backtrace
    572      * of the given Throwable.
    573      */
    574     private static native void initStackTraceElements(StackTraceElement[] elements,
    575                                                       Throwable x);
    576     /*
    577      * Sets the given stack trace element with the given StackFrameInfo
    578      */
    579     private static native void initStackTraceElement(StackTraceElement element,
    580                                                      StackFrameInfo sfi);
    581
    582     @java.io.Serial
    583     private static final long serialVersionUID = 6992337162326171013L;
    584 }
    --- EOF ---