1 /*
   2  * Copyright (c) 2018, 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 8174994
  27  * @summary Test the clhsdb commands 'printmdo', 'printall' on a CDS enabled corefile.
  28  * @requires vm.cds
  29  * @requires vm.hasSA
  30  * @requires os.family != "windows"
  31  * @requires vm.flavor == "server"
  32  * @library /test/lib
  33  * @modules java.base/jdk.internal.misc
  34  * @run main/othervm/timeout=2400 -Xmx1g ClhsdbCDSCore
  35  */
  36 
  37 import java.util.List;
  38 import java.util.ArrayList;
  39 import java.util.Arrays;
  40 import java.util.Map;
  41 import java.util.HashMap;
  42 import jdk.test.lib.process.ProcessTools;
  43 import jdk.test.lib.Platform;
  44 import jdk.test.lib.process.OutputAnalyzer;
  45 import jdk.test.lib.cds.CDSTestUtils;
  46 import jdk.test.lib.cds.CDSOptions;
  47 import java.io.IOException;
  48 import java.io.File;
  49 import java.nio.file.Files;
  50 import java.nio.file.Path;
  51 import java.nio.file.Paths;
  52 import jdk.test.lib.Asserts;
  53 import java.util.regex.Pattern;
  54 import java.util.regex.Matcher;
  55 import jdk.internal.misc.Unsafe;
  56 import java.util.Scanner;
  57 import jtreg.SkippedException;
  58 
  59 class CrashApp {
  60     public static void main(String[] args) {
  61         Unsafe.getUnsafe().putInt(0L, 0);
  62     }
  63 }
  64 
  65 public class ClhsdbCDSCore {
  66 
  67     private static final String TEST_CDS_CORE_FILE_NAME = "cds_core_file";
  68     private static final String LOCATIONS_STRING = "location: ";
  69     private static final String RUN_SHELL_NO_LIMIT = "ulimit -c unlimited && ";
  70     private static final String SHARED_ARCHIVE_NAME = "ArchiveForClhsdbCDSCore.jsa";
  71     private static final String CORE_PATTERN_FILE_NAME = "/proc/sys/kernel/core_pattern";
  72 
  73     public static void main(String[] args) throws Exception {
  74         System.out.println("Starting ClhsdbCDSCore test");
  75         cleanup();
  76 
  77         try {
  78             CDSOptions opts = (new CDSOptions()).setArchiveName(SHARED_ARCHIVE_NAME);
  79             CDSTestUtils.createArchiveAndCheck(opts);
  80 
  81             String[] jArgs = {
  82                 "-XX:+UnlockDiagnosticVMOptions",
  83                 "-XX:SharedArchiveFile=" + SHARED_ARCHIVE_NAME,
  84                 "-XX:+CreateCoredumpOnCrash",
  85                 "-Xshare:auto",
  86                 "-XX:+ProfileInterpreter",
  87                 "--add-exports=java.base/jdk.internal.misc=ALL-UNNAMED",
  88                 CrashApp.class.getName()
  89             };
  90 
  91             OutputAnalyzer crashOut;
  92             try {
  93                List<String> options = new ArrayList<>();
  94                options.addAll(Arrays.asList(jArgs));
  95                crashOut =
  96                    ProcessTools.executeProcess(getTestJavaCommandlineWithPrefix(
  97                    RUN_SHELL_NO_LIMIT, options.toArray(new String[0])));
  98             } catch (Throwable t) {
  99                throw new Error("Can't execute the java cds process.", t);
 100             }
 101 
 102             System.out.println(crashOut.getOutput());
 103             String crashOutputString = crashOut.getOutput();
 104             String coreFileLocation = getCoreFileLocation(crashOutputString);
 105             if (coreFileLocation == null) {
 106                 if (Platform.isOSX()) {
 107                     File coresDir = new File("/cores");
 108                     if (!coresDir.isDirectory() || !coresDir.canWrite()) {
 109                         throw new Error("cores is not a directory or does not have write permissions");
 110                     }
 111                 } else if (Platform.isLinux()) {
 112                     // Check if a crash report tool is installed.
 113                     File corePatternFile = new File(CORE_PATTERN_FILE_NAME);
 114                     Scanner scanner = new Scanner(corePatternFile);
 115                     while (scanner.hasNextLine()) {
 116                         String line = scanner.nextLine();
 117                         line = line.trim();
 118                         System.out.println(line);
 119                         if (line.startsWith("|")) {
 120                             System.out.println(
 121                                 "\nThis system uses a crash report tool ($cat /proc/sys/kernel/core_pattern).\n" +
 122                                 "Core files might not be generated. Please reset /proc/sys/kernel/core_pattern\n" +
 123                                 "to enable core generation. Skipping this test.");
 124                             cleanup();
 125                             throw new SkippedException("This system uses a crash report tool");
 126                         }
 127                     }
 128                 }
 129                 throw new Error("Couldn't find core file location in: '" + crashOutputString + "'");
 130             }
 131             try {
 132                 Asserts.assertGT(new File(coreFileLocation).length(), 0L, "Unexpected core size");
 133                 Files.move(Paths.get(coreFileLocation), Paths.get(TEST_CDS_CORE_FILE_NAME));
 134             } catch (IOException ioe) {
 135                 throw new Error("Can't move core file: " + ioe, ioe);
 136             }
 137 
 138             ClhsdbLauncher test = new ClhsdbLauncher();
 139 
 140             // Ensure that UseSharedSpaces is turned on.
 141             List<String> cmds = List.of("flags UseSharedSpaces");
 142 
 143             String useSharedSpacesOutput = test.runOnCore(TEST_CDS_CORE_FILE_NAME, cmds,
 144                                                           null, null);
 145 
 146             if (useSharedSpacesOutput == null) {
 147                 // Output could be null due to attach permission issues.
 148                 cleanup();
 149                 throw new SkippedException("Could not determine the UseSharedSpaces value");
 150             }
 151 
 152             if (!useSharedSpacesOutput.contains("true")) {
 153                 // CDS archive is not mapped. Skip the rest of the test.
 154                 cleanup();
 155                 throw new SkippedException("The CDS archive is not mapped");
 156             }
 157 
 158             cmds = List.of("printmdo -a", "printall");
 159 
 160             Map<String, List<String>> expStrMap = new HashMap<>();
 161             Map<String, List<String>> unExpStrMap = new HashMap<>();
 162             expStrMap.put("printmdo -a", List.of(
 163                 "CounterData",
 164                 "BranchData"));
 165             unExpStrMap.put("printmdo -a", List.of(
 166                 "No suitable match for type of address"));
 167             expStrMap.put("printall", List.of(
 168                 "aload_0",
 169                 "_nofast_aload_0",
 170                 "_nofast_getfield",
 171                 "_nofast_putfield",
 172                 "Constant Pool of",
 173                 "public static void main(java.lang.String[])",
 174                 "Bytecode",
 175                 "invokevirtual",
 176                 "checkcast",
 177                 "Exception Table",
 178                 "invokedynamic"));
 179             unExpStrMap.put("printall", List.of(
 180                 "sun.jvm.hotspot.types.WrongTypeException",
 181                 "illegal code",
 182                 "Failure occurred at bci",
 183                 "No suitable match for type of address"));
 184             test.runOnCore(TEST_CDS_CORE_FILE_NAME, cmds, expStrMap, unExpStrMap);
 185         } catch (SkippedException e) {
 186             throw e;
 187         } catch (Exception ex) {
 188             throw new RuntimeException("Test ERROR " + ex, ex);
 189         }
 190         cleanup();
 191         System.out.println("Test PASSED");
 192     }
 193 
 194     // lets search for a few possible locations using process output and return existing location
 195     private static String getCoreFileLocation(String crashOutputString) {
 196         Asserts.assertTrue(crashOutputString.contains(LOCATIONS_STRING),
 197             "Output doesn't contain the location of core file.");
 198         String stringWithLocation = Arrays.stream(crashOutputString.split("\\r?\\n"))
 199             .filter(str -> str.contains(LOCATIONS_STRING))
 200             .findFirst()
 201             .get();
 202         stringWithLocation = stringWithLocation.substring(stringWithLocation
 203             .indexOf(LOCATIONS_STRING) + LOCATIONS_STRING.length());
 204         System.out.println("getCoreFileLocation found stringWithLocation = " + stringWithLocation);
 205         String coreWithPid;
 206         if (stringWithLocation.contains("or ")) {
 207             Matcher m = Pattern.compile("or.* ([^ ]+[^\\)])\\)?").matcher(stringWithLocation);
 208             if (!m.find()) {
 209                 throw new Error("Couldn't find path to core inside location string");
 210             }
 211             coreWithPid = m.group(1);
 212         } else {
 213             coreWithPid = stringWithLocation.trim();
 214         }
 215         if (new File(coreWithPid).exists()) {
 216             return coreWithPid;
 217         }
 218         String justCore = Paths.get("core").toString();
 219         if (new File(justCore).exists()) {
 220             return justCore;
 221         }
 222         Path coreWithPidPath = Paths.get(coreWithPid);
 223         String justFile = coreWithPidPath.getFileName().toString();
 224         if (new File(justFile).exists()) {
 225             return justFile;
 226         }
 227         Path parent = coreWithPidPath.getParent();
 228         if (parent != null) {
 229             String coreWithoutPid = parent.resolve("core").toString();
 230             if (new File(coreWithoutPid).exists()) {
 231                 return coreWithoutPid;
 232             }
 233         }
 234         return null;
 235     }
 236 
 237     private static String[] getTestJavaCommandlineWithPrefix(String prefix, String... args) {
 238         try {
 239             String cmd = ProcessTools.getCommandLine(ProcessTools.createJavaProcessBuilder(true, args));
 240             return new String[]{"sh", "-c", prefix + cmd};
 241         } catch (Throwable t) {
 242             throw new Error("Can't create process builder: " + t, t);
 243         }
 244     }
 245 
 246     private static void cleanup() {
 247         remove(TEST_CDS_CORE_FILE_NAME);
 248         remove(SHARED_ARCHIVE_NAME);
 249     }
 250 
 251     private static void remove(String item) {
 252         File toDelete = new File(item);
 253         toDelete.delete();
 254     }
 255 }