java.lang.StackWalker.StackFrame Java Examples

The following examples show how to use java.lang.StackWalker.StackFrame. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: StackStreamFactory.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
@Override
public boolean tryAdvance(Consumer<? super StackFrame> action) {
    checkState(OPEN);

    int index = frameBuffer.getIndex();
    if (hasNext()) {
        StackFrame frame = nextStackFrame();
        action.accept(frame);
        if (isDebug) {
            System.err.println("tryAdvance: " + index + " " + frame);
        }
        return true;
    }
    if (isDebug) {
        System.err.println("tryAdvance: " + index + " NO element");
    }
    return false;
}
 
Example #2
Source File: Basic.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public boolean accept(StackFrame f) {
    // Frames whose class names don't contain "."
    // are our own test frames. These are the ones
    // we expect.
    // Frames whose class names contain ".reflect."
    // are reflection frames. None should be present,
    // since they are supposed to be filtered by
    // by StackWalker. If we find any, we want to fail.
    if (!f.getClassName().contains(".")
        || f.getClassName().contains(".reflect.")) {
        System.out.println("    " + f);
        return true;
    }
    // Filter out all other frames (in particular
    // those from the test framework) in order to
    // have predictable results.
    return false;
}
 
Example #3
Source File: StackStreamFactory.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean tryAdvance(Consumer<? super StackFrame> action) {
    checkState(OPEN);

    int index = frameBuffer.getIndex();
    if (hasNext()) {
        StackFrame frame = nextStackFrame();
        action.accept(frame);
        if (isDebug) {
            System.err.println("tryAdvance: " + index + " " + frame);
        }
        return true;
    }
    if (isDebug) {
        System.err.println("tryAdvance: " + index + " NO element");
    }
    return false;
}
 
Example #4
Source File: LocalsAndOperands.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private static void usedLong(long longArg) throws Exception {
    StackFrame[] frames = extendedWalker.walk(s ->
        s.filter(f -> "usedLong".equals(f.getMethodName()))
         .toArray(StackFrame[]::new)
    );
    try {
        dumpFramesIfDebug(frames);

        Object[] locals = (Object[]) getLocals.invoke(frames[0]);
        assertLongIsInSlots(locals[0], locals[1], longArg);
        System.out.println("Stayin' alive: " + longArg);
    } catch (Exception t) {
        dumpFramesIfNotDebug(frames);
        throw t;
    }
}
 
Example #5
Source File: AbstractRequester.java    From catnip with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Nonnull
@Override
public Observable<ResponsePayload> queue(@Nonnull final OutboundRequest r) {
    final CompletableFuture<ResponsePayload> future = new CompletableFuture<>();
    final Bucket bucket = getBucket(r.route());
    // Capture stacktrace if possible
    final StackTraceElement[] stacktrace;
    if(catnip.options().captureRestStacktraces()) {
        stacktrace = STACK_WALKER.walk(stream -> stream
                .map(StackFrame::toStackTraceElement)
                .toArray(StackTraceElement[]::new));
    } else {
        stacktrace = new StackTraceElement[0];
    }
    bucket.queueRequest(new QueuedRequest(r, r.route(), future, bucket, stacktrace));
    return RxHelpers.futureToObservable(future)
            .subscribeOn(catnip.rxScheduler())
            .observeOn(catnip.rxScheduler());
}
 
Example #6
Source File: SimpleConsoleLogger.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
/**
 * Returns true if we have found the caller's frame, false if the frame
 * must be skipped.
 *
 * @param t The frame info.
 * @return true if we have found the caller's frame, false if the frame
 * must be skipped.
 */
@Override
public boolean test(StackWalker.StackFrame t) {
    final String cname = t.getClassName();
    // We should skip all frames until we have found the logger,
    // because these frames could be frames introduced by e.g. custom
    // sub classes of Handler.
    if (lookingForLogger) {
        // Skip all frames until we have found the first logger frame.
        lookingForLogger = !isLoggerImplFrame(cname);
        return false;
    }
    // Continue walking until we've found the relevant calling frame.
    // Skips logging/logger infrastructure.
    return !Formatting.isFilteredFrame(t);
}
 
Example #7
Source File: LocalsAndOperands.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Perform stackwalk, keeping local variables alive, and return a list of
 * the collected StackFrames
 */
