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