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