1 /*
  2  * Copyright (c) 2020, 2024, 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.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  */
 23 
 24 /**
 25  * @test
 26  * @summary Test stack traces in exceptions, stack frames walked by the StackWalker,
 27  *    and the stack trace returned by Thread.getStackTrace
 28  * @requires vm.continuations
 29  * @modules java.base/java.lang:+open java.management
 30  * @library /test/lib
 31  * @run junit StackFrames
 32  * @run junit/othervm -XX:+UnlockDiagnosticVMOptions -XX:+ShowCarrierFrames StackFrames
 33  */
 34 
 35 import java.lang.management.ManagementFactory;
 36 import java.util.Arrays;
 37 import java.util.Set;
 38 import java.util.concurrent.Executor;
 39 import java.util.concurrent.ForkJoinPool;
 40 import java.util.concurrent.ForkJoinWorkerThread;
 41 import java.util.concurrent.ThreadFactory;
 42 import java.util.concurrent.atomic.AtomicBoolean;
 43 import java.util.concurrent.atomic.AtomicReference;
 44 import java.util.stream.Stream;
 45 import static java.lang.StackWalker.Option.*;
 46 
 47 import jdk.test.lib.thread.VThreadRunner;
 48 import jdk.test.lib.thread.VThreadScheduler;
 49 import org.junit.jupiter.api.Test;
 50 import static org.junit.jupiter.api.Assertions.*;
 51 
 52 class StackFrames {
 53 
 54     /**
 55      * Test that the stack trace in exceptions does not include the carrier thread
 56      * frames, except when running with -XX:+ShowCarrierFrames.
 57      */
 58     @Test
 59     void testStackTraceException() throws Exception {
 60         VThreadRunner.run(() -> {
 61             Exception e = new Exception();
 62             boolean found = Arrays.stream(e.getStackTrace())
 63                     .map(StackTraceElement::getClassName)
 64                     .anyMatch("java.util.concurrent.ForkJoinPool"::equals);
 65             assertTrue(found == hasJvmArgument("-XX:+ShowCarrierFrames"));
 66         });
 67     }
 68 
 69     /**
 70      * Test that StackWalker does not include carrier thread frames in the stream of
 71      * stack frames.
 72      */
 73     @Test
 74     void testStackWalker() throws Exception {
 75         VThreadRunner.run(() -> {
 76             StackWalker walker = StackWalker.getInstance(Set.of(RETAIN_CLASS_REFERENCE));
 77             boolean found = walker.walk(sf ->
 78                     sf.map(StackWalker.StackFrame::getDeclaringClass)
 79                             .anyMatch(c -> c == ForkJoinPool.class));
 80             assertFalse(found);
 81         });
 82     }
 83 
 84     /**
 85      * Test Thread.getStackTrace returns the expected bottom frame for both the carrier
 86      * and virtual thread.
 87      */
 88     @Test
 89     void testBottomFrames() throws Exception {
 90         try (ForkJoinPool pool = new ForkJoinPool(1)) {
 91             var carrierRef = new AtomicReference<Thread>();
 92             Executor scheduler = task -> {
 93                 pool.submit(() -> {
 94                     carrierRef.set(Thread.currentThread());
 95                     task.run();
 96                 });
 97             };
 98             ThreadFactory factory = VThreadScheduler.virtualThreadFactory(scheduler);
 99 
100             var ready = new AtomicBoolean();
101             var done = new AtomicBoolean();
102 
103             // create virtual thread to use custom scheduler
104             var vthread = factory.newThread(() -> {
105                 ready.set(true);
106                 while (!done.get()) {
107                     Thread.onSpinWait();
108                 }
109             });
110 
111             vthread.start();
112             try {
113                 awaitTrue(ready);
114 
115                 // get carrier Thread
116                 Thread carrier = carrierRef.get();
117                 assertTrue(carrier instanceof ForkJoinWorkerThread);
118 
119                 // bottom-most frame of virtual thread should be VirtualThread.run
120                 System.err.println(vthread);
121                 StackTraceElement[] vthreadStack = vthread.getStackTrace();
122                 Stream.of(vthreadStack).forEach(e -> System.err.println("    " + e));
123                 StackTraceElement bottomFrame = vthreadStack[vthreadStack.length - 1];
124                 assertEquals("java.lang.VirtualThread.run",
125                         bottomFrame.getClassName() + "." + bottomFrame.getMethodName());
126 
127                 // bottom-most frame of carrier thread should be Thread.run
128                 System.err.println(carrier);
129                 StackTraceElement[] carrierStack = carrier.getStackTrace();
130                 Stream.of(carrierStack).forEach(e -> System.err.println("    " + e));
131                 bottomFrame = carrierStack[carrierStack.length - 1];
132                 assertEquals("java.util.concurrent.ForkJoinWorkerThread.run",
133                         bottomFrame.getClassName() + "." + bottomFrame.getMethodName());
134 
135             } finally {
136                 done.set(true);
137                 vthread.join();
138             }
139         }
140     }
141 
142     /**
143      * Returns true if started with the given VM option.
144      */
145     private static boolean hasJvmArgument(String arg) {
146         for (String argument : ManagementFactory.getRuntimeMXBean().getInputArguments()) {
147             if (argument.equals(arg)) return true;
148         }
149         return false;
150     }
151 
152     /**
153      * Waits for the boolean value to become true.
154      */
155     private static void awaitTrue(AtomicBoolean ref) throws InterruptedException {
156         while (!ref.get()) {
157             Thread.sleep(20);
158         }
159     }
160 }