private synchronized StackFrame[] testLocalsKeepAlive() {
    int x = 0xA;
    char c = 'z'; // 0x7A
    String hi = "himom";
    long l = 0x3FF00000000L + 0xFFFFL;
    double d =  Math.PI;

    StackFrame[] frames = walker.walk(s ->
        s.filter(f -> TEST_METHODS.contains(f.getMethodName()))
         .toArray(StackFrame[]::new)
    );

    // Use local variables so they stay alive
    System.out.println("Stayin' alive: "+this+" "+x+" "+c+" "+hi+" "+l+" "+d);
    return frames;
}
 
Example #8
Source File: SimpleConsoleLogger.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns true if we have found the caller's frame, false if the frame
 * must be skipped.
 *
 * @param t The frame info.
 * @return true if we have found the caller's frame, false if the frame
 * must be skipped.
 */
@Override
public boolean test(StackWalker.StackFrame t) {
    final String cname = t.getClassName();
    // We should skip all frames until we have found the logger,
    // because these frames could be frames introduced by e.g. custom
    // sub classes of Handler.
    if (lookingForLogger) {
        // Skip all frames until we have found the first logger frame.
        lookingForLogger = !isLoggerImplFrame(cname);
        return false;
    }
    // Continue walking until we've found the relevant calling frame.
    // Skips logging/logger infrastructure.
    return !Formatting.isFilteredFrame(t);
}
 
Example #9
Source File: StackWalkTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public void consume(StackFrame sf) {
    if (count == 0 && swOptions.contains(StackWalker.Option.RETAIN_CLASS_REFERENCE)
            && isStreamPipeline(sf.getDeclaringClass())) {
        return;
    }
    if (verbose) {
        System.out.println("\t" + sf.getClassName() + "." + sf.getMethodName());
    }
    if (count >= recorder.frameCount()) {
        // We've gone past main()...
        if (infrastructureClasses.contains(sf.getClassName())) {
            // safe to ignore
            return;
        }
    }
    try {
        recorder.compareFrame(count, sf);
    } catch (IndexOutOfBoundsException e) {
        // Extra non-infra frame in stream
        throw new RuntimeException("extra non-infra stack frame at count "
                + count + ": <" + sf + ">", e);
    }
    count++;
}
 
Example #10
Source File: StackStreamTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
static void firstFrame() {
    System.out.println("first frame()");
    StackWalker sw = StackWalker.getInstance(RETAIN_CLASS_REFERENCE);
    sw.forEach(e -> {
        System.out.println(e.getClassName() + "," + e.getMethodName());
    });
    System.out.println("\n");
    Optional<StackFrame> frame = sw.walk(s ->
    {
         return s.filter(e -> {
                    System.err.println(e.getClassName() + " == " +
                                       e.getClassName().equals("StackStreamTest"));
                    return e.getClassName().equals("StackStreamTest");
                }).findFirst();
    });
    Class<?> c = frame.get().getDeclaringClass();
    System.out.println("\nfirst frame: " + c);
    if (c != StackStreamTest.class) {
        throw new RuntimeException("Unexpected first caller class " + c);
    }
}
 
