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.");
  98             }
  99             System.out.println(crashOut.getOutput());
 100             String crashOutputString = crashOut.getOutput();
 101             String coreFileLocation = getCoreFileLocation(crashOutputString);
 102             if (coreFileLocation == null) {
 103                 if (Platform.isOSX()) {
 104                     File coresDir = new File("/cores");
 105                     if (!coresDir.isDirectory() || !coresDir.canWrite()) {
 106                         throw new Error("cores is not a directory or does not have write permissions");
 107                     }
 108                 } else if (Platform.isLinux()) {
 109                     // Check if a crash report tool is installed.
 110                     File corePatternFile = new File(CORE_PATTERN_FILE_NAME);
 111                     Scanner scanner = new Scanner(corePatternFile);
 112                     while (scanner.hasNextLine()) {
 113                         String line = scanner.nextLine();
 114                         line = line.trim();
 115                         System.out.println(line);
 116                         if (line.startsWith("|")) {
 117                             throw new Error(
 118                                 "\nThis system uses a crash report tool ($cat /proc/sys/kernel/core_pattern).\n" +
 119                                 "Core files might not be generated. Please reset /proc/sys/kernel/core_pattern\n" +
 120                                 "to enable core generation.");
 121                         }
 122                     }
 123                 }
 124                 throw new Error("Couldn't find core file location in: '" + crashOutputString + "'");
 125             }
 126             try {
 127                 Asserts.assertGT(new File(coreFileLocation).length(), 0L, "Unexpected core size");
 128                 Files.move(Paths.get(coreFileLocation), Paths.get(TEST_CDS_CORE_FILE_NAME));
 129             } catch (IOException ioe) {
 130                 throw new Error("Can't move core file: " + ioe, ioe);
 131             }
 132 
 133             ClhsdbLauncher test = new ClhsdbLauncher();
 134 
 135             // Ensure that UseSharedSpaces is turned on.
 136             List<String> cmds = List.of("flags UseSharedSpaces");
 137 
 138             String useSharedSpacesOutput = test.runOnCore(TEST_CDS_CORE_FILE_NAME, cmds,
 139                                                           null, null);
 140 
 141             if (useSharedSpacesOutput == null) {
 142                 // Output could be null due to attach permission issues.
 143                 System.out.println("Could not determine the UseSharedSpaces value - test skipped.");
 144                 cleanup();
 145                 return;
 146             }
 147 
 148             if (useSharedSpacesOutput.contains("true") == false) {
 149                 // CDS archive is not mapped. Skip the rest of the test.
 150                 System.out.println("The CDS archive is not mapped - test skipped.");
 151                 cleanup();
 152                 return;
 153             }
 154 
 155             cmds = List.of("printmdo -a", "printall");
 156 
 157             Map<String, List<String>> expStrMap = new HashMap<>();
 158             Map<String, List<String>> unExpStrMap = new HashMap<>();
 159             expStrMap.put("printmdo -a", List.of(
 160                 "CounterData",
 161                 "BranchData"));
 162             unExpStrMap.put("printmdo -a", List.of(
 163                 "No suitable match for type of address"));
 164             expStrMap.put("printall", List.of(
 165                 "aload_0",
 166                 "Constant Pool of",
 167                 "public static void main(java.lang.String[])",
 168                 "Bytecode",
 169                 "invokevirtual",
 170                 "checkcast",
 171                 "Exception Table",
 172                 "invokedynamic"));
 173             unExpStrMap.put("printall", List.of(
 174                 "sun.jvm.hotspot.types.WrongTypeException",
 175                 "No suitable match for type of address"));
 176             test.runOnCore(TEST_CDS_CORE_FILE_NAME, cmds, expStrMap, unExpStrMap);
 177         } catch (Exception ex) {
 178             throw new RuntimeException("Test ERROR " + ex, ex);
 179         }
 180         cleanup();
 181         System.out.println("Test PASSED");
 182     }
 183 
 184     // lets search for a few possible locations using process output and return existing location
 185     private static String getCoreFileLocation(String crashOutputString) {
 186         Asserts.assertTrue(crashOutputString.contains(LOCATIONS_STRING),
 187             "Output doesn't contain the location of core file.");
 188         String stringWithLocation = Arrays.stream(crashOutputString.split("\\r?\\n"))
 189             .filter(str -> str.contains(LOCATIONS_STRING))
 190             .findFirst()
 191             .get();
 192         stringWithLocation = stringWithLocation.substring(stringWithLocation
 193             .indexOf(LOCATIONS_STRING) + LOCATIONS_STRING.length());
 194         String coreWithPid;
 195         if (stringWithLocation.contains("or ")) {
 196             Matcher m = Pattern.compile("or.* ([^ ]+[^\\)])\\)?").matcher(stringWithLocation);
 197             if (!m.find()) {
 198                 throw new Error("Couldn't find path to core inside location string");
 199             }
 200             coreWithPid = m.group(1);
 201         } else {
 202             coreWithPid = stringWithLocation.trim();
 203         }
 204         if (new File(coreWithPid).exists()) {
 205             return coreWithPid;
 206         }
 207         String justCore = Paths.get("core").toString();
 208         if (new File(justCore).exists()) {
 209             return justCore;
 210         }
 211         Path coreWithPidPath = Paths.get(coreWithPid);
 212         String justFile = coreWithPidPath.getFileName().toString();
 213         if (new File(justFile).exists()) {
 214             return justFile;
 215         }
 216         Path parent = coreWithPidPath.getParent();
 217         if (parent != null) {
 218             String coreWithoutPid = parent.resolve("core").toString();
 219             if (new File(coreWithoutPid).exists()) {
 220                 return coreWithoutPid;
 221             }
 222         }
 223         return null;
 224     }
 225 
 226     private static String[] getTestJavaCommandlineWithPrefix(String prefix, String... args) {
 227         try {
 228             String cmd = ProcessTools.getCommandLine(ProcessTools.createJavaProcessBuilder(true, args));
 229             return new String[]{"sh", "-c", prefix + cmd};
 230         } catch (Throwable t) {
 231             throw new Error("Can't create process builder: " + t, t);
 232         }
 233     }
 234 
 235     private static void cleanup() {
 236         remove(TEST_CDS_CORE_FILE_NAME);
 237         remove(SHARED_ARCHIVE_NAME);
 238     }
 239 
 240     private static void remove(String item) {
 241         File toDelete = new File(item);
 242         toDelete.delete();
 243     }
 244 }