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 import jdk.internal.vm.Continuation;
 33 
 34 import java.lang.module.ModuleDescriptor.Version;
 35 import java.lang.module.ModuleReference;
 36 import java.lang.module.ResolvedModule;
 37 import java.util.HashSet;
 38 import java.util.Objects;
 39 import java.util.Optional;
 40 import java.util.Set;
 41 
 42 /**
 43  * An element in a stack trace, as returned by {@link
 44  * Throwable#getStackTrace()}.  Each element represents a single stack frame.
 45  * All stack frames except for the one at the top of the stack represent
 46  * a method invocation.  The frame at the top of the stack represents the
 47  * execution point at which the stack trace was generated.  Typically,
 48  * this is the point at which the throwable corresponding to the stack trace
 49  * was created.
 50  *
 51  * @since  1.4
 52  * @author Josh Bloch
 53  */
 54 public final class StackTraceElement implements java.io.Serializable {
 55 
 56     // For Throwables and StackWalker, the VM initially sets this field to a
 57     // reference to the declaring Class.  The Class reference is used to
 58     // construct the 'format' bitmap, and then is cleared.
 59     //
 60     // For STEs constructed using the public constructors, this field is not used.
 61     private transient Class<?> declaringClassObject;
 62 
 63     // Normally initialized by VM
 64     /**
 65      * The name of the class loader.
 66      */
 67     private String classLoaderName;
 68     /**
 69      * The module name.
 70      */
 71     private String moduleName;
 72     /**
 73      * The module version.
 74      */
 75     private String moduleVersion;
 76     /**
 77      * The declaring class.
 78      */
 79     private String declaringClass;
 80     /**
 81      * The method name.
 82      */
 83     private String methodName;
 84     /**
 85      * The source file name.
 86      */
 87     private String fileName;
 88     /**
 89      * The contintation name.
 90      */
 91     private String contScopeName;
 92     /**
 93      * The source line number.
 94      */
 95     private int    lineNumber;
 96     /**
 97      * Control to show full or partial module, package, and class names.
 98      */
 99     private byte   format = 0; // Default to show all
100 
101     /**
102      * Creates a stack trace element representing the specified execution
103      * point. The {@link #getModuleName module name} and {@link
104      * #getModuleVersion module version} of the stack trace element will
105      * be {@code null}.
106      *
107      * @param declaringClass the fully qualified name of the class containing
108      *        the execution point represented by the stack trace element
109      * @param methodName the name of the method containing the execution point
110      *        represented by the stack trace element
111      * @param fileName the name of the file containing the execution point
112      *         represented by the stack trace element, or {@code null} if
113      *         this information is unavailable
114      * @param lineNumber the line number of the source line containing the
115      *         execution point represented by this stack trace element, or
116      *         a negative number if this information is unavailable. A value
117      *         of -2 indicates that the method containing the execution point
118      *         is a native method
119      * @throws NullPointerException if {@code declaringClass} or
120      *         {@code methodName} is null
121      * @since 1.5
122      * @revised 9
123      */
124     public StackTraceElement(String declaringClass, String methodName,
125                              String fileName, int lineNumber) {
126         this(null, null, null, declaringClass, methodName, fileName, lineNumber);
127     }
128 
129     /**
130      * Creates a stack trace element representing the specified execution
131      * point.
132      *
133      * @param classLoaderName the class loader name if the class loader of
134      *        the class containing the execution point represented by
135      *        the stack trace is named; otherwise {@code null}
136      * @param moduleName the module name if the class containing the
137      *        execution point represented by the stack trace is in a named
138      *        module; otherwise {@code null}
139      * @param moduleVersion the module version if the class containing the
140      *        execution point represented by the stack trace is in a named
141      *        module that has a version; otherwise {@code null}
142      * @param declaringClass the fully qualified name of the class containing
143      *        the execution point represented by the stack trace element
144      * @param methodName the name of the method containing the execution point
145      *        represented by the stack trace element
146      * @param fileName the name of the file containing the execution point
147      *        represented by the stack trace element, or {@code null} if
148      *        this information is unavailable
149      * @param lineNumber the line number of the source line containing the
150      *        execution point represented by this stack trace element, or
151      *        a negative number if this information is unavailable. A value
152      *        of -2 indicates that the method containing the execution point
153      *        is a native method
154      *
155      * @throws NullPointerException if {@code declaringClass} is {@code null}
156      *         or {@code methodName} is {@code null}
157      *
158      * @since 9
159      */
160     public StackTraceElement(String classLoaderName,
161                              String moduleName, String moduleVersion,
162                              String declaringClass, String methodName,
163                              String fileName, int lineNumber) {
164         this.classLoaderName = classLoaderName;
165         this.moduleName      = moduleName;
166         this.moduleVersion   = moduleVersion;
167         this.declaringClass  = Objects.requireNonNull(declaringClass, "Declaring class is null");
168         this.methodName      = Objects.requireNonNull(methodName, "Method name is null");
169         this.fileName        = fileName;
170         this.lineNumber      = lineNumber;
171     }
172 
173     /*
174      * Private constructor for the factory methods to create StackTraceElement
175      * for Throwable and StackFrameInfo
176      */
177     private StackTraceElement() {}
178 
179     /**
180      * Returns the name of the source file containing the execution point
181      * represented by this stack trace element.  Generally, this corresponds
182      * to the {@code SourceFile} attribute of the relevant {@code class}
183      * file (as per <cite>The Java Virtual Machine Specification</cite>, Section
184      * {@jvms 4.7.7}).  In some systems, the name may refer to some source code unit
185      * other than a file, such as an entry in source repository.
186      *
187      * @return the name of the file containing the execution point
188      *         represented by this stack trace element, or {@code null} if
189      *         this information is unavailable.
190      */
191     public String getFileName() {
192         return fileName;
193     }
194 
195     /**
196      * Returns the line number of the source line containing the execution
197      * point represented by this stack trace element.  Generally, this is
198      * derived from the {@code LineNumberTable} attribute of the relevant
199      * {@code class} file (as per <cite>The Java Virtual Machine
200      * Specification</cite>, Section {@jvms 4.7.8}).
201      *
202      * @return the line number of the source line containing the execution
203      *         point represented by this stack trace element, or a negative
204      *         number if this information is unavailable.
205      */
206     public int getLineNumber() {
207         return lineNumber;
208     }
209 
210     /**
211      * Returns the module name of the module containing the execution point
212      * represented by this stack trace element.
213      *
214      * @return the module name of the {@code Module} containing the execution
215      *         point represented by this stack trace element; {@code null}
216      *         if the module name is not available.
217      * @since 9
218      * @see Module#getName()
219      */
220     public String getModuleName() {
221         return moduleName;
222     }
223 
224     /**
225      * Returns the module version of the module containing the execution point
226      * represented by this stack trace element.
227      *
228      * @return the module version of the {@code Module} containing the execution
229      *         point represented by this stack trace element; {@code null}
230      *         if the module version is not available.
231      * @since 9
232      * @see java.lang.module.ModuleDescriptor.Version
233      */
234     public String getModuleVersion() {
235         return moduleVersion;
236     }
237 
238     /**
239      * Returns the name of the class loader of the class containing the
240      * execution point represented by this stack trace element.
241      *
242      * @return the name of the class loader of the class containing the execution
243      *         point represented by this stack trace element; {@code null}
244      *         if the class loader is not named.
245      *
246      * @since 9
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      * @see    Throwable#printStackTrace()
362      */
363     public String toString() {
364         String s = "";
365         if (!dropClassLoaderName() && classLoaderName != null &&
366                 !classLoaderName.isEmpty()) {
367             s += classLoaderName + "/";
368         }
369         if (moduleName != null && !moduleName.isEmpty()) {
370             s += moduleName;
371 
372             if (!dropModuleVersion() && moduleVersion != null &&
373                     !moduleVersion.isEmpty()) {
374                 s += "@" + moduleVersion;
375             }
376         }
377         s = s.isEmpty() ? declaringClass : s + "/" + declaringClass;
378 
379         s = s + "." + methodName + "(" +
380              (isNativeMethod() ? "Native Method)" :
381               (fileName != null && lineNumber >= 0 ?
382                fileName + ":" + lineNumber + ")" :
383                 (fileName != null ?  ""+fileName+")" : "Unknown Source)")));
384 
385         if (contScopeName != null
386                 && !contScopeName.equals(VirtualThread.continuationScope().getName())
387                 && isContinuationEntry()) {
388             s = s + " " + contScopeName;
389         }
390 
391         return s;
392     }
393 
394     private boolean isContinuationEntry() {
395         return declaringClass.equals(Continuation.class.getName()) && methodName.equals("enter");
396     }
397 
398     /**
399      * Returns true if the specified object is another
400      * {@code StackTraceElement} instance representing the same execution
401      * point as this instance.  Two stack trace elements {@code a} and
402      * {@code b} are equal if and only if:
403      * <pre>{@code
404      *     equals(a.getClassLoaderName(), b.getClassLoaderName()) &&
405      *     equals(a.getModuleName(), b.getModuleName()) &&
406      *     equals(a.getModuleVersion(), b.getModuleVersion()) &&
407      *     equals(a.getClassName(), b.getClassName()) &&
408      *     equals(a.getMethodName(), b.getMethodName())
409      *     equals(a.getFileName(), b.getFileName()) &&
410      *     a.getLineNumber() == b.getLineNumber()
411      *
412      * }</pre>
413      * where {@code equals} has the semantics of {@link
414      * java.util.Objects#equals(Object, Object) Objects.equals}.
415      *
416      * @param  obj the object to be compared with this stack trace element.
417      * @return true if the specified object is another
418      *         {@code StackTraceElement} instance representing the same
419      *         execution point as this instance.
420      *
421      * @revised 9
422      */
423     public boolean equals(Object obj) {
424         if (obj==this)
425             return true;
426         return (obj instanceof StackTraceElement e)
427                 && e.lineNumber == lineNumber
428                 && e.declaringClass.equals(declaringClass)
429                 && Objects.equals(classLoaderName, e.classLoaderName)
430                 && Objects.equals(moduleName, e.moduleName)
431                 && Objects.equals(moduleVersion, e.moduleVersion)
432                 && Objects.equals(methodName, e.methodName)
433                 && Objects.equals(fileName, e.fileName)
434                 && Objects.equals(contScopeName, e.contScopeName);
435     }
436 
437     /**
438      * Returns a hash code value for this stack trace element.
439      */
440     public int hashCode() {
441         int result = 31*declaringClass.hashCode() + methodName.hashCode();
442         result = 31*result + Objects.hashCode(classLoaderName);
443         result = 31*result + Objects.hashCode(moduleName);
444         result = 31*result + Objects.hashCode(moduleVersion);
445         result = 31*result + Objects.hashCode(fileName);
446         result = 31*result + Objects.hashCode(contScopeName);
447         result = 31*result + lineNumber;
448         return result;
449     }
450 
451 
452     /**
453      * Called from of() methods to set the 'format' bitmap using the Class
454      * reference stored in declaringClassObject, and then clear the reference.
455      *
456      * <p>
457      * If the module is a non-upgradeable JDK module, then set
458      * JDK_NON_UPGRADEABLE_MODULE to omit its version string.
459      * <p>
460      * If the loader is one of the built-in loaders (`boot`, `platform`, or `app`)
461      * then set BUILTIN_CLASS_LOADER to omit the first element (`<loader>/`).
462      */
463     private synchronized void computeFormat() {
464         try {
465             Class<?> cls = (Class<?>) declaringClassObject;
466             ClassLoader loader = cls.getClassLoader0();
467             Module m = cls.getModule();
468             byte bits = 0;
469 
470             // First element - class loader name
471             // Call package-private ClassLoader::name method
472 
473             if (loader instanceof BuiltinClassLoader) {
474                 bits |= BUILTIN_CLASS_LOADER;
475             }
476 
477             // Second element - module name and version
478 
479             // Omit if is a JDK non-upgradeable module (recorded in the hashes
480             // in java.base)
481             if (isHashedInJavaBase(m)) {
482                 bits |= JDK_NON_UPGRADEABLE_MODULE;
483             }
484             format = bits;
485         } finally {
486             // Class reference no longer needed, clear it
487             declaringClassObject = null;
488         }
489     }
490 
491     private static final byte BUILTIN_CLASS_LOADER       = 0x1;
492     private static final byte JDK_NON_UPGRADEABLE_MODULE = 0x2;
493 
494     private boolean dropClassLoaderName() {
495         return (format & BUILTIN_CLASS_LOADER) == BUILTIN_CLASS_LOADER;
496     }
497 
498     private boolean dropModuleVersion() {
499         return (format & JDK_NON_UPGRADEABLE_MODULE) == JDK_NON_UPGRADEABLE_MODULE;
500     }
501 
502     /**
503      * Returns true if the module is hashed with java.base.
504      * <p>
505      * This method returns false when running on the exploded image
506      * since JDK modules are not hashed. They have no Version attribute
507      * and so "@<version>" part will be omitted anyway.
508      */
509     private static boolean isHashedInJavaBase(Module m) {
510         // return true if module system is not initialized as the code
511         // must be in java.base
512         if (!VM.isModuleSystemInited())
513             return true;
514 
515         return ModuleLayer.boot() == m.getLayer() && HashedModules.contains(m);
516     }
517 
518     /*
519      * Finds JDK non-upgradeable modules, i.e. the modules that are
520      * included in the hashes in java.base.
521      */
522     private static class HashedModules {
523         static Set<String> HASHED_MODULES = hashedModules();
524 
525         static Set<String> hashedModules() {
526 
527             Optional<ResolvedModule> resolvedModule = ModuleLayer.boot()
528                     .configuration()
529                     .findModule("java.base");
530             assert resolvedModule.isPresent();
531             ModuleReference mref = resolvedModule.get().reference();
532             assert mref instanceof ModuleReferenceImpl;
533             ModuleHashes hashes = ((ModuleReferenceImpl)mref).recordedHashes();
534             if (hashes != null) {
535                 Set<String> names = new HashSet<>(hashes.names());
536                 names.add("java.base");
537                 return names;
538             }
539 
540             return Set.of();
541         }
542 
543         static boolean contains(Module m) {
544             return HASHED_MODULES.contains(m.getName());
545         }
546     }
547 
548 
549     /*
550      * Returns an array of StackTraceElements of the given depth
551      * filled from the given backtrace.
552      */
553     static StackTraceElement[] of(Object x, int depth) {
554         StackTraceElement[] stackTrace = new StackTraceElement[depth];
555         for (int i = 0; i < depth; i++) {
556             stackTrace[i] = new StackTraceElement();
557         }
558 
559         // VM to fill in StackTraceElement
560         initStackTraceElements(stackTrace, x, depth);
561         return of(stackTrace);
562     }
563 
564     /*
565      * Returns a StackTraceElement from a given StackFrameInfo.
566      */
567     static StackTraceElement of(StackFrameInfo sfi) {
568         StackTraceElement ste = new StackTraceElement();
569         initStackTraceElement(ste, sfi);
570 
571         ste.computeFormat();
572         return ste;
573     }
574 
575     static StackTraceElement[] of(StackTraceElement[] stackTrace) {
576         // ensure the proper StackTraceElement initialization
577         for (StackTraceElement ste : stackTrace) {
578             ste.computeFormat();
579         }
580         return stackTrace;
581     }
582 
583     /*
584      * Sets the given stack trace elements with the backtrace
585      * of the given Throwable.
586      */
587     private static native void initStackTraceElements(StackTraceElement[] elements,
588                                                       Object x, int depth);
589     /*
590      * Sets the given stack trace element with the given StackFrameInfo
591      */
592     private static native void initStackTraceElement(StackTraceElement element,
593                                                      StackFrameInfo sfi);
594 
595     @java.io.Serial
596     private static final long serialVersionUID = 6992337162326171013L;
597 }