1 /*
2  * Copyright (c) 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 /**
26  * @test
27  * @requires vm.cds
28  * @library /test/lib /test/hotspot/jtreg/runtime/cds/appcds
29  * @modules jdk.jartool/sun.tools.jar
30  * @build sun.hotspot.WhiteBox
31  * @run driver ClassFileInstaller sun.hotspot.WhiteBox sun.hotspot.WhiteBox$WhiteBoxPermission
32  * @run main/othervm/timeout=480 -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -Xbootclasspath/a:. MainModuleOnly
33  * @summary Test some scenarios with a main modular jar specified in the --module-path and -cp options in the command line.
34  */
35 
36 import java.io.File;
37 import java.nio.file.Files;
38 import java.nio.file.Path;
39 import java.nio.file.Paths;
40 import java.util.Arrays;
41 
42 import jdk.test.lib.process.OutputAnalyzer;
43 import jdk.test.lib.Platform;
44 
45 import jtreg.SkippedException;
46 import sun.hotspot.code.Compiler;
47 
48 public class MainModuleOnly extends DynamicArchiveTestBase {
49 
50     private static final Path USER_DIR = Paths.get(System.getProperty("user.dir"));
51 
52     private static final String FS = File.separator;
53     private static final String TEST_SRC = System.getProperty("test.src") +
54         FS + ".." + FS + "jigsaw" + FS + "modulepath";
55 
56     private static final Path SRC_DIR = Paths.get(TEST_SRC, "src");
57     private static final Path MODS_DIR = Paths.get("mods");
58 
59     // the module name of the test module
60     private static final String TEST_MODULE1 = "com.simple";
61 
62     // the module main class
63     private static final String MAIN_CLASS = "com.simple.Main";
64 
65     private static Path moduleDir = null;
66     private static Path moduleDir2 = null;
67     private static Path destJar = null;
68 
buildTestModule()69     public static void buildTestModule() throws Exception {
70 
71         // javac -d mods/$TESTMODULE --module-path MOD_DIR src/$TESTMODULE/**
72         JarBuilder.compileModule(SRC_DIR.resolve(TEST_MODULE1),
73                                  MODS_DIR.resolve(TEST_MODULE1),
74                                  MODS_DIR.toString());
75 
76 
77         moduleDir = Files.createTempDirectory(USER_DIR, "mlib");
78         moduleDir2 = Files.createTempDirectory(USER_DIR, "mlib2");
79 
80         Path srcJar = moduleDir.resolve(TEST_MODULE1 + ".jar");
81         destJar = moduleDir2.resolve(TEST_MODULE1 + ".jar");
82         String classes = MODS_DIR.resolve(TEST_MODULE1).toString();
83         JarBuilder.createModularJar(srcJar.toString(), classes, MAIN_CLASS);
84         Files.copy(srcJar, destJar);
85 
86     }
87 
testDefaultBase()88     static void testDefaultBase() throws Exception {
89         String topArchiveName = getNewArchiveName("top");
90         doTest(topArchiveName);
91     }
92 
main(String... args)93     public static void main(String... args) throws Exception {
94         runTest(MainModuleOnly::testDefaultBase);
95     }
96 
doTest(String topArchiveName)97     public static void doTest(String topArchiveName) throws Exception {
98         // compile the modules and create the modular jar files
99         buildTestModule();
100         // create an archive with both -cp and --module-path in the command line.
101         // Only the class in the modular jar in the --module-path will be archived;
102         // the class in the modular jar in the -cp won't be archived.
103         dump2(null, topArchiveName,
104               "-Xlog:cds+dynamic=debug,cds=debug",
105               "-cp", destJar.toString(),
106               "--module-path", moduleDir.toString(),
107               "-m", TEST_MODULE1)
108               .assertNormalExit(output -> {
109                       output.shouldContain("Buffer-space to target-space delta")
110                             .shouldContain("Written dynamic archive 0x");
111                   });
112 
113         // run with the archive using the same command line as in dump time.
114         // The main class should be loaded from the archive.
115         run2(null, topArchiveName,
116              "-Xlog:cds+dynamic=debug,cds=debug,class+load=trace",
117              "-cp", destJar.toString(),
118              "--module-path", moduleDir.toString(),
119              "-m", TEST_MODULE1)
120             .assertNormalExit(output -> {
121                     output.shouldContain("[class,load] com.simple.Main source: shared objects file")
122                           .shouldHaveExitValue(0);
123                 });
124 
125         // run with the archive with the main class name inserted before the -m.
126         // The main class name will be picked up before the module name. So the
127         // main class should be loaded from the jar in the -cp.
128         run2(null, topArchiveName,
129              "-Xlog:cds+dynamic=debug,cds=debug,class+load=trace",
130              "-cp", destJar.toString(),
131              "--module-path", moduleDir.toString(),
132              MAIN_CLASS, "-m", TEST_MODULE1)
133             .assertNormalExit(out ->
134                 out.shouldMatch(".class.load. com.simple.Main source:.*com.simple.jar"));
135 
136         // run with the archive with exploded module. Since during dump time, we
137         // only archive classes from the modular jar in the --module-path, the
138         // main class should be loaded from the exploded module directory.
139         run2(null, topArchiveName,
140              "-Xlog:cds+dynamic=debug,cds=debug,class+load=trace",
141              "-cp", destJar.toString(),
142              "--module-path", MODS_DIR.toString(),
143              "-m", TEST_MODULE1 + "/" + MAIN_CLASS)
144             .assertNormalExit(out -> {
145                 out.shouldMatch(".class.load. com.simple.Main source:.*com.simple")
146                    .shouldContain(MODS_DIR.toString());
147             });
148 
149         // run with the archive with the --upgrade-module-path option.
150         // CDS will be disabled with this options and the main class will be
151         // loaded from the modular jar.
152         run2(null, topArchiveName,
153              "-Xlog:cds+dynamic=debug,cds=debug,class+load=trace",
154              "-cp", destJar.toString(),
155              "--upgrade-module-path", moduleDir.toString(),
156              "--module-path", moduleDir.toString(),
157              "-m", TEST_MODULE1)
158             .assertSilentlyDisabledCDS(out -> {
159                 out.shouldHaveExitValue(0)
160                    .shouldMatch("CDS is disabled when the.*option is specified")
161                    .shouldMatch(".class.load. com.simple.Main source:.*com.simple.jar");
162             });
163 
164         boolean skippedTest = false;
165         if (!Compiler.isGraalEnabled()) {
166             // run with the archive with the --limit-modules option.
167             // CDS will be disabled with this options and the main class will be
168             // loaded from the modular jar.
169             run2(null, topArchiveName,
170                  "-Xlog:cds+dynamic=debug,cds=debug,class+load=trace",
171                  "-cp", destJar.toString(),
172                  "--limit-modules", "java.base," + TEST_MODULE1,
173                  "--module-path", moduleDir.toString(),
174                  "-m", TEST_MODULE1)
175                 .assertSilentlyDisabledCDS(out -> {
176                     out.shouldHaveExitValue(0)
177                        .shouldMatch("CDS is disabled when the.*option is specified")
178                        .shouldMatch(".class.load. com.simple.Main source:.*com.simple.jar");
179             });
180         } else {
181             skippedTest = true;
182         }
183         // run with the archive with the --patch-module option.
184         // CDS will be disabled with this options and the main class will be
185         // loaded from the modular jar.
186         run2(null, topArchiveName,
187              "-Xlog:cds+dynamic=debug,cds=debug,class+load=trace",
188              "-cp", destJar.toString(),
189              "--patch-module", TEST_MODULE1 + "=" + MODS_DIR.toString(),
190              "--module-path", moduleDir.toString(),
191              "-m", TEST_MODULE1)
192             .assertSilentlyDisabledCDS(out -> {
193                 out.shouldHaveExitValue(0)
194                    .shouldMatch("CDS is disabled when the.*option is specified")
195                    .shouldMatch(".class.load. com.simple.Main source:.*com.simple.jar");
196             });
197         // modify the timestamp of the jar file
198         (new File(destJar.toString())).setLastModified(System.currentTimeMillis() + 2000);
199         // run with the archive and the jar with modified timestamp.
200         // It should fail due to timestamp of the jar doesn't match the one
201         // used during dump time.
202         run2(null, topArchiveName,
203              "-Xlog:cds+dynamic=debug,cds=debug,class+load=trace",
204              "-cp", destJar.toString(),
205              "--module-path", moduleDir.toString(),
206              "-m", TEST_MODULE1)
207             .assertAbnormalExit(
208                 "A jar file is not the one used while building the shared archive file:");
209         // create an archive with a non-empty directory in the --module-path.
210         // The dumping process will exit with an error due to non-empty directory
211         // in the --module-path.
212         dump2(null, topArchiveName,
213               "-Xlog:cds+dynamic=debug,cds=debug",
214               "-cp", destJar.toString(),
215               "--module-path", MODS_DIR.toString(),
216               "-m", TEST_MODULE1 + "/" + MAIN_CLASS)
217             .assertAbnormalExit(output -> {
218                 output.shouldMatch("Error: non-empty directory.*com.simple");
219                 });
220 
221         // test module path with very long length
222         //
223         // This test can't be run on the windows platform due to an existing
224         // issue in ClassLoader::get_canonical_path() (JDK-8190737).
225         if (Platform.isWindows()) {
226             System.out.println("Long module path test cannot be tested on the Windows platform.");
227             return;
228         }
229         Path longDir = USER_DIR;
230         int pathLen = longDir.toString().length();
231         int PATH_LEN = 2034;
232         int MAX_DIR_LEN = 250;
233         while (pathLen < PATH_LEN) {
234             int remaining = PATH_LEN - pathLen;
235             int subPathLen = remaining > MAX_DIR_LEN ? MAX_DIR_LEN : remaining;
236             char[] chars = new char[subPathLen];
237             Arrays.fill(chars, 'x');
238             String subPath = new String(chars);
239             longDir = Paths.get(longDir.toString(), subPath);
240             pathLen = longDir.toString().length();
241         }
242         File longDirFile = new File(longDir.toString());
243         try {
244             longDirFile.mkdirs();
245         } catch (Exception e) {
246             throw e;
247         }
248         Path longDirJar = longDir.resolve(TEST_MODULE1 + ".jar");
249         // IOException results from the Files.copy() call on platform
250         // such as MacOS X. Test can't be proceeded further with the
251         // exception.
252         try {
253             Files.copy(destJar, longDirJar);
254         } catch (java.io.IOException ioe) {
255             System.out.println("Caught IOException from Files.copy(). Cannot continue.");
256             return;
257         }
258         dump2(null, topArchiveName,
259               "-Xlog:cds+dynamic=debug,cds=debug",
260               "-cp", destJar.toString(),
261               "-Xlog:exceptions=trace",
262               "--module-path", longDirJar.toString(),
263               "-m", TEST_MODULE1)
264             .ifAbnormalExit(output -> {
265                 output.shouldMatch("os::stat error.*CDS dump aborted");
266                 });
267 
268         if (skippedTest) {
269             throw new SkippedException("Skipped --limit-modules test; it can't be run with Graal enabled");
270         }
271     }
272 }
273