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          * Gets a {@code StackTraceElement} for this stack frame.
231          *
232          * @return {@code StackTraceElement} for this stack frame.
233          */
234         public StackTraceElement toStackTraceElement();
235     }
236 
237     /**
238      * Stack walker option to configure the {@linkplain StackFrame stack frame}
239      * information obtained by a {@code StackWalker}.
240      *
241      * @since 9
242      */
243     public enum Option {
244         /**
245          * Retains {@code Class} object in {@code StackFrame}s
246          * walked by this {@code StackWalker}.
247          *
248          * <p> A {@code StackWalker} configured with this option will support
249          * {@link StackWalker#getCallerClass()} and
250          * {@link StackFrame#getDeclaringClass() StackFrame.getDeclaringClass()}.
251          */
252         RETAIN_CLASS_REFERENCE,
253         /**
254          * Shows all reflection frames.
255          *
256          * <p>By default, reflection frames are hidden.  A {@code StackWalker}
257          * configured with this {@code SHOW_REFLECT_FRAMES} option
258          * will show all reflection frames that
259          * include {@link java.lang.reflect.Method#invoke} and
260          * {@link java.lang.reflect.Constructor#newInstance(Object...)}
261          * and their reflection implementation classes.
262          *
263          * <p>The {@link #SHOW_HIDDEN_FRAMES} option can also be used to show all
264          * reflection frames and it will also show other hidden frames that
265          * are implementation-specific.
266          *
267          * @apiNote
268          * This option includes the stack frames representing the invocation of
269          * {@code Method} and {@code Constructor}.  Any utility methods that
270          * are equivalent to calling {@code Method.invoke} or
271          * {@code Constructor.newInstance} such as {@code Class.newInstance}
272          * are not filtered or controlled by any stack walking option.
273          */
274         SHOW_REFLECT_FRAMES,
275         /**
276          * Shows all hidden frames.
277          *
278          * <p>A Java Virtual Machine implementation may hide implementation
279          * specific frames in addition to {@linkplain #SHOW_REFLECT_FRAMES
280          * reflection frames}. A {@code StackWalker} with this {@code SHOW_HIDDEN_FRAMES}
281          * option will show all hidden frames (including reflection frames).
282          */
283         SHOW_HIDDEN_FRAMES,
284     }
285 
286     enum ExtendedOption {
287         /**
288          * Obtain monitors, locals and operands.
289          */
290         LOCALS_AND_OPERANDS
291     };
292 
293     static final EnumSet<Option> DEFAULT_EMPTY_OPTION = EnumSet.noneOf(Option.class);
294 
295     private static final StackWalker DEFAULT_WALKER =
296         new StackWalker(DEFAULT_EMPTY_OPTION);
297 
298     private final Continuation continuation;
299     private final ContinuationScope contScope;
300     private final Set<Option> options;
301     private final ExtendedOption extendedOption;
302     private final int estimateDepth;
303     final boolean retainClassRef; // cached for performance
304 
305     /**
306      * Returns a {@code StackWalker} instance.
307      *
308      * <p> This {@code StackWalker} is configured to skip all
309      * {@linkplain Option#SHOW_HIDDEN_FRAMES hidden frames} and
310      * no {@linkplain Option#RETAIN_CLASS_REFERENCE class reference} is retained.
311      *
312      * @return a {@code StackWalker} configured to skip all
313      * {@linkplain Option#SHOW_HIDDEN_FRAMES hidden frames} and
314      * no {@linkplain Option#RETAIN_CLASS_REFERENCE class reference} is retained.
315      *
316      */
317     public static StackWalker getInstance() {
318         // no permission check needed
319         return DEFAULT_WALKER;
320     }
321 
322     /**
323      * Returns a {@code StackWalker} instance.
324      *
325      * <p> This {@code StackWalker} is configured to skip all
326      * {@linkplain Option#SHOW_HIDDEN_FRAMES hidden frames} and
327      * no {@linkplain Option#RETAIN_CLASS_REFERENCE class reference} is retained.
328      * 
329      * @param contScope the continuation scope up to which (inclusive) to walk the stack
330      * 
331      * @return a {@code StackWalker} configured to skip all
332      * {@linkplain Option#SHOW_HIDDEN_FRAMES hidden frames} and
333      * no {@linkplain Option#RETAIN_CLASS_REFERENCE class reference} is retained.
334      *
335      */
336     static StackWalker getInstance(ContinuationScope contScope) {
337         return getInstance(EnumSet.noneOf(Option.class), contScope);
338     }
339 
340     /**
341      * Returns a {@code StackWalker} instance with the given option specifying
342      * the stack frame information it can access.
343      *
344      * <p>
345      * If a security manager is present and the given {@code option} is
346      * {@link Option#RETAIN_CLASS_REFERENCE Option.RETAIN_CLASS_REFERENCE},
347      * it calls its {@link SecurityManager#checkPermission checkPermission}
348      * method for {@code RuntimePermission("getStackWalkerWithClassReference")}.
349      *
350      * @param option {@link Option stack walking option}
351      *
352      * @return a {@code StackWalker} configured with the given option
353      *
354      * @throws SecurityException if a security manager exists and its
355      *         {@code checkPermission} method denies access.
356      */
357     public static StackWalker getInstance(Option option) {
358         return getInstance(EnumSet.of(Objects.requireNonNull(option)));
359     }
360 
361    /**
362      * Returns a {@code StackWalker} instance with the given option specifying
363      * the stack frame information it can access.
364      *
365      * <p>
366      * If a security manager is present and the given {@code option} is
367      * {@link Option#RETAIN_CLASS_REFERENCE Option.RETAIN_CLASS_REFERENCE},
368      * it calls its {@link SecurityManager#checkPermission checkPermission}
369      * method for {@code RuntimePermission("getStackWalkerWithClassReference")}.
370      *
371      * @param option {@link Option stack walking option}
372      * @param contScope the continuation scope up to which (inclusive) to walk the stack
373      *
374      * @return a {@code StackWalker} configured with the given option
375      *
376      * @throws SecurityException if a security manager exists and its
377      *         {@code checkPermission} method denies access.
378      */
379     static StackWalker getInstance(Option option, ContinuationScope contScope) {
380         return getInstance(EnumSet.of(Objects.requireNonNull(option)), contScope);
381     }
382 
383     /**
384      * Returns a {@code StackWalker} instance with the given {@code options} specifying
385      * the stack frame information it can access.  If the given {@code options}
386      * is empty, this {@code StackWalker} is configured to skip all
387      * {@linkplain Option#SHOW_HIDDEN_FRAMES hidden frames} and no
388      * {@linkplain Option#RETAIN_CLASS_REFERENCE class reference} is retained.
389      *
390      * <p>
391      * If a security manager is present and the given {@code options} contains
392      * {@link Option#RETAIN_CLASS_REFERENCE Option.RETAIN_CLASS_REFERENCE},
393      * it calls its {@link SecurityManager#checkPermission checkPermission}
394      * method for {@code RuntimePermission("getStackWalkerWithClassReference")}.
395      *
396      * @param options {@link Option stack walking option}
397      *
398      * @return a {@code StackWalker} configured with the given options
399      *
400      * @throws SecurityException if a security manager exists and its
401      *         {@code checkPermission} method denies access.
402      */
403     public static StackWalker getInstance(Set<Option> options) {
404         return getInstance(options, null);
405     }
406 
407     /**
408      * Returns a {@code StackWalker} instance with the given {@code options} specifying
409      * the stack frame information it can access.  If the given {@code options}
410      * is empty, this {@code StackWalker} is configured to skip all
411      * {@linkplain Option#SHOW_HIDDEN_FRAMES hidden frames} and no
412      * {@linkplain Option#RETAIN_CLASS_REFERENCE class reference} is retained.
413      *
414      * <p>
415      * If a security manager is present and the given {@code options} contains
416      * {@link Option#RETAIN_CLASS_REFERENCE Option.RETAIN_CLASS_REFERENCE},
417      * it calls its {@link SecurityManager#checkPermission checkPermission}
418      * method for {@code RuntimePermission("getStackWalkerWithClassReference")}.
419      *
420      * @param options {@link Option stack walking option}
421      * @param contScope the continuation scope up to which (inclusive) to walk the stack
422      *
423      * @return a {@code StackWalker} configured with the given options
424      *
425      * @throws SecurityException if a security manager exists and its
426      *         {@code checkPermission} method denies access.
427      */
428     static StackWalker getInstance(Set<Option> options, ContinuationScope contScope) {
429         if (options.isEmpty() && contScope == null) {
430             return DEFAULT_WALKER;
431         }
432 
433         EnumSet<Option> optionSet = toEnumSet(options);
434         checkPermission(optionSet);
435         return new StackWalker(optionSet, contScope);
436     }
437 
438     /**
439      * Returns a {@code StackWalker} instance with the given {@code options} specifying
440      * the stack frame information it can access. If the given {@code options}
441      * is empty, this {@code StackWalker} is configured to skip all
442      * {@linkplain Option#SHOW_HIDDEN_FRAMES hidden frames} and no
443      * {@linkplain Option#RETAIN_CLASS_REFERENCE class reference} is retained.
444      *
445      * <p>
446      * If a security manager is present and the given {@code options} contains
447      * {@link Option#RETAIN_CLASS_REFERENCE Option.RETAIN_CLASS_REFERENCE},
448      * it calls its {@link SecurityManager#checkPermission checkPermission}
449      * method for {@code RuntimePermission("getStackWalkerWithClassReference")}.
450      *
451      * <p>
452      * The {@code estimateDepth} specifies the estimate number of stack frames
453      * this {@code StackWalker} will traverse that the {@code StackWalker} could
454      * use as a hint for the buffer size.
455      *
456      * @param options {@link Option stack walking options}
457      * @param estimateDepth Estimate number of stack frames to be traversed.
458      *
459      * @return a {@code StackWalker} configured with the given options
460      *
461      * @throws IllegalArgumentException if {@code estimateDepth <= 0}
462      * @throws SecurityException if a security manager exists and its
463      *         {@code checkPermission} method denies access.
464      */
465     public static StackWalker getInstance(Set<Option> options, int estimateDepth) {
466         if (estimateDepth <= 0) {
467             throw new IllegalArgumentException("estimateDepth must be > 0");
468         }
469         EnumSet<Option> optionSet = toEnumSet(options);
470         checkPermission(optionSet);
471         return new StackWalker(optionSet, estimateDepth);
472     }
473 
474     // ----- private constructors ------
475     private StackWalker(EnumSet<Option> options) {
476         this(options, 0, null, null, null);
477     }
478     private StackWalker(EnumSet<Option> options, ContinuationScope contScope) {
479         this(options, 0, null, contScope, null);
480     }
481     private StackWalker(EnumSet<Option> options, ContinuationScope contScope, Continuation continuation) {
482         this(options, 0, null, contScope, continuation);
483     }
484     private StackWalker(EnumSet<Option> options, int estimateDepth) {
485         this(options, estimateDepth, null, null, null);
486     }
487     private StackWalker(EnumSet<Option> options, int estimateDepth, ContinuationScope contScope) {
488         this(options, estimateDepth, null, contScope, null);
489     }
490     private StackWalker(EnumSet<Option> options,
491                         int estimateDepth,
492                         ContinuationScope contScope,
493                         Continuation continuation) {
494         this(options, estimateDepth, null, contScope, continuation);
495     }
496     private StackWalker(EnumSet<Option> options,
497                         int estimateDepth,
498                         ExtendedOption extendedOption,
499                         ContinuationScope contScope,
500                         Continuation continuation) {
501         this.options = options;
502         this.estimateDepth = estimateDepth;
503         this.extendedOption = extendedOption;
504         this.retainClassRef = hasOption(Option.RETAIN_CLASS_REFERENCE);
505         this.contScope = contScope;
506         this.continuation = continuation;
507     }
508 
509     private static void checkPermission(Set<Option> options) {
510         Objects.requireNonNull(options);
511         @SuppressWarnings("removal")
512         SecurityManager sm = System.getSecurityManager();
513         if (sm != null) {
514             if (options.contains(Option.RETAIN_CLASS_REFERENCE)) {
515                 sm.checkPermission(new RuntimePermission("getStackWalkerWithClassReference"));
516             }
517         }
518     }
519 
520     /*
521      * Returns a defensive copy
522      */
523     private static EnumSet<Option> toEnumSet(Set<Option> options) {
524         Objects.requireNonNull(options);
525         if (options.isEmpty()) {
526             return DEFAULT_EMPTY_OPTION;
527         } else {
528             return EnumSet.copyOf(options);
529         }
530     }
531 
532     /**
533      * Applies the given function to the stream of {@code StackFrame}s
534      * for the current thread, traversing from the top frame of the stack,
535      * which is the method calling this {@code walk} method.
536      *
537      * <p>The {@code StackFrame} stream will be closed when
538      * this method returns.  When a closed {@code Stream<StackFrame>} object
539      * is reused, {@code IllegalStateException} will be thrown.
540      *
541      * @apiNote
542      * For example, to find the first 10 calling frames, first skipping those frames
543      * whose declaring class is in package {@code com.foo}:
544      * <blockquote>
545      * <pre>{@code
546      * List<StackFrame> frames = StackWalker.getInstance().walk(s ->
547      *     s.dropWhile(f -> f.getClassName().startsWith("com.foo."))
548      *      .limit(10)
549      *      .collect(Collectors.toList()));
550      * }</pre></blockquote>
551      *
552      * <p>This method takes a {@code Function} accepting a {@code Stream<StackFrame>},
553      * rather than returning a {@code Stream<StackFrame>} and allowing the
554      * caller to directly manipulate the stream. The Java virtual machine is
555      * free to reorganize a thread's control stack, for example, via
556      * deoptimization. By taking a {@code Function} parameter, this method
557      * allows access to stack frames through a stable view of a thread's control
558      * stack.
559      *
560      * <p>Parallel execution is effectively disabled and stream pipeline
561      * execution will only occur on the current thread.
562      *
563      * @implNote The implementation stabilizes the stack by anchoring a frame
564      * specific to the stack walking and ensures that the stack walking is
565      * performed above the anchored frame. When the stream object is closed or
566      * being reused, {@code IllegalStateException} will be thrown.
567      *
568      * @param function a function that takes a stream of
569      *                 {@linkplain StackFrame stack frames} and returns a result.
570      * @param <T> The type of the result of applying the function to the
571      *            stream of {@linkplain StackFrame stack frame}.
572      *
573      * @return the result of applying the function to the stream of
574      *         {@linkplain StackFrame stack frame}.
575      */
576     @CallerSensitive
577     public <T> T walk(Function<? super Stream<StackFrame>, ? extends T> function) {
578         // Returning a Stream<StackFrame> would be unsafe, as the stream could
579         // be used to access the stack frames in an uncontrolled manner.  For
580         // example, a caller might pass a Spliterator of stack frames after one
581         // or more frames had been traversed. There is no robust way to detect
582         // whether the execution point when
583         // Spliterator.tryAdvance(java.util.function.Consumer<? super T>) is
584         // invoked is the exact same execution point where the stack frame
585         // traversal is expected to resume.
586 
587         Objects.requireNonNull(function);
588         return StackStreamFactory.makeStackTraverser(this, function)
589                                  .walk();
590     }
591 
592     /**
593      * Performs the given action on each element of {@code StackFrame} stream
594      * of the current thread, traversing from the top frame of the stack,
595      * which is the method calling this {@code forEach} method.
596      *
597      * <p> This method is equivalent to calling
598      * <blockquote>
599      * {@code walk(s -> { s.forEach(action); return null; });}
600      * </blockquote>
601      *
602      * @param action an action to be performed on each {@code StackFrame}
603      *               of the stack of the current thread
604      */
605     @CallerSensitive
606     public void forEach(Consumer<? super StackFrame> action) {
607         Objects.requireNonNull(action);
608         StackStreamFactory.makeStackTraverser(this, s -> {
609             s.forEach(action);
610             return null;
611         }).walk();
612     }
613 
614     /**
615      * Gets the {@code Class} object of the caller who invoked the method
616      * that invoked {@code getCallerClass}.
617      *
618      * <p> This method filters {@linkplain Option#SHOW_REFLECT_FRAMES reflection
619      * frames}, {@link java.lang.invoke.MethodHandle}, and
620      * {@linkplain Option#SHOW_HIDDEN_FRAMES hidden frames} regardless of the
621      * {@link Option#SHOW_REFLECT_FRAMES SHOW_REFLECT_FRAMES}
622      * and {@link Option#SHOW_HIDDEN_FRAMES SHOW_HIDDEN_FRAMES} options
623      * this {@code StackWalker} has been configured with.
624      *
625      * <p> This method should be called when a caller frame is present.  If
626      * it is called from the bottom most frame on the stack,
627      * {@code IllegalCallerException} will be thrown.
628      *
629      * <p> This method throws {@code UnsupportedOperationException}
630      * if this {@code StackWalker} is not configured with the
631      * {@link Option#RETAIN_CLASS_REFERENCE RETAIN_CLASS_REFERENCE} option.
632      *
633      * @apiNote
634      * For example, {@code Util::getResourceBundle} loads a resource bundle
635      * on behalf of the caller.  It invokes {@code getCallerClass} to identify
636      * the class whose method called {@code Util::getResourceBundle}.
637      * Then, it obtains the class loader of that class, and uses
638      * the class loader to load the resource bundle. The caller class
639      * in this example is {@code MyTool}.
640      *
641      * <pre>{@code
642      * class Util {
643      *     private final StackWalker walker = StackWalker.getInstance(Option.RETAIN_CLASS_REFERENCE);
644      *     public ResourceBundle getResourceBundle(String bundleName) {
645      *         Class<?> caller = walker.getCallerClass();
646      *         return ResourceBundle.getBundle(bundleName, Locale.getDefault(), caller.getClassLoader());
647      *     }
648      * }
649      *
650      * class MyTool {
651      *     private final Util util = new Util();
652      *     private void init() {
653      *         ResourceBundle rb = util.getResourceBundle("mybundle");
654      *     }
655      * }
656      * }</pre>
657      *
658      * An equivalent way to find the caller class using the
659      * {@link StackWalker#walk walk} method is as follows
660      * (filtering the reflection frames, {@code MethodHandle} and hidden frames
661      * not shown below):
662      * <pre>{@code
663      *     Optional<Class<?>> caller = walker.walk(s ->
664      *         s.map(StackFrame::getDeclaringClass)
665      *          .skip(2)
666      *          .findFirst());
667      * }</pre>
668      *
669      * When the {@code getCallerClass} method is called from a method that
670      * is the bottom most frame on the stack,
671      * for example, {@code static public void main} method launched by the
672      * {@code java} launcher, or a method invoked from a JNI attached thread,
673      * {@code IllegalCallerException} is thrown.
674      *
675      * @return {@code Class} object of the caller's caller invoking this method.
676      *
677      * @throws UnsupportedOperationException if this {@code StackWalker}
678      *         is not configured with {@link Option#RETAIN_CLASS_REFERENCE
679      *         Option.RETAIN_CLASS_REFERENCE}.
680      * @throws IllegalCallerException if there is no caller frame, i.e.
681      *         when this {@code getCallerClass} method is called from a method
682      *         which is the last frame on the stack.
683      */
684     @CallerSensitive
685     public Class<?> getCallerClass() {
686         if (!retainClassRef) {
687             throw new UnsupportedOperationException("This stack walker " +
688                     "does not have RETAIN_CLASS_REFERENCE access");
689         }
690         if (continuation != null) {
691             throw new UnsupportedOperationException("This stack walker walks a continuation");
692         }
693 
694         return StackStreamFactory.makeCallerFinder(this).findCaller();
695     }
696 
697     // ---- package access ----
698 
699     static StackWalker newInstance(Set<Option> options, ExtendedOption extendedOption) {
700         return newInstance(options, extendedOption, null);
701     }
702 
703     static StackWalker newInstance(Set<Option> options, ExtendedOption extendedOption, ContinuationScope contScope) {
704         EnumSet<Option> optionSet = toEnumSet(options);
705         checkPermission(optionSet);
706         return new StackWalker(optionSet, 0, extendedOption, contScope, null);
707     }
708 
709     static StackWalker newInstance(Set<Option> options, ExtendedOption extendedOption, ContinuationScope contScope, Continuation continuation) {
710         EnumSet<Option> optionSet = toEnumSet(options);
711         checkPermission(optionSet);
712         return new StackWalker(optionSet, 0, extendedOption, contScope, continuation);
713     }
714 
715     int estimateDepth() {
716         return estimateDepth;
717     }
718 
719     boolean hasOption(Option option) {
720         return options.contains(option);
721     }
722 
723     boolean hasLocalsOperandsOption() {
724         return extendedOption == ExtendedOption.LOCALS_AND_OPERANDS;
725     }
726 
727     ContinuationScope getContScope() {
728         return contScope;
729     }
730 
731     Continuation getContinuation() {
732         return continuation;
733     }
734 }