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 /*
  26  * @test
  27  * @summary Tests how CDS works when critical library classes are replaced with JVMTI ClassFileLoadHook
  28  * @library /test/lib
  29  * @requires vm.cds
  30  * @build sun.hotspot.WhiteBox
  31  * @run driver ClassFileInstaller -jar whitebox.jar sun.hotspot.WhiteBox
  32  * @run main/othervm/native ReplaceCriticalClasses
  33  */
  34 
  35 import java.util.regex.Matcher;
  36 import java.util.regex.Pattern;
  37 import jdk.test.lib.cds.CDSTestUtils;
  38 import jdk.test.lib.cds.CDSOptions;
  39 import jdk.test.lib.process.OutputAnalyzer;
  40 import sun.hotspot.WhiteBox;
  41 
  42 public class ReplaceCriticalClasses {
  43     public static void main(String args[]) throws Throwable {
  44         ReplaceCriticalClasses rcc = new ReplaceCriticalClasses();
  45         rcc.process(args);
  46     }
  47 
  48     public void process(String args[]) throws Throwable {
  49         if (args.length == 0) {
  50             launchChildProcesses(getTests());
  51         } else if (args.length == 3 && args[0].equals("child")) {
  52             Class klass = Class.forName(args[2].replace("/", "."));
  53             if (args[1].equals("-shared")) {
  54                 testInChild(true, klass);
  55             } else if (args[1].equals("-notshared")) {
  56                 testInChild(false, klass);
  57             } else {
  58                 throw new RuntimeException("Unknown child exec option " + args[1]);
  59             }
  60             return;
  61         } else {
  62             throw new RuntimeException("Usage: @run main/othervm/native ReplaceCriticalClasses");
  63         }
  64     }
  65 
  66     public String[] getTests() {
  67         String tests[] = {
  68             // CDS should be disabled -- these critical classes will be replaced
  69             // because JvmtiExport::early_class_hook_env() is true.
  70             "-early -notshared java/lang/Object",
  71             "-early -notshared java/lang/String",
  72             "-early -notshared java/lang/Cloneable",
  73             "-early -notshared java/io/Serializable",
  74 
  75             // CDS should not be disabled -- these critical classes cannot be replaced because
  76             // JvmtiExport::early_class_hook_env() is false.
  77             "java/lang/Object",
  78             "java/lang/String",
  79             "java/lang/Cloneable",
  80             "java/io/Serializable",
  81 
  82             /* Try to replace classes that are used by the archived subgraph graphs.
  83                The following test cases are in ReplaceCriticalClassesForSubgraphs.java.
  84             "-early -notshared -subgraph java/lang/module/ResolvedModule jdk.internal.module.ArchivedModuleGraph",
  85             "-early -notshared -subgraph java/lang/Long java.lang.Long$LongCache",
  86             "-subgraph java/lang/Long java.lang.Long$LongCache",
  87             */
  88 
  89             // Replace classes that are loaded after JVMTI_PHASE_PRIMORDIAL. It's OK to replace
  90             // such
  91             // classes even when CDS is enabled. Nothing bad should happen.
  92             "-notshared java/util/Locale",
  93             "-notshared sun/util/locale/BaseLocale",
  94             "-notshared java/lang/Readable",
  95         };
  96         return tests;
  97     }
  98 
  99     static void launchChildProcesses(String tests[]) throws Throwable {
 100         int n = 0;
 101         for (String s : tests) {
 102             System.out.println("Test case[" + (n++) + "] = \"" + s + "\"");
 103             String args[] = s.split("\\s+"); // split by space character
 104             launchChild(args);
 105         }
 106     }
 107 
 108     static void launchChild(String args[]) throws Throwable {
 109         if (args.length < 1) {
 110             throw new RuntimeException("Invalid test case. Should be <-early> <-subgraph> <-notshared> klassName subgraphKlass");
 111         }
 112         String klassName = null;
 113         String subgraphKlass = null;
 114         String early = "";
 115         boolean subgraph = false;
 116         String shared = "-shared";
 117 
 118         for (int i=0; i<args.length-1; i++) {
 119             String opt = args[i];
 120             if (opt.equals("-early")) {
 121                 early = "-early,";
 122             } else if (opt.equals("-subgraph")) {
 123                 subgraph = true;
 124             } else if (opt.equals("-notshared")) {
 125                 shared = opt;
 126             } else {
 127               if (!subgraph) {
 128                 throw new RuntimeException("Unknown option: " + opt);
 129               }
 130             }
 131         }
 132         if (subgraph) {
 133           klassName = args[args.length-2];
 134           subgraphKlass = args[args.length-1];
 135         } else {
 136           klassName = args[args.length-1];
 137         }
 138         Class.forName(klassName.replace("/", ".")); // make sure it's a valid class
 139         final String subgraphInit = "initialize_from_archived_subgraph " + subgraphKlass;
 140 
 141         // We will pass an option like "-agentlib:SimpleClassFileLoadHook=java/util/Locale,XXX,XXX".
 142         // The SimpleClassFileLoadHook agent would attempt to hook the java/util/Locale class
 143         // but leave the class file bytes unchanged (it replaces all bytes "XXX" with "XXX", i.e.,
 144         // a no-op). JVMTI doesn't check the class file bytes returned by the agent, so as long
 145         // as the agent returns a buffer, it will not load the class from CDS, and will instead
 146         // load the class by parsing the buffer.
 147         //
 148         // Note that for safety we don't change the contents of the class file bytes. If in the
 149         // future JVMTI starts checking the contents of the class file bytes, this test would need
 150         // to be updated. (You'd see the test case with java/util/Locale staring to fail).
 151         String agent = "-agentlib:SimpleClassFileLoadHook=" + early + klassName + ",XXX,XXX";
 152 
 153         CDSOptions opts = (new CDSOptions())
 154             .setXShareMode("auto")
 155             .setUseSystemArchive(true)
 156             .setUseVersion(false)
 157             .addSuffix("-showversion",
 158                        "-Xlog:cds",
 159                        "-XX:+UnlockDiagnosticVMOptions",
 160                        agent,
 161                        "-XX:+WhiteBoxAPI",
 162                        "-Xbootclasspath/a:" + ClassFileInstaller.getJarPath("whitebox.jar"));
 163 
 164         if (subgraph) {
 165             opts.addSuffix("-Xlog:cds,cds+heap");
 166         }
 167 
 168         opts.addSuffix("ReplaceCriticalClasses",
 169                        "child",
 170                        shared,
 171                        klassName);
 172 
 173         final boolean expectDisable = !early.equals("");
 174         final boolean checkSubgraph = subgraph;
 175         final boolean expectShared = shared.equals("-shared");
 176         CDSTestUtils.run(opts).assertNormalExit(out -> {
 177                 if (expectDisable) {
 178                     out.shouldContain("UseSharedSpaces: CDS is disabled because early JVMTI ClassFileLoadHook is in use.");
 179                     System.out.println("CDS disabled as expected");
 180                 }
 181                 if (checkSubgraph) {
 182                     if (expectShared) {
 183                         if (!out.getOutput().contains("UseSharedSpaces: Unable to map at required address in java heap")) {
 184                             out.shouldContain(subgraphInit);
 185                         }
 186                     } else {
 187                       out.shouldNotContain(subgraphInit);
 188                     }
 189                 }
 190             });
 191     }
 192 
 193     static void testInChild(boolean shouldBeShared, Class klass) {
 194         WhiteBox wb = WhiteBox.getWhiteBox();
 195 
 196         if (shouldBeShared && !wb.isSharedClass(klass)) {
 197             throw new RuntimeException(klass + " should be shared but but actually is not.");
 198         }
 199         if (!shouldBeShared && wb.isSharedClass(klass)) {
 200             throw new RuntimeException(klass + " should not be shared but actually is.");
 201         }
 202         System.out.println("wb.isSharedClass(klass): " + wb.isSharedClass(klass) + " == " + shouldBeShared);
 203 
 204         String strings[] = {
 205             // interned strings from j.l.Object
 206             "@",
 207             "nanosecond timeout value out of range",
 208             "timeoutMillis value is negative",
 209 
 210             // interned strings from j.l.Integer
 211             "0",
 212             "0X",
 213             "0x",
 214             "int"
 215         };
 216 
 217         // Make sure the interned string table is same
 218         for (String s : strings) {
 219             String i = s.intern();
 220             if (s != i) {
 221                 throw new RuntimeException("Interned string mismatch: \"" + s + "\" @ " + System.identityHashCode(s) +
 222                                            " vs \"" + i + "\" @ " + System.identityHashCode(i));
 223             }
 224         }
 225         // We have tried to use ClassFileLoadHook to replace critical library classes (which may
 226         // may not have succeeded, depending on whether the agent has requested
 227         // can_generate_all_class_hook_events/can_generate_early_class_hook_events capabilities).
 228         //
 229         // In any case, the JVM should have started properly (perhaps with CDS disabled) and
 230         // the above operations should succeed.
 231         System.out.println("If I can come to here without crashing, things should be OK");
 232     }
 233 }