1 /*
  2  * Copyright (c) 2021, 2025, 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  * @bug 8272586
 27  * @requires vm.flagless
 28  * @requires vm.compiler2.enabled
 29  * @requires test.thread.factory == null
 30  * @summary Test that abstract machine code is dumped for the top frames in a hs-err log
 31  * @library /test/lib
 32  * @modules java.base/jdk.internal.misc
 33  *          java.compiler
 34  *          java.management
 35  *          jdk.internal.jvmstat/sun.jvmstat.monitor
 36  * @run driver MachCodeFramesInErrorFile
 37  */
 38 
 39 import java.io.File;
 40 import java.lang.annotation.Annotation;
 41 import java.lang.reflect.Method;
 42 import java.nio.file.Files;
 43 import java.nio.file.Path;
 44 import java.nio.file.Paths;
 45 import java.util.ArrayList;
 46 import java.util.HashSet;
 47 import java.util.List;
 48 import java.util.Set;
 49 import java.util.stream.Collectors;
 50 import java.util.stream.Stream;
 51 import java.util.regex.Pattern;
 52 import java.util.regex.Matcher;
 53 
 54 import jdk.test.lib.Platform;
 55 import jdk.test.lib.process.ProcessTools;
 56 import jdk.test.lib.process.OutputAnalyzer;
 57 import jdk.test.lib.Asserts;
 58 
 59 import jdk.internal.misc.Unsafe;
 60 
 61 public class MachCodeFramesInErrorFile {
 62     private static class Crasher {
 63         // Make Crasher.unsafe a compile-time constant so that
 64         // C2 intrinsifies calls to Unsafe intrinsics.
 65         private static final Unsafe unsafe = Unsafe.getUnsafe();
 66 
 67         public static void main(String[] args) throws Exception {
 68             if (args[0].equals("crashInJava")) {
 69                 // This test relies on Unsafe.putLong(Object, long, long) being intrinsified
 70                 if (!Stream.of(Unsafe.class.getDeclaredMethod("putLong", Object.class, long.class, long.class).getAnnotations()).
 71                     anyMatch(a -> a.annotationType().getName().equals("jdk.internal.vm.annotation.IntrinsicCandidate"))) {
 72                     throw new RuntimeException("Unsafe.putLong(Object, long, long) is not an intrinsic");
 73                 }
 74                 crashInJava1(10);
 75             } else {
 76                 assert args[0].equals("crashInVM");
 77                 // Low address reads are allowed on PPC
 78                 crashInNative1(Platform.isPPC() ? -1 : 10);
 79             }
 80         }
 81 
 82         static void crashInJava1(long address) {
 83             System.out.println("in crashInJava1");
 84             crashInJava2(address);
 85         }
 86         static void crashInJava2(long address) {
 87             System.out.println("in crashInJava2");
 88             crashInJava3(address);
 89         }
 90         static void crashInJava3(long address) {
 91             unsafe.putLong(null, address, 42);
 92             System.out.println("wrote value to 0x" + Long.toHexString(address));
 93         }
 94 
 95         static void crashInNative1(long address) {
 96             System.out.println("in crashInNative1");
 97             crashInNative2(address);
 98         }
 99         static void crashInNative2(long address) {
100             System.out.println("in crashInNative2");
101             crashInNative3(address);
102         }
103         static void crashInNative3(long address) {
104             System.out.println("read value " + unsafe.getLong(address) + " from 0x" + Long.toHexString(address));
105         }
106     }
107 
108     public static void main(String[] args) throws Exception {
109         run(true);
110         run(false);
111     }
112 
113     /**
114      * Runs Crasher in Xcomp mode. The inner
115      * most method crashes the VM with Unsafe. The resulting hs-err log is
116      * expected to have a min number of MachCode sections.
117      */
118     private static void run(boolean crashInJava) throws Exception {
119         ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(
120             "-Xmx64m", "--add-exports=java.base/jdk.internal.misc=ALL-UNNAMED",
121             "-XX:-CreateCoredumpOnCrash",
122             "-Xcomp",
123             "-XX:-TieredCompilation",
124             "-XX:CompileCommand=compileonly,MachCodeFramesInErrorFile$Crasher.crashIn*",
125             "-XX:CompileCommand=dontinline,MachCodeFramesInErrorFile$Crasher.crashIn*",
126             "-XX:CompileCommand=dontinline,*/Unsafe.getLong", // ensures VM call when crashInJava == false
127             Crasher.class.getName(),
128             crashInJava ? "crashInJava" : "crashInVM");
129         OutputAnalyzer output = new OutputAnalyzer(pb.start());
130 
131         // Extract hs_err_pid file.
132         File hs_err_file = HsErrFileUtils.openHsErrFileFromOutput(output);
133         Path hsErrPath = hs_err_file.toPath();
134         if (!Files.exists(hsErrPath)) {
135             throw new RuntimeException("hs_err_pid file missing at " + hsErrPath + ".\n");
136         }
137         String hsErr = Files.readString(hsErrPath);
138         if (System.getenv("DEBUG") != null) {
139             System.err.println(hsErr);
140         }
141         Set<String> frames = new HashSet<>();
142         extractFrames(hsErr, frames, true);
143         if (!crashInJava) {
144             // A crash in native will have Java frames in the hs-err log
145             // as there is a Java frame anchor on the stack.
146             extractFrames(hsErr, frames, false);
147         }
148         int compiledJavaFrames = (int) frames.stream().filter(f -> f.startsWith("J ")).count();
149 
150         Matcher matcherDisasm = Pattern.compile("\\[Disassembly\\].*\\[/Disassembly\\]", Pattern.DOTALL).matcher(hsErr);
151         if (matcherDisasm.find()) {
152             // Real disassembly is present, no MachCode is expected.
153             return;
154         }
155 
156         String preCodeBlobSectionHeader = "Stack slot to memory mapping:";
157         if (!hsErr.contains(preCodeBlobSectionHeader) &&
158             System.getProperty("os.arch").equals("aarch64") &&
159             System.getProperty("os.name").toLowerCase().startsWith("mac")) {
160             // JDK-8282607: hs_err can be truncated. If the section preceding
161             // code blob dumping is missing, exit successfully.
162             System.out.println("Could not find \"" + preCodeBlobSectionHeader + "\" in " + hsErrPath);
163             System.out.println("Looks like hs-err is truncated - exiting with success");
164             return;
165         }
166 
167         Matcher matcher = Pattern.compile("\\[MachCode\\]\\s*\\[Verified Entry Point\\]\\s*  # \\{method\\} \\{[^}]*\\} '([^']+)' '([^']+)' in '([^']+)'", Pattern.DOTALL).matcher(hsErr);
168         List<String> machCodeHeaders = matcher.results().map(mr -> String.format("'%s' '%s' in '%s'", mr.group(1), mr.group(2), mr.group(3))).collect(Collectors.toList());
169         int minExpectedMachCodeSections = Math.max(1, compiledJavaFrames);
170         if (machCodeHeaders.size() < minExpectedMachCodeSections) {
171             Asserts.fail(machCodeHeaders.size() + " < " + minExpectedMachCodeSections);
172         }
173     }
174 
175     /**
176      * Extracts the lines in {@code hsErr} below the line starting with
177      * "Native frame" or "Java frame" up to the next blank line
178      * and adds them to {@code frames}.
179      */
180     private static void extractFrames(String hsErr, Set<String> frames, boolean nativeStack) {
181         String marker = (nativeStack ? "Native" : "Java") + " frame";
182 
183         boolean seenMarker = false;
184         for (String line : hsErr.split(System.lineSeparator())) {
185             if (line.startsWith(marker)) {
186                 seenMarker = true;
187             } else if (seenMarker) {
188                 if (line.trim().isEmpty()) {
189                     return;
190                 }
191                 frames.add(line);
192             }
193         }
194         System.err.println(hsErr);
195         throw new RuntimeException("\"" + marker + "\" line missing in hs_err_pid file");
196     }
197 }