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