1 /*
  2  * Copyright (c) 2015, 2021, 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 package java.lang;
 26 
 27 import jdk.internal.reflect.CallerSensitive;
 28 
 29 import java.lang.invoke.MethodType;
 30 import java.util.EnumSet;
 31 import java.util.Objects;
 32 import java.util.Set;
 33 import java.util.function.Consumer;
 34 import java.util.function.Function;
 35 import java.util.stream.Stream;
 36 import jdk.internal.vm.Continuation;
 37 import jdk.internal.vm.ContinuationScope;
 38 
 39 /**
 40  * A stack walker.
 41  *
 42  * <p> The {@link StackWalker#walk walk} method opens a sequential stream
 43  * of {@link StackFrame StackFrame}s for the current thread and then applies
 44  * the given function to walk the {@code StackFrame} stream.
 45  * The stream reports stack frame elements in order, from the top most frame
 46  * that represents the execution point at which the stack was generated to
 47  * the bottom most frame.
 48  * The {@code StackFrame} stream is closed when the {@code walk} method returns.
 49  * If an attempt is made to reuse the closed stream,
 50  * {@code IllegalStateException} will be thrown.
 51  *
 52  * <p> The {@linkplain Option <em>stack walking options</em>} of a
 53  * {@code StackWalker} determines the information of
 54  * {@link StackFrame StackFrame} objects to be returned.
 55  * By default, stack frames of the reflection API and implementation
 56  * classes are {@linkplain Option#SHOW_HIDDEN_FRAMES hidden}
 57  * and {@code StackFrame}s have the class name and method name
 58  * available but not the {@link StackFrame#getDeclaringClass() Class reference}.
 59  *
 60  * <p> {@code StackWalker} is thread-safe. Multiple threads can share
 61  * a single {@code StackWalker} object to traverse its own stack.
 62  * A permission check is performed when a {@code StackWalker} is created,
 63  * according to the options it requests.
 64  * No further permission check is done at stack walking time.
 65  *
 66  * @apiNote
 67  * Examples
 68  *
 69  * <p>1. To find the first caller filtering a known list of implementation class:
 70  * <pre>{@code
 71  *     StackWalker walker = StackWalker.getInstance(Option.RETAIN_CLASS_REFERENCE);
 72  *     Optional<Class<?>> callerClass = walker.walk(s ->
 73  *         s.map(StackFrame::getDeclaringClass)
 74  *          .filter(interestingClasses::contains)
 75  *          .findFirst());
 76  * }</pre>
 77  *
 78  * <p>2. To snapshot the top 10 stack frames of the current thread,
 79  * <pre>{@code
 80  *     List<StackFrame> stack = StackWalker.getInstance().walk(s ->
 81  *         s.limit(10).collect(Collectors.toList()));
 82  * }</pre>
 83  *
 84  * Unless otherwise noted, passing a {@code null} argument to a
 85  * constructor or method in this {@code StackWalker} class
 86  * will cause a {@link NullPointerException NullPointerException}
 87  * to be thrown.
 88  *
 89  * @since 9
 90  */
 91 public final class StackWalker {
 92     /**
 93      * A {@code StackFrame} object represents a method invocation returned by
 94      * {@link StackWalker}.
 95      *
 96      * <p> The {@link #getDeclaringClass()} method may be unsupported as determined
 97      * by the {@linkplain Option stack walking options} of a {@linkplain
 98      * StackWalker stack walker}.
 99      *
100      * @since 9
101      * @jvms 2.6
102      */
103     public interface StackFrame {
104         /**
105          * Gets the <a href="ClassLoader.html#binary-name">binary name</a>
106          * of the declaring class of the method represented by this stack frame.
107          *
108          * @return the binary name of the declaring class of the method
109          *         represented by this stack frame
110          *
111          * @jls 13.1 The Form of a Binary
112          */
113         public String getClassName();
114 
115         /**
116          * Gets the name of the method represented by this stack frame.
117          * @return the name of the method represented by this stack frame
118          */
119         public String getMethodName();
120 
121         /**
122          * Gets the declaring {@code Class} for the method represented by
123          * this stack frame.
124          *
125          * @return the declaring {@code Class} of the method represented by
126          * this stack frame
127          *
128          * @throws UnsupportedOperationException if this {@code StackWalker}
129          *         is not configured with {@link Option#RETAIN_CLASS_REFERENCE
130          *         Option.RETAIN_CLASS_REFERENCE}.
131          */
132         public Class<?> getDeclaringClass();
133 
134         /**
135          * Returns the {@link MethodType} representing the parameter types and
136          * the return type for the method represented by this stack frame.
137          *
138          * @implSpec
139          * The default implementation throws {@code UnsupportedOperationException}.
140          *
141          * @return the {@code MethodType} for this stack frame
142          *
143          * @throws UnsupportedOperationException if this {@code StackWalker}
144          *         is not configured with {@link Option#RETAIN_CLASS_REFERENCE
145          *         Option.RETAIN_CLASS_REFERENCE}.
146          *
147          * @since 10
148          */
149         public default MethodType getMethodType() {
150             throw new UnsupportedOperationException();
151         }
152 
153         /**
154          * Returns the <i>descriptor</i> of the method represented by
155          * this stack frame as defined by
156          * <cite>The Java Virtual Machine Specification</cite>.
157          *
158          * @implSpec
159          * The default implementation throws {@code UnsupportedOperationException}.
160          *
161          * @return the descriptor of the method represented by
162          *         this stack frame
163          *
164          * @see MethodType#fromMethodDescriptorString(String, ClassLoader)
165          * @see MethodType#toMethodDescriptorString()
166          * @jvms 4.3.3 Method Descriptor
167          *
168          * @since 10
169          */
170         public default String getDescriptor() {
171             throw new UnsupportedOperationException();
172         }
173 
174 
175         /**
176          * Returns the index to the code array of the {@code Code} attribute
177          * containing the execution point represented by this stack frame.
178          * The code array gives the actual bytes of Java Virtual Machine code
179          * that implement the method.
180          *
181          * @return the index to the code array of the {@code Code} attribute
182          *         containing the execution point represented by this stack frame,
183          *         or a negative number if the method is native.
184          *
185          * @jvms 4.7.3 The {@code Code} Attribute
186          */
187         public int getByteCodeIndex();
188 
189         /**
190          * Returns the name of the source file containing the execution point
191          * represented by this stack frame.  Generally, this corresponds
192          * to the {@code SourceFile} attribute of the relevant {@code class}
193          * file as defined by <cite>The Java Virtual Machine Specification</cite>.
194          * In some systems, the name may refer to some source code unit
195          * other than a file, such as an entry in a source repository.
196          *
197          * @return the name of the file containing the execution point
198          *         represented by this stack frame, or {@code null} if
199          *         this information is unavailable.
200          *
201          * @jvms 4.7.10 The {@code SourceFile} Attribute
202          */
203         public String getFileName();
204 
205         /**
206          * Returns the line number of the source line containing the execution
207          * point represented by this stack frame.  Generally, this is
208          * derived from the {@code LineNumberTable} attribute of the relevant
209          * {@code class} file as defined by <cite>The Java Virtual Machine
210          * Specification</cite>.
211          *
212          * @return the line number of the source line containing the execution
213          *         point represented by this stack frame, or a negative number if
214          *         this information is unavailable.
215          *
216          * @jvms 4.7.12 The {@code LineNumberTable} Attribute
217          */
218         public int getLineNumber();
219 
220         /**
221          * Returns {@code true} if the method containing the execution point
222          * represented by this stack frame is a native method.
223          *
224          * @return {@code true} if the method containing the execution point
225          *         represented by this stack frame is a native method.
226          */
227         public boolean isNativeMethod();
228 
229         /**
230          * Returns the name of the {@link ContinuationScope} of the continuation 
231          * (if any) in which this frame exists.
232          * 
233          * @return the name of the {@link ContinuationScope} of the continuation 
234          *         in which this frame exists or {@code null} if this frame is 
235          *         not in a continuation.
236          */
237         public default String getContinuationScopeName() {
238             return null;
239         }
240 
241         /**
242          * Gets a {@code StackTraceElement} for this stack frame.
243          *
244          * @return {@code StackTraceElement} for this stack frame.
245          */
246         public StackTraceElement toStackTraceElement();
247     }
248 
249     /**
250      * Stack walker option to configure the {@linkplain StackFrame stack frame}
251      * information obtained by a {@code StackWalker}.
252      *
253      * @since 9
254      */
255     public enum Option {
256         /**
257          * Retains {@code Class} object in {@code StackFrame}s
258          * walked by this {@code StackWalker}.
259          *
260          * <p> A {@code StackWalker} configured with this option will support
261          * {@link StackWalker#getCallerClass()} and
262          * {@link StackFrame#getDeclaringClass() StackFrame.getDeclaringClass()}.
263          */
264         RETAIN_CLASS_REFERENCE,
265         /**
266          * Shows all reflection frames.
267          *
268          * <p>By default, reflection frames are hidden.  A {@code StackWalker}
269          * configured with this {@code SHOW_REFLECT_FRAMES} option
270          * will show all reflection frames that
271          * include {@link java.lang.reflect.Method#invoke} and
272          * {@link java.lang.reflect.Constructor#newInstance(Object...)}
273          * and their reflection implementation classes.
274          *
275          * <p>The {@link #SHOW_HIDDEN_FRAMES} option can also be used to show all
276          * reflection frames and it will also show other hidden frames that
277          * are implementation-specific.
278          *
279          * @apiNote
280          * This option includes the stack frames representing the invocation of
281          * {@code Method} and {@code Constructor}.  Any utility methods that
282          * are equivalent to calling {@code Method.invoke} or
283          * {@code Constructor.newInstance} such as {@code Class.newInstance}
284          * are not filtered or controlled by any stack walking option.
285          */
286         SHOW_REFLECT_FRAMES,
287         /**
288          * Shows all hidden frames.
289          *
290          * <p>A Java Virtual Machine implementation may hide implementation
291          * specific frames in addition to {@linkplain #SHOW_REFLECT_FRAMES
292          * reflection frames}. A {@code StackWalker} with this {@code SHOW_HIDDEN_FRAMES}
293          * option will show all hidden frames (including reflection frames).
294          */
295         SHOW_HIDDEN_FRAMES,
296     }
297 
298     enum ExtendedOption {
299         /**
300          * Obtain monitors, locals and operands.
301          */
302         LOCALS_AND_OPERANDS
303     };
304 
305     static final EnumSet<Option> DEFAULT_EMPTY_OPTION = EnumSet.noneOf(Option.class);
306 
307     private static final StackWalker DEFAULT_WALKER =
308         new StackWalker(DEFAULT_EMPTY_OPTION);
309 
310     private final Continuation continuation;
311     private final ContinuationScope contScope;
312     private final Set<Option> options;
313     private final ExtendedOption extendedOption;
314     private final int estimateDepth;
315     final boolean retainClassRef; // cached for performance
316 
317     /**
318      * Returns a {@code StackWalker} instance.
319      *
320      * <p> This {@code StackWalker} is configured to skip all
321      * {@linkplain Option#SHOW_HIDDEN_FRAMES hidden frames} and
322      * no {@linkplain Option#RETAIN_CLASS_REFERENCE class reference} is retained.
323      *
324      * @return a {@code StackWalker} configured to skip all
325      * {@linkplain Option#SHOW_HIDDEN_FRAMES hidden frames} and
326      * no {@linkplain Option#RETAIN_CLASS_REFERENCE class reference} is retained.
327      *
328      */
329     public static StackWalker getInstance() {
330         // no permission check needed
331         return DEFAULT_WALKER;
332     }
333 
334     /**
335      * Returns a {@code StackWalker} instance.
336      *
337      * <p> This {@code StackWalker} is configured to skip all
338      * {@linkplain Option#SHOW_HIDDEN_FRAMES hidden frames} and
339      * no {@linkplain Option#RETAIN_CLASS_REFERENCE class reference} is retained.
340      * 
341      * @param contScope the continuation scope up to which (inclusive) to walk the stack
342      * 
343      * @return a {@code StackWalker} configured to skip all
344      * {@linkplain Option#SHOW_HIDDEN_FRAMES hidden frames} and
345      * no {@linkplain Option#RETAIN_CLASS_REFERENCE class reference} is retained.
346      *
347      */
348     static StackWalker getInstance(ContinuationScope contScope) {
349         return getInstance(EnumSet.noneOf(Option.class), contScope);
350     }
351 
352     /**
353      * Returns a {@code StackWalker} instance with the given option specifying
354      * the stack frame information it can access.
355      *
356      * <p>
357      * If a security manager is present and the given {@code option} is
358      * {@link Option#RETAIN_CLASS_REFERENCE Option.RETAIN_CLASS_REFERENCE},
359      * it calls its {@link SecurityManager#checkPermission checkPermission}
360      * method for {@code RuntimePermission("getStackWalkerWithClassReference")}.
361      *
362      * @param option {@link Option stack walking option}
363      *
364      * @return a {@code StackWalker} configured with the given option
365      *
366      * @throws SecurityException if a security manager exists and its
367      *         {@code checkPermission} method denies access.
368      */
369     public static StackWalker getInstance(Option option) {
370         return getInstance(EnumSet.of(Objects.requireNonNull(option)));
371     }
372 
373    /**
374      * Returns a {@code StackWalker} instance with the given option specifying
375      * the stack frame information it can access.
376      *
377      * <p>
378      * If a security manager is present and the given {@code option} is
379      * {@link Option#RETAIN_CLASS_REFERENCE Option.RETAIN_CLASS_REFERENCE},
380      * it calls its {@link SecurityManager#checkPermission checkPermission}
381      * method for {@code RuntimePermission("getStackWalkerWithClassReference")}.
382      *
383      * @param option {@link Option stack walking option}
384      * @param contScope the continuation scope up to which (inclusive) to walk the stack
385      *
386      * @return a {@code StackWalker} configured with the given option
387      *
388      * @throws SecurityException if a security manager exists and its
389      *         {@code checkPermission} method denies access.
390      */
391     static StackWalker getInstance(Option option, ContinuationScope contScope) {
392         return getInstance(EnumSet.of(Objects.requireNonNull(option)), contScope);
393     }
394 
395     /**
396      * Returns a {@code StackWalker} instance with the given {@code options} specifying
397      * the stack frame information it can access.  If the given {@code options}
398      * is empty, this {@code StackWalker} is configured to skip all
399      * {@linkplain Option#SHOW_HIDDEN_FRAMES hidden frames} and no
400      * {@linkplain Option#RETAIN_CLASS_REFERENCE class reference} is retained.
401      *
402      * <p>
403      * If a security manager is present and the given {@code options} contains
404      * {@link Option#RETAIN_CLASS_REFERENCE Option.RETAIN_CLASS_REFERENCE},
405      * it calls its {@link SecurityManager#checkPermission checkPermission}
406      * method for {@code RuntimePermission("getStackWalkerWithClassReference")}.
407      *
408      * @param options {@link Option stack walking option}
409      *
410      * @return a {@code StackWalker} configured with the given options
411      *
412      * @throws SecurityException if a security manager exists and its
413      *         {@code checkPermission} method denies access.
414      */
415     public static StackWalker getInstance(Set<Option> options) {
416         return getInstance(options, null);
417     }
418 
419     /**
420      * Returns a {@code StackWalker} instance with the given {@code options} specifying
421      * the stack frame information it can access.  If the given {@code options}
422      * is empty, this {@code StackWalker} is configured to skip all
423      * {@linkplain Option#SHOW_HIDDEN_FRAMES hidden frames} and no
424      * {@linkplain Option#RETAIN_CLASS_REFERENCE class reference} is retained.
425      *
426      * <p>
427      * If a security manager is present and the given {@code options} contains
428      * {@link Option#RETAIN_CLASS_REFERENCE Option.RETAIN_CLASS_REFERENCE},
429      * it calls its {@link SecurityManager#checkPermission checkPermission}
430      * method for {@code RuntimePermission("getStackWalkerWithClassReference")}.
431      *
432      * @param options {@link Option stack walking option}
433      * @param contScope the continuation scope up to which (inclusive) to walk the stack
434      *
435      * @return a {@code StackWalker} configured with the given options
436      *
437      * @throws SecurityException if a security manager exists and its
438      *         {@code checkPermission} method denies access.
439      */
440     static StackWalker getInstance(Set<Option> options, ContinuationScope contScope) {
441         if (options.isEmpty() && contScope == null) {
442             return DEFAULT_WALKER;
443         }
444 
445         EnumSet<Option> optionSet = toEnumSet(options);
446         checkPermission(optionSet);
447         return new StackWalker(optionSet, contScope);
448     }
449 
450     /**
451      * Returns a {@code StackWalker} instance with the given {@code options} specifying
452      * the stack frame information it can access. If the given {@code options}
453      * is empty, this {@code StackWalker} is configured to skip all
454      * {@linkplain Option#SHOW_HIDDEN_FRAMES hidden frames} and no
455      * {@linkplain Option#RETAIN_CLASS_REFERENCE class reference} is retained.
456      *
457      * <p>
458      * If a security manager is present and the given {@code options} contains
459      * {@link Option#RETAIN_CLASS_REFERENCE Option.RETAIN_CLASS_REFERENCE},
460      * it calls its {@link SecurityManager#checkPermission checkPermission}
461      * method for {@code RuntimePermission("getStackWalkerWithClassReference")}.
462      *
463      * <p>
464      * The {@code estimateDepth} specifies the estimate number of stack frames
465      * this {@code StackWalker} will traverse that the {@code StackWalker} could
466      * use as a hint for the buffer size.
467      *
468      * @param options {@link Option stack walking options}
469      * @param estimateDepth Estimate number of stack frames to be traversed.
470      *
471      * @return a {@code StackWalker} configured with the given options
472      *
473      * @throws IllegalArgumentException if {@code estimateDepth <= 0}
474      * @throws SecurityException if a security manager exists and its
475      *         {@code checkPermission} method denies access.
476      */
477     public static StackWalker getInstance(Set<Option> options, int estimateDepth) {
478         if (estimateDepth <= 0) {
479             throw new IllegalArgumentException("estimateDepth must be > 0");
480         }
481         EnumSet<Option> optionSet = toEnumSet(options);
482         checkPermission(optionSet);
483         return new StackWalker(optionSet, estimateDepth);
484     }
485 
486     // ----- private constructors ------
487     private StackWalker(EnumSet<Option> options) {
488         this(options, 0, null, null, null);
489     }
490     private StackWalker(EnumSet<Option> options, ContinuationScope contScope) {
491         this(options, 0, null, contScope, null);
492     }
493     private StackWalker(EnumSet<Option> options, ContinuationScope contScope, Continuation continuation) {
494         this(options, 0, null, contScope, continuation);
495     }
496     private StackWalker(EnumSet<Option> options, int estimateDepth) {
497         this(options, estimateDepth, null, null, null);
498     }
499     private StackWalker(EnumSet<Option> options, int estimateDepth, ContinuationScope contScope) {
500         this(options, estimateDepth, null, contScope, null);
501     }
502     private StackWalker(EnumSet<Option> options,
503                         int estimateDepth,
504                         ContinuationScope contScope,
505                         Continuation continuation) {
506         this(options, estimateDepth, null, contScope, continuation);
507     }
508     private StackWalker(EnumSet<Option> options,
509                         int estimateDepth,
510                         ExtendedOption extendedOption,
511                         ContinuationScope contScope,
512                         Continuation continuation) {
513         this.options = options;
514         this.estimateDepth = estimateDepth;
515         this.extendedOption = extendedOption;
516         this.retainClassRef = hasOption(Option.RETAIN_CLASS_REFERENCE);
517         this.contScope = contScope;
518         this.continuation = continuation;
519     }
520 
521     private static void checkPermission(Set<Option> options) {
522         Objects.requireNonNull(options);
523         @SuppressWarnings("removal")
524         SecurityManager sm = System.getSecurityManager();
525         if (sm != null) {
526             if (options.contains(Option.RETAIN_CLASS_REFERENCE)) {
527                 sm.checkPermission(new RuntimePermission("getStackWalkerWithClassReference"));
528             }
529         }
530     }
531 
532     /*
533      * Returns a defensive copy
534      */
535     private static EnumSet<Option> toEnumSet(Set<Option> options) {
536         Objects.requireNonNull(options);
537         if (options.isEmpty()) {
538             return DEFAULT_EMPTY_OPTION;
539         } else {
540             return EnumSet.copyOf(options);
541         }
542     }
543 
544     /**
545      * Applies the given function to the stream of {@code StackFrame}s
546      * for the current thread, traversing from the top frame of the stack,
547      * which is the method calling this {@code walk} method.
548      *
549      * <p>The {@code StackFrame} stream will be closed when
550      * this method returns.  When a closed {@code Stream<StackFrame>} object
551      * is reused, {@code IllegalStateException} will be thrown.
552      *
553      * @apiNote
554      * For example, to find the first 10 calling frames, first skipping those frames
555      * whose declaring class is in package {@code com.foo}:
556      * <blockquote>
557      * <pre>{@code
558      * List<StackFrame> frames = StackWalker.getInstance().walk(s ->
559      *     s.dropWhile(f -> f.getClassName().startsWith("com.foo."))
560      *      .limit(10)
561      *      .collect(Collectors.toList()));
562      * }</pre></blockquote>
563      *
564      * <p>This method takes a {@code Function} accepting a {@code Stream<StackFrame>},
565      * rather than returning a {@code Stream<StackFrame>} and allowing the
566      * caller to directly manipulate the stream. The Java virtual machine is
567      * free to reorganize a thread's control stack, for example, via
568      * deoptimization. By taking a {@code Function} parameter, this method
569      * allows access to stack frames through a stable view of a thread's control
570      * stack.
571      *
572      * <p>Parallel execution is effectively disabled and stream pipeline
573      * execution will only occur on the current thread.
574      *
575      * @implNote The implementation stabilizes the stack by anchoring a frame
576      * specific to the stack walking and ensures that the stack walking is
577      * performed above the anchored frame. When the stream object is closed or
578      * being reused, {@code IllegalStateException} will be thrown.
579      *
580      * @param function a function that takes a stream of
581      *                 {@linkplain StackFrame stack frames} and returns a result.
582      * @param <T> The type of the result of applying the function to the
583      *            stream of {@linkplain StackFrame stack frame}.
584      *
585      * @return the result of applying the function to the stream of
586      *         {@linkplain StackFrame stack frame}.
587      */
588     @CallerSensitive
589     public <T> T walk(Function<? super Stream<StackFrame>, ? extends T> function) {
590         // Returning a Stream<StackFrame> would be unsafe, as the stream could
591         // be used to access the stack frames in an uncontrolled manner.  For
592         // example, a caller might pass a Spliterator of stack frames after one
593         // or more frames had been traversed. There is no robust way to detect
594         // whether the execution point when
595         // Spliterator.tryAdvance(java.util.function.Consumer<? super T>) is
596         // invoked is the exact same execution point where the stack frame
597         // traversal is expected to resume.
598 
599         Objects.requireNonNull(function);
600         return StackStreamFactory.makeStackTraverser(this, function)
601                                  .walk();
602     }
603 
604     /**
605      * Performs the given action on each element of {@code StackFrame} stream
606      * of the current thread, traversing from the top frame of the stack,
607      * which is the method calling this {@code forEach} method.
608      *
609      * <p> This method is equivalent to calling
610      * <blockquote>
611      * {@code walk(s -> { s.forEach(action); return null; });}
612      * </blockquote>
613      *
614      * @param action an action to be performed on each {@code StackFrame}
615      *               of the stack of the current thread
616      */
617     @CallerSensitive
618     public void forEach(Consumer<? super StackFrame> action) {
619         Objects.requireNonNull(action);
620         StackStreamFactory.makeStackTraverser(this, s -> {
621             s.forEach(action);
622             return null;
623         }).walk();
624     }
625 
626     /**
627      * Gets the {@code Class} object of the caller who invoked the method
628      * that invoked {@code getCallerClass}.
629      *
630      * <p> This method filters {@linkplain Option#SHOW_REFLECT_FRAMES reflection
631      * frames}, {@link java.lang.invoke.MethodHandle}, and
632      * {@linkplain Option#SHOW_HIDDEN_FRAMES hidden frames} regardless of the
633      * {@link Option#SHOW_REFLECT_FRAMES SHOW_REFLECT_FRAMES}
634      * and {@link Option#SHOW_HIDDEN_FRAMES SHOW_HIDDEN_FRAMES} options
635      * this {@code StackWalker} has been configured with.
636      *
637      * <p> This method should be called when a caller frame is present.  If
638      * it is called from the bottom most frame on the stack,
639      * {@code IllegalCallerException} will be thrown.
640      *
641      * <p> This method throws {@code UnsupportedOperationException}
642      * if this {@code StackWalker} is not configured with the
643      * {@link Option#RETAIN_CLASS_REFERENCE RETAIN_CLASS_REFERENCE} option.
644      *
645      * @apiNote
646      * For example, {@code Util::getResourceBundle} loads a resource bundle
647      * on behalf of the caller.  It invokes {@code getCallerClass} to identify
648      * the class whose method called {@code Util::getResourceBundle}.
649      * Then, it obtains the class loader of that class, and uses
650      * the class loader to load the resource bundle. The caller class
651      * in this example is {@code MyTool}.
652      *
653      * <pre>{@code
654      * class Util {
655      *     private final StackWalker walker = StackWalker.getInstance(Option.RETAIN_CLASS_REFERENCE);
656      *     public ResourceBundle getResourceBundle(String bundleName) {
657      *         Class<?> caller = walker.getCallerClass();
658      *         return ResourceBundle.getBundle(bundleName, Locale.getDefault(), caller.getClassLoader());
659      *     }
660      * }
661      *
662      * class MyTool {
663      *     private final Util util = new Util();
664      *     private void init() {
665      *         ResourceBundle rb = util.getResourceBundle("mybundle");
666      *     }
667      * }
668      * }</pre>
669      *
670      * An equivalent way to find the caller class using the
671      * {@link StackWalker#walk walk} method is as follows
672      * (filtering the reflection frames, {@code MethodHandle} and hidden frames
673      * not shown below):
674      * <pre>{@code
675      *     Optional<Class<?>> caller = walker.walk(s ->
676      *         s.map(StackFrame::getDeclaringClass)
677      *          .skip(2)
678      *          .findFirst());
679      * }</pre>
680      *
681      * When the {@code getCallerClass} method is called from a method that
682      * is the bottom most frame on the stack,
683      * for example, {@code static public void main} method launched by the
684      * {@code java} launcher, or a method invoked from a JNI attached thread,
685      * {@code IllegalCallerException} is thrown.
686      *
687      * @return {@code Class} object of the caller's caller invoking this method.
688      *
689      * @throws UnsupportedOperationException if this {@code StackWalker}
690      *         is not configured with {@link Option#RETAIN_CLASS_REFERENCE
691      *         Option.RETAIN_CLASS_REFERENCE}.
692      * @throws IllegalCallerException if there is no caller frame, i.e.
693      *         when this {@code getCallerClass} method is called from a method
694      *         which is the last frame on the stack.
695      */
696     @CallerSensitive
697     public Class<?> getCallerClass() {
698         if (!retainClassRef) {
699             throw new UnsupportedOperationException("This stack walker " +
700                     "does not have RETAIN_CLASS_REFERENCE access");
701         }
702         if (continuation != null) {
703             throw new UnsupportedOperationException("This stack walker walks a continuation");
704         }
705 
706         return StackStreamFactory.makeCallerFinder(this).findCaller();
707     }
708 
709     // ---- package access ----
710 
711     static StackWalker newInstance(Set<Option> options, ExtendedOption extendedOption) {
712         return newInstance(options, extendedOption, null);
713     }
714 
715     static StackWalker newInstance(Set<Option> options, ExtendedOption extendedOption, ContinuationScope contScope) {
716         EnumSet<Option> optionSet = toEnumSet(options);
717         checkPermission(optionSet);
718         return new StackWalker(optionSet, 0, extendedOption, contScope, null);
719     }
720 
721     static StackWalker newInstance(Set<Option> options, ExtendedOption extendedOption, ContinuationScope contScope, Continuation continuation) {
722         EnumSet<Option> optionSet = toEnumSet(options);
723         checkPermission(optionSet);
724         return new StackWalker(optionSet, 0, extendedOption, contScope, continuation);
725     }
726 
727     int estimateDepth() {
728         return estimateDepth;
729     }
730 
731     boolean hasOption(Option option) {
732         return options.contains(option);
733     }
734 
735     boolean hasLocalsOperandsOption() {
736         return extendedOption == ExtendedOption.LOCALS_AND_OPERANDS;
737     }
738 
739     ContinuationScope getContScope() {
740         return contScope;
741     }
742 
743     Continuation getContinuation() {
744         return continuation;
745     }
746 }