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