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