Example #11
Source File: TestSecurityManager.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 * <p>This method inspects the stack trace and checks who is calling
 * {@link System#exit(int)} and similar methods
 * @throws SecurityException if the caller of this method is not the test runner itself.
 */
@Override
public void checkExit(final int status) {
  if (StackWalker.getInstance().walk(s -> s
      .dropWhile(Predicate.not(TestSecurityManager::isExitStackFrame)) // skip all internal stack frames
      .dropWhile(TestSecurityManager::isExitStackFrame)                // skip all exit()/halt() stack frames
      .limit(1)                                                        // only look at one more frame (caller of exit)
      .map(StackFrame::getClassName)
      .noneMatch(c -> c.startsWith(JUNIT4_TEST_RUNNER_PACKAGE) || 
          c.startsWith(ECLIPSE_TEST_RUNNER_PACKAGE) ||
          c.startsWith(IDEA_TEST_RUNNER_PACKAGE) ||
          c.startsWith(GRADLE_TEST_RUNNER_PACKAGE)))) {
    throw new SecurityException(String.format(Locale.ENGLISH,
        "System/Runtime.exit(%1$d) or halt(%1$d) calls are not allowed because they terminate the test runner's JVM.",
        status));
  }
  // we passed the stack check, delegate to super, so default policy can still deny permission:
  super.checkExit(status);
}
 
Example #12
Source File: LocalsAndOperands.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private static void usedDouble(double doubleArg) throws Exception {
    StackFrame[] frames = extendedWalker.walk(s ->
        s.filter(f -> "usedDouble".equals(f.getMethodName()))
         .toArray(StackFrame[]::new)
    );
    try {
        dumpFramesIfDebug(frames);

        Object[] locals = (Object[]) getLocals.invoke(frames[0]);
        assertDoubleIsInSlots(locals[0], locals[1], doubleArg);
        System.out.println("Stayin' alive: " + doubleArg);
    } catch (Exception t) {
        dumpFramesIfNotDebug(frames);
        throw t;
    }
}
 
Example #13
Source File: TestLoggerFinder.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns true if we have found the caller's frame, false if the frame
 * must be skipped.
 *
 * @param t The frame info.
 * @return true if we have found the caller's frame, false if the frame
 * must be skipped.
 */
@Override
public boolean test(StackWalker.StackFrame s) {
    // We should skip all frames until we have found the logger,
    // because these frames could be frames introduced by e.g. custom
    // sub classes of Handler.
    Class<?> c = s.getDeclaringClass();
    boolean isLogger = System.Logger.class.isAssignableFrom(c);
    if (lookingForLogger) {
        // Skip all frames until we have found the first logger frame.
        lookingForLogger = c != TestLogger.class;
        return false;
    }
    // Continue walking until we've found the relevant calling frame.
    // Skips logging/logger infrastructure.
    return !isLogger;
}
 
Example #14
Source File: TestLoggerFinder.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
static void publish(Level level, ResourceBundle bundle, String format, Object... params) {
    StackFrame sf = new CallerFinder().get().get();
    if (bundle != null && format != null) {
        format = bundle.getString(format);
    }
    String msg = format(format, params);
    LocalDateTime ldt = LocalDateTime.now();
    String date = DateTimeFormatter.ISO_DATE_TIME.format(ldt);
    System.err.println(date + " "
            + sf.getClassName() + " " + sf.getMethodName() + "\n"
            + String.valueOf(level) + ": " + msg);
}
 
Example #15
Source File: Utils.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void verify(Class<?> caller, String loaderName,
                          String methodname, String filename) {
    StackTraceElement[] stes = Thread.currentThread().getStackTrace();
    StackWalker.StackFrame[] frames = new StackFrame[] {
        makeStackFrame(Utils.class, "verify", "Utils.java"),
        makeStackFrame(caller, methodname, filename)
    };

    checkFrame("app", frames[0], stes[1]);
    checkFrame(loaderName, frames[1], stes[2]);
}
 
Example #16
Source File: Utils.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void checkFrame(String loaderName, StackFrame frame,
                              StackTraceElement ste) {
    System.err.println("checking " + ste.toString() + " expected: " + frame.toString());
    Class<?> c = frame.getDeclaringClass();
    Module module = c.getModule();
    assertEquals(ste.getModuleName(), module.getName(), "module name");
    assertEquals(ste.getClassLoaderName(), loaderName, "class loader name");
    assertEquals(ste.getClassLoaderName(), c.getClassLoader().getName(),
                 "class loader name");
    assertEquals(ste.getClassName(), c.getName(), "class name");
    assertEquals(ste.getMethodName(), frame.getMethodName(), "method name");
    assertEquals(ste.getFileName(), frame.getFileName(), "file name");

}
 
Example #17
Source File: EmbeddedStackWalkTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
static void call(StackWalker walker) {
    String caller = walker.walk(s ->
        s.map(StackFrame::getClassName)
         .filter(cn -> !cn.startsWith("jdk.internal.reflect.") && !cn.startsWith("java.lang.invoke"))
         .skip(2).findFirst()
    ).get();
    assertEquals(caller, C2.class.getName());

    verify(walker, C1.class, "call");
    verify(walker, C2.class, "call");
    verify(walker, C2.class, "run");
    verify(walker, C2.class, "walk");
    verify(walker, C2.class, "testEmbeddedWalker");
}
 
Example #18
Source File: ReflectionFrames.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public boolean filter(StackFrame f) {
    if (filterImplFrames &&
        f.getClassName().startsWith("jdk.internal.reflect.")) {
        filtered++;
        return false;
    }
    if (!verbose) System.out.println("    " + f);
    return true;
}
 
Example #19
Source File: NativeMethod.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
void walk() {
    List<StackFrame> nativeFrames = walker.walk(s ->
        s.filter(StackFrame::isNativeMethod)
         .collect(Collectors.toList())
    );

    assertTrue(nativeFrames.size() > 0, "native frame not found");
    for (StackFrame f : nativeFrames) {
        assertTrue(f.getFileName() != null, "source file expected to be found");
        assertTrue(f.getLineNumber() < 0, "line number expected to be unavailable");
        assertTrue(f.getByteCodeIndex() < 0, "bci expected to be unavailable");
    }

}
 
Example #20
Source File: Basic.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
void walk(int estimate) {
    int limit = Math.min(depth, 16);
    List<StackFrame> frames = new StackBuilder(depth, limit).build();
    System.out.format("depth=%d estimate=%d expected=%d walked=%d%n",
                      depth, estimate, limit, frames.size());
    assertEquals(limit, frames.size());
}
 
Example #21
Source File: EmbeddedStackWalkTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void call(StackWalker walker, int loops) {
    if (loops == 0) {
        String caller = walker.walk(s ->
            s.map(StackFrame::getClassName)
             .filter(cn -> !cn.startsWith("jdk.internal.reflect.") && !cn.startsWith("java.lang.invoke"))
             .skip(2).findFirst()
        ).get();
        assertEquals(caller, C1.class.getName());

        walker.forEach(f -> C2.testEmbeddedWalker());
    } else {
        call(walker, --loops);
    }
}
 
Example #22
Source File: LocalsAndOperands.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/** Calls KnownLocalsTester.testLocals* and provides LiveStackFrames */
@DataProvider
public static StackFrame[][] knownLocalsProvider() {
    List<StackFrame[]> list = new ArrayList<>(3);
    list.add(new KnownLocalsTester().testLocalsKeepAlive());
    list.add(new KnownLocalsTester().testLocalsKeepAliveArgs(0xA, 'z',
            "himom", 0x3FF00000000L + 0xFFFF, Math.PI));
    if (testUnused) {
        list.add(new KnownLocalsTester().testLocalsUnused());
    }
    return list.toArray(new StackFrame[1][1]);
}
 
Example #23
Source File: DynamicLinker.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns a stack trace element describing the location of the
 * {@code invokedynamic} call site currently being linked on the current
 * thread. The operation is potentially expensive as it needs to generate a
 * stack trace to inspect it and is intended for use in diagnostics code.
 * For "free-floating" call sites (not associated with an
 * {@code invokedynamic} instruction), the result is not well-defined.
 *
 * @return a stack trace element describing the location of the call site
 *         currently being linked, or null if it is not invoked while a call
 *         site is being linked.
 */
public static StackTraceElement getLinkedCallSiteLocation() {
    return stackWalker.walk(s -> s
            // Find one of our linking entry points on the stack...
            .dropWhile(f -> !(isRelinkFrame(f) || isInitialLinkFrame(f)))
            .skip(1)
            // ... then look for the first thing calling it that isn't j.l.invoke
            .dropWhile(f -> f.getClassName().startsWith(INVOKE_PACKAGE_PREFIX))
            .findFirst()
            .map(StackFrame::toStackTraceElement)
            .orElse(null)
    );
}
 
Example #24
Source File: HiddenFrames.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
void checkFrame(StackFrame frame) {
    String cn = frame.getClassName();
    if (cn.startsWith("java.lang.reflect.") || cn.startsWith("jdk.internal.reflect.")) {
        reflects.add(frame);
    }
    if (cn.contains("$$Lambda$")) {
        lambdas.add(frame);
    }
}
 
Example #25
Source File: LocalsAndOperands.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Print the StackFrame and an indexed list of its locals
 */
public static void printLocals(StackWalker.StackFrame frame) {
    try {
        System.out.println("Locals for: " + frame);
        Object[] locals = (Object[]) getLocals.invoke(frame);
        for (int i = 0; i < locals.length; i++) {
            String localStr = null;

            if (primitiveSlot64Class.isInstance(locals[i])) {
                localStr = String.format("0x%X",
                        (Long)primitiveLongValue.invoke(locals[i]));
            } else if (primitiveSlot32Class.isInstance(locals[i])) {
                localStr = String.format("0x%X",
                        (Integer)primitiveIntValue.invoke(locals[i]));
            } else if (locals[i] != null) {
                localStr = locals[i].toString();
            }
            System.out.format("  local %d: %s type %s\n", i, localStr, type(locals[i]));
        }

        Object[] operands = (Object[]) getOperands.invoke(frame);
        for (int i = 0; i < operands.length; i++) {
            System.out.format("  operand %d: %s type %s%n", i, operands[i],
                              type(operands[i]));
        }

        Object[] monitors = (Object[]) getMonitors.invoke(frame);
        for (int i = 0; i < monitors.length; i++) {
            System.out.format("  monitor %d: %s%n", i, monitors[i]);
        }
    } catch (Exception e) { throw new RuntimeException(e); }
}
 
Example #26
Source File: LegacyTest.java    From demo-junit-5 with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
@Test
public void testWithJUnit4_failsIfNotRunWithJUnit5Platform() {
	Optional<String> vintageFrame = StackWalker
			.getInstance()
			.walk(frames -> frames
					.peek(System.out::println)
					.map(StackFrame::getClassName)
					.filter(method -> method.contains("vintage"))
					.findAny());
	assertThat(vintageFrame).isNotEmpty();
}
 
Example #27
Source File: LocalsAndOperands.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Perform stackwalk without keeping local variables alive and return an
 * array of the collected StackFrames
 */
private synchronized StackFrame[] testLocalsUnused() {
    // Unused local variables will become dead
    int x = 0xA;
    char c = 'z'; // 0x7A
    String hi = "himom";
    long l = 0x3FF00000000L + 0xFFFFL;
    double d =  Math.PI;

    return walker.walk(s ->
        s.filter(f -> TEST_METHODS.contains(f.getMethodName()))
         .toArray(StackFrame[]::new)
    );
}
 
Example #28
Source File: LocalsAndOperands.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Check the locals in the given StackFrame against the expected values.
 */
private static void checkFrameLocals(StackFrame f) {
    Object[] expectedArray = KnownLocalsTester.LOCAL_VALUES;
    Object[] locals = invokeGetLocals(f);

    for (int i = 0; i < locals.length; i++) {
        Object expected = expectedArray[i];
        Object observed = locals[i];

        if (expected == null) { /* skip nulls in golden values */
            continue;
        } else if (expected instanceof KnownLocalsTester.TwoSlotValue) {
            // confirm integrity of expected values
            assertEquals(expectedArray[i+1], null,
                    "Malformed array of expected values - slot after TwoSlotValue should be null");
            assertLongIsInSlots(locals[i], locals[i+1],
                    ((KnownLocalsTester.TwoSlotValue)expected).value);
            i++; // skip following slot
        } else if (primitiveSlotClass.isInstance(observed)) { // single slot primitive
            assertTrue(primitiveValueEquals(observed, expected),
                    "Local value mismatch: local " + i + " value is " +
                      observed + ", expected " + expected);
        } else if (expected instanceof Class) {
            assertTrue(((Class)expected).isInstance(observed),
                    "Local value mismatch: local " + i + " expected instancof " +
                      expected + " but got " + observed);
        } else if (expected instanceof String) {
            assertEquals(expected, observed, "Local value mismatch: local " +
                    i + " value is " + observed + ", expected " + expected);
        } else {
            throw new RuntimeException("Unrecognized expected local value " +
                    i + ": " + expected);
        }
    }
}
 
Example #29
Source File: LocalsAndOperands.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Check for expected local values in the LiveStackFrame
 */
@Test(dataProvider = "knownLocalsProvider")
public static void checkLocalValues(StackFrame... frames) {
    dumpFramesIfDebug(frames);
    try {
        Stream.of(frames)
              .filter(f -> KnownLocalsTester.TEST_METHODS.contains(f.getMethodName()))
              .forEach(LocalsAndOperands::checkFrameLocals);
    } catch (Exception e) { dumpFramesIfNotDebug(frames); throw e; }
}
 
Example #30
Source File: LocalsAndOperands.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Perform stackwalk, keeping method arguments alive, and return a list of
 * the collected StackFrames
 */
private synchronized StackFrame[] testLocalsKeepAliveArgs(int x, char c,
                                                          String hi, long l,
                                                          double d) {
    StackFrame[] frames = walker.walk(s ->
        s.filter(f -> TEST_METHODS.contains(f.getMethodName()))
         .toArray(StackFrame[]::new)
    );

    // Use local variables so they stay alive
    System.out.println("Stayin' alive: "+this+" "+x+" "+c+" "+hi+" "+l+" "+d);
    return frames;
}