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