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