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