1 /* 2 * Copyright (c) 2015, 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 sun.reflect.CallerSensitive; 28 29 import java.util.*; 30 import java.util.function.Consumer; 31 import java.util.function.Function; 32 import java.util.stream.Stream; 33 34 /** 35 * A stack walker. 36 * 37 * <p> The {@link StackWalker#walk walk} method opens a sequential stream 38 * of {@link StackFrame StackFrame}s for the current thread and then applies 39 * the given function to walk the {@code StackFrame} stream. 40 * The stream reports stack frame elements in order, from the top most frame 41 * that represents the execution point at which the stack was generated to 42 * the bottom most frame. 43 * The {@code StackFrame} stream is closed when the {@code walk} method returns. 44 * If an attempt is made to reuse the closed stream, 45 * {@code IllegalStateException} will be thrown. 46 * 47 * <p> The {@linkplain Option <em>stack walking options</em>} of a 48 * {@code StackWalker} determines the information of 49 * {@link StackFrame StackFrame} objects to be returned. 50 * By default, stack frames of the reflection API and implementation 51 * classes are {@linkplain Option#SHOW_HIDDEN_FRAMES hidden} 52 * and {@code StackFrame}s have the class name and method name 53 * available but not the {@link StackFrame#getDeclaringClass() Class reference}. 54 * 55 * <p> {@code StackWalker} is thread-safe. Multiple threads can share 56 * a single {@code StackWalker} object to traverse its own stack. 57 * A permission check is performed when a {@code StackWalker} is created, 58 * according to the options it requests. 59 * No further permission check is done at stack walking time. 60 * 61 * @apiNote 62 * Examples 63 * 64 * <p>1. To find the first caller filtering a known list of implementation class: 65 * <pre>{@code 66 * StackWalker walker = StackWalker.getInstance(Option.RETAIN_CLASS_REFERENCE); 67 * Optional<Class<?>> callerClass = walker.walk(s -> 68 * s.map(StackFrame::getDeclaringClass) 69 * .filter(interestingClasses::contains) 70 * .findFirst()); 71 * }</pre> 72 * 73 * <p>2. To snapshot the top 10 stack frames of the current thread, 74 * <pre>{@code 75 * List<StackFrame> stack = StackWalker.getInstance().walk(s -> 76 * s.limit(10).collect(Collectors.toList())); 77 * }</pre> 78 * 79 * Unless otherwise noted, passing a {@code null} argument to a 80 * constructor or method in this {@code StackWalker} class 81 * will cause a {@link NullPointerException NullPointerException} 82 * to be thrown. 83 * 84 * @since 9 85 */ 86 public final class StackWalker { 87 /** 88 * A {@code StackFrame} object represents a method invocation returned by 89 * {@link StackWalker}. 90 * 91 * <p> The {@link #getDeclaringClass()} method may be unsupported as determined 92 * by the {@linkplain Option stack walking options} of a {@linkplain 93 * StackWalker stack walker}. 94 * 95 * @since 9 96 * @jvms 2.6 97 */ 98 public static interface StackFrame { 99 /** 100 * Gets the <a href="ClassLoader.html#name">binary name</a> 101 * of the declaring class of the method represented by this stack frame. 102 * 103 * @return the binary name of the declaring class of the method 104 * represented by this stack frame 105 * 106 * @jls 13.1 The Form of a Binary 107 */ 108 public String getClassName(); 109 110 /** 111 * Gets the name of the method represented by this stack frame. 112 * @return the name of the method represented by this stack frame 113 */ 114 public String getMethodName(); 115 116 /** 117 * Gets the declaring {@code Class} for the method represented by 118 * this stack frame. 119 * 120 * @return the declaring {@code Class} of the method represented by 121 * this stack frame 122 * 123 * @throws UnsupportedOperationException if this {@code StackWalker} 124 * is not configured with {@link Option#RETAIN_CLASS_REFERENCE 125 * Option.RETAIN_CLASS_REFERENCE}. 126 */ 127 public Class<?> getDeclaringClass(); 128 129 /** 130 * Returns the name of the source file containing the execution point 131 * represented by this stack frame. Generally, this corresponds 132 * to the {@code SourceFile} attribute of the relevant {@code class} 133 * file as defined by <cite>The Java Virtual Machine Specification</cite>. 134 * In some systems, the name may refer to some source code unit 135 * other than a file, such as an entry in a source repository. 136 * 137 * @return the name of the file containing the execution point 138 * represented by this stack frame, or empty {@code Optional} 139 * is unavailable. 140 * 141 * @jvms 4.7.10 The {@code SourceFile} Attribute 142 */ 143 public Optional<String> getFileName(); 144 145 /** 146 * Returns the line number of the source line containing the execution 147 * point represented by this stack frame. Generally, this is 148 * derived from the {@code LineNumberTable} attribute of the relevant 149 * {@code class} file as defined by <cite>The Java Virtual Machine 150 * Specification</cite>. 151 * 152 * @return the line number of the source line containing the execution 153 * point represented by this stack frame, or empty 154 * {@code Optional} if this information is unavailable. 155 * 156 * @jvms 4.7.12 The {@code LineNumberTable} Attribute 157 */ 158 public OptionalInt getLineNumber(); 159 160 /** 161 * Returns {@code true} if the method containing the execution point 162 * represented by this stack frame is a native method. 163 * 164 * @return {@code true} if the method containing the execution point 165 * represented by this stack frame is a native method. 166 */ 167 public boolean isNativeMethod(); 168 169 /** 170 * Gets a {@code StackTraceElement} for this stack frame. 171 * 172 * @return {@code StackTraceElement} for this stack frame. 173 */ 174 public StackTraceElement toStackTraceElement(); 175 } 176 177 /** 178 * Stack walker option to configure the {@linkplain StackFrame stack frame} 179 * information obtained by a {@code StackWalker}. 180 * 181 * @since 9 182 */ 183 public enum Option { 184 /** 185 * Retains {@code Class} object in {@code StackFrame}s 186 * walked by this {@code StackWalker}. 187 * 188 * <p> A {@code StackWalker} configured with this option will support 189 * {@link StackWalker#getCallerClass()} and 190 * {@link StackFrame#getDeclaringClass() StackFrame.getDeclaringClass()}. 191 */ 192 RETAIN_CLASS_REFERENCE, 193 /** 194 * Shows all reflection frames. 195 * 196 * <p>By default, reflection frames are hidden. This includes the 197 * {@link java.lang.reflect.Method#invoke} method 198 * and the reflection implementation classes. A {@code StackWalker} with 199 * this {@code SHOW_REFLECT_FRAMES} option will show all reflection frames. 200 * The {@link #SHOW_HIDDEN_FRAMES} option can also be used to show all 201 * reflection frames and it will also show other hidden frames that 202 * are implementation-specific. 203 */ 204 SHOW_REFLECT_FRAMES, 205 /** 206 * Shows all hidden frames. 207 * 208 * <p>A Java Virtual Machine implementation may hide implementation 209 * specific frames in addition to {@linkplain #SHOW_REFLECT_FRAMES 210 * reflection frames}. A {@code StackWalker} with this {@code SHOW_HIDDEN_FRAMES} 211 * option will show all hidden frames (including reflection frames). 212 */ 213 SHOW_HIDDEN_FRAMES; 214 } 215 216 enum ExtendedOption { 217 /** 218 * Obtain monitors, locals and operands. 219 */ 220 LOCALS_AND_OPERANDS 221 }; 222 223 static final EnumSet<Option> DEFAULT_EMPTY_OPTION = EnumSet.noneOf(Option.class); 224 225 private final static StackWalker DEFAULT_WALKER = 226 new StackWalker(DEFAULT_EMPTY_OPTION); 227 228 private final Set<Option> options; 229 private final ExtendedOption extendedOption; 230 private final int estimateDepth; 231 232 /** 233 * Returns a {@code StackWalker} instance. 234 * 235 * <p> This {@code StackWalker} is configured to skip all 236 * {@linkplain Option#SHOW_HIDDEN_FRAMES hidden frames} and 237 * no {@linkplain Option#RETAIN_CLASS_REFERENCE class reference} is retained. 238 * 239 * @return a {@code StackWalker} configured to skip all 240 * {@linkplain Option#SHOW_HIDDEN_FRAMES hidden frames} and 241 * no {@linkplain Option#RETAIN_CLASS_REFERENCE class reference} is retained. 242 * 243 */ 244 public static StackWalker getInstance() { 245 // no permission check needed 246 return DEFAULT_WALKER; 247 } 248 249 /** 250 * Returns a {@code StackWalker} instance with the given option specifying 251 * the stack frame information it can access. 252 * 253 * <p> 254 * If a security manager is present and the given {@code option} is 255 * {@link Option#RETAIN_CLASS_REFERENCE Option.RETAIN_CLASS_REFERENCE}, 256 * it calls its {@link SecurityManager#checkPermission checkPermission} 257 * method for {@code StackFramePermission("retainClassReference")}. 258 * 259 * @param option {@link Option stack walking option} 260 * 261 * @return a {@code StackWalker} configured with the given option 262 * 263 * @throws SecurityException if a security manager exists and its 264 * {@code checkPermission} method denies access. 265 */ 266 public static StackWalker getInstance(Option option) { 267 return getInstance(EnumSet.of(Objects.requireNonNull(option))); 268 } 269 270 /** 271 * Returns a {@code StackWalker} instance with the given {@code options} specifying 272 * the stack frame information it can access. If the given {@code options} 273 * is empty, this {@code StackWalker} is configured to skip all 274 * {@linkplain Option#SHOW_HIDDEN_FRAMES hidden frames} and no 275 * {@linkplain Option#RETAIN_CLASS_REFERENCE class reference} is retained. 276 * 277 * <p> 278 * If a security manager is present and the given {@code options} contains 279 * {@link Option#RETAIN_CLASS_REFERENCE Option.RETAIN_CLASS_REFERENCE}, 280 * it calls its {@link SecurityManager#checkPermission checkPermission} 281 * method for {@code StackFramePermission("retainClassReference")}. 282 * 283 * @param options {@link Option stack walking option} 284 * 285 * @return a {@code StackWalker} configured with the given options 286 * 287 * @throws SecurityException if a security manager exists and its 288 * {@code checkPermission} method denies access. 289 */ 290 public static StackWalker getInstance(Set<Option> options) { 291 if (options.isEmpty()) { 292 return DEFAULT_WALKER; 293 } 294 295 checkPermission(options); 296 return new StackWalker(toEnumSet(options)); 297 } 298 299 /** 300 * Returns a {@code StackWalker} instance with the given {@code options} specifying 301 * the stack frame information it can access. If the given {@code options} 302 * is empty, this {@code StackWalker} is configured to skip all 303 * {@linkplain Option#SHOW_HIDDEN_FRAMES hidden frames} and no 304 * {@linkplain Option#RETAIN_CLASS_REFERENCE class reference} is retained. 305 * 306 * <p> 307 * If a security manager is present and the given {@code options} contains 308 * {@link Option#RETAIN_CLASS_REFERENCE Option.RETAIN_CLASS_REFERENCE}, 309 * it calls its {@link SecurityManager#checkPermission checkPermission} 310 * method for {@code StackFramePermission("retainClassReference")}. 311 * 312 * <p> 313 * The {@code estimateDepth} specifies the estimate number of stack frames 314 * this {@code StackWalker} will traverse that the {@code StackWalker} could 315 * use as a hint for the buffer size. 316 * 317 * @param options {@link Option stack walking options} 318 * @param estimateDepth Estimate number of stack frames to be traversed. 319 * 320 * @return a {@code StackWalker} configured with the given options 321 * 322 * @throws IllegalArgumentException if {@code estimateDepth <= 0} 323 * @throws SecurityException if a security manager exists and its 324 * {@code checkPermission} method denies access. 325 */ 326 public static StackWalker getInstance(Set<Option> options, int estimateDepth) { 327 if (estimateDepth <= 0) { 328 throw new IllegalArgumentException("estimateDepth must be > 0"); 329 } 330 checkPermission(options); 331 return new StackWalker(toEnumSet(options), estimateDepth); 332 } 333 334 // ----- private constructors ------ 335 private StackWalker(EnumSet<Option> options) { 336 this(options, 0, null); 337 } 338 private StackWalker(EnumSet<Option> options, int estimateDepth) { 339 this(options, estimateDepth, null); 340 } 341 private StackWalker(EnumSet<Option> options, int estimateDepth, ExtendedOption extendedOption) { 342 this.options = options; 343 this.estimateDepth = estimateDepth; 344 this.extendedOption = extendedOption; 345 } 346 347 private static void checkPermission(Set<Option> options) { 348 Objects.requireNonNull(options); 349 SecurityManager sm = System.getSecurityManager(); 350 if (sm != null) { 351 if (options.contains(Option.RETAIN_CLASS_REFERENCE)) { 352 sm.checkPermission(new StackFramePermission("retainClassReference")); 353 } 354 } 355 } 356 357 /* 358 * Returns a defensive copy 359 */ 360 private static EnumSet<Option> toEnumSet(Set<Option> options) { 361 Objects.requireNonNull(options); 362 if (options.isEmpty()) { 363 return DEFAULT_EMPTY_OPTION; 364 } else { 365 return EnumSet.copyOf(options); 366 } 367 } 368 369 /** 370 * Applies the given function to the stream of {@code StackFrame}s 371 * for the current thread, traversing from the top frame of the stack, 372 * which is the method calling this {@code walk} method. 373 * 374 * <p>The {@code StackFrame} stream will be closed when 375 * this method returns. When a closed {@code Stream<StackFrame>} object 376 * is reused, {@code IllegalStateException} will be thrown. 377 * 378 * @apiNote 379 * For example, to find the first 10 calling frames, first skipping those frames 380 * whose declaring class is in package {@code com.foo}: 381 * <blockquote> 382 * <pre>{@code 383 * List<StackFrame> frames = StackWalker.getInstance().walk(s -> 384 * s.dropWhile(f -> f.getClassName().startsWith("com.foo.")) 385 * .limit(10) 386 * .collect(Collectors.toList())); 387 * }</pre></blockquote> 388 * 389 * <p>This method takes a {@code Function} accepting a {@code Stream<StackFrame>}, 390 * rather than returning a {@code Stream<StackFrame>} and allowing the 391 * caller to directly manipulate the stream. The Java virtual machine is 392 * free to reorganize a thread's control stack, for example, via 393 * deoptimization. By taking a {@code Function} parameter, this method 394 * allows access to stack frames through a stable view of a thread's control 395 * stack. 396 * 397 * <p>Parallel execution is effectively disabled and stream pipeline 398 * execution will only occur on the current thread. 399 * 400 * @implNote The implementation stabilizes the stack by anchoring a frame 401 * specific to the stack walking and ensures that the stack walking is 402 * performed above the anchored frame. When the stream object is closed or 403 * being reused, {@code IllegalStateException} will be thrown. 404 * 405 * @param function a function that takes a stream of 406 * {@linkplain StackFrame stack frames} and returns a result. 407 * @param <T> The type of the result of applying the function to the 408 * stream of {@linkplain StackFrame stack frame}. 409 * 410 * @return the result of applying the function to the stream of 411 * {@linkplain StackFrame stack frame}. 412 */ 413 @CallerSensitive 414 public <T> T walk(Function<? super Stream<StackFrame>, ? extends T> function) { 415 // Returning a Stream<StackFrame> would be unsafe, as the stream could 416 // be used to access the stack frames in an uncontrolled manner. For 417 // example, a caller might pass a Spliterator of stack frames after one 418 // or more frames had been traversed. There is no robust way to detect 419 // whether the execution point when 420 // Spliterator.tryAdvance(java.util.function.Consumer<? super T>) is 421 // invoked is the exact same execution point where the stack frame 422 // traversal is expected to resume. 423 424 Objects.requireNonNull(function); 425 return StackStreamFactory.makeStackTraverser(this, function) 426 .walk(); 427 } 428 429 /** 430 * Performs the given action on each element of {@code StackFrame} stream 431 * of the current thread, traversing from the top frame of the stack, 432 * which is the method calling this {@code forEach} method. 433 * 434 * <p> This method is equivalent to calling 435 * <blockquote> 436 * {@code walk(s -> { s.forEach(action); return null; });} 437 * </blockquote> 438 * 439 * @param action an action to be performed on each {@code StackFrame} 440 * of the stack of the current thread 441 */ 442 @CallerSensitive 443 public void forEach(Consumer<? super StackFrame> action) { 444 Objects.requireNonNull(action); 445 StackStreamFactory.makeStackTraverser(this, s -> { 446 s.forEach(action); 447 return null; 448 }).walk(); 449 } 450 451 /** 452 * Gets the {@code Class} object of the caller invoking the method 453 * that calls this {@code getCallerClass} method. 454 * 455 * <p> Reflection frames, {@link java.lang.invoke.MethodHandle} and 456 * hidden frames are filtered regardless of the 457 * {@link Option#SHOW_REFLECT_FRAMES SHOW_REFLECT_FRAMES} 458 * and {@link Option#SHOW_HIDDEN_FRAMES SHOW_HIDDEN_FRAMES} options 459 * this {@code StackWalker} has been configured. 460 * 461 * <p> This method throws {@code UnsupportedOperationException} 462 * if this {@code StackWalker} is not configured with 463 * {@link Option#RETAIN_CLASS_REFERENCE RETAIN_CLASS_REFERENCE} option, 464 * This method should be called when a caller frame is present. If 465 * it is called from the last frame on the stack; 466 * {@code IllegalStateException} will be thrown. 467 * 468 * @apiNote 469 * For example, {@code Util::getResourceBundle} loads a resource bundle 470 * on behalf of the caller. It calls this {@code getCallerClass} method 471 * to find the method calling {@code Util::getResourceBundle} and use the caller's 472 * class loader to load the resource bundle. The caller class in this example 473 * is the {@code MyTool} class. 474 * 475 * <pre>{@code 476 * class Util { 477 * private final StackWalker walker = StackWalker.getInstance(Option.RETAIN_CLASS_REFERENCE); 478 * public ResourceBundle getResourceBundle(String bundleName) { 479 * Class<?> caller = walker.getCallerClass(); 480 * return ResourceBundle.getBundle(bundleName, Locale.getDefault(), caller.getClassLoader()); 481 * } 482 * } 483 * 484 * class MyTool { 485 * private final Util util = new Util(); 486 * private void init() { 487 * ResourceBundle rb = util.getResourceBundle("mybundle"); 488 * } 489 * } 490 * }</pre> 491 * 492 * An equivalent way to find the caller class using the 493 * {@link StackWalker#walk walk} method is as follows 494 * (filtering the reflection frames, {@code MethodHandle} and hidden frames 495 * not shown below): 496 * <pre>{@code 497 * Optional<Class<?>> caller = walker.walk(s -> 498 * s.map(StackFrame::getDeclaringClass) 499 * .skip(2) 500 * .findFirst()); 501 * }</pre> 502 * 503 * When the {@code getCallerClass} method is called from a method that 504 * is the last frame on the stack, 505 * for example, {@code static public void main} method launched by the 506 * {@code java} launcher or a method invoked from a JNI attached thread. 507 * {@code IllegalStateException} is thrown. 508 * 509 * @return {@code Class} object of the caller's caller invoking this method. 510 * 511 * @throws UnsupportedOperationException if this {@code StackWalker} 512 * is not configured with {@link Option#RETAIN_CLASS_REFERENCE 513 * Option.RETAIN_CLASS_REFERENCE}. 514 * @throws IllegalStateException if there is no caller frame, i.e. 515 * when this {@code getCallerClass} method is called from a method 516 * which is the last frame on the stack. 517 */ 518 @CallerSensitive 519 public Class<?> getCallerClass() { 520 if (!options.contains(Option.RETAIN_CLASS_REFERENCE)) { 521 throw new UnsupportedOperationException("This stack walker " + 522 "does not have RETAIN_CLASS_REFERENCE access"); 523 } 524 525 return StackStreamFactory.makeCallerFinder(this).findCaller(); 526 } 527 528 // ---- package access ---- 529 static StackWalker newInstanceNoCheck(EnumSet<Option> options) { 530 return new StackWalker(options, 0, null); 531 } 532 533 static StackWalker newInstance(Set<Option> options, ExtendedOption extendedOption) { 534 checkPermission(options); 535 return new StackWalker(toEnumSet(options), 0, extendedOption); 536 } 537 538 int estimateDepth() { 539 return estimateDepth; 540 } 541 542 boolean hasOption(Option option) { 543 return options.contains(option); 544 } 545 546 boolean hasLocalsOperandsOption() { 547 return extendedOption == ExtendedOption.LOCALS_AND_OPERANDS; 548 } 549 550 void ensureAccessEnabled(Option access) { 551 if (!hasOption(access)) { 552 throw new UnsupportedOperationException("No access to " + access + 553 ": " + options.toString()); 554 } 555 } 556 }