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