1 /*
  2  * Copyright (c) 2019, 2024, 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 import java.io.File;
 25 import java.io.IOException;
 26 import java.io.OutputStream;
 27 import java.lang.invoke.MethodHandle;
 28 import java.lang.invoke.MethodHandles;
 29 import java.lang.module.ModuleDescriptor;
 30 import java.lang.reflect.Method;
 31 import java.nio.file.FileSystems;
 32 import java.nio.file.Files;
 33 import java.nio.file.Path;
 34 import java.util.ArrayList;
 35 import java.util.LinkedList;
 36 import java.util.List;
 37 import java.util.jar.Attributes;
 38 import java.util.jar.JarEntry;
 39 import java.util.jar.JarOutputStream;
 40 import java.util.jar.Manifest;
 41 import java.util.stream.Collectors;
 42 import java.util.stream.Stream;
 43 
 44 import jdk.test.lib.JDKToolFinder;
 45 import jdk.test.lib.process.ProcessTools;
 46 import jdk.test.lib.util.JarUtils;
 47 import jdk.test.lib.util.ModuleInfoWriter;
 48 
 49 /*
 50  * @test
 51  * @bug 8205654
 52  * @summary Unit test for sun.tools.ProcessHelper class. The test launches Java processes with different Java options
 53  * and checks that sun.tools.ProcessHelper.getMainClass(pid) method returns a correct main class.
 54  *
 55  * @requires vm.flagless
 56  * @requires os.family == "linux"
 57  * @modules jdk.jcmd/sun.tools.common:+open
 58  *          java.base/jdk.internal.module
 59  * @library /test/lib
 60  * @build test.TestProcess
 61  *        jdk.test.lib.util.JarUtils
 62  * @run main/othervm TestProcessHelper
 63  */
 64 public class TestProcessHelper {
 65 
 66     private static final String TEST_PROCESS_MAIN_CLASS_NAME = "TestProcess";
 67     private static final String TEST_PROCESS_MAIN_CLASS_PACKAGE = "test";
 68     private static final String TEST_PROCESS_MAIN_CLASS = TEST_PROCESS_MAIN_CLASS_PACKAGE + "."
 69             + TEST_PROCESS_MAIN_CLASS_NAME;
 70     private static final Path TEST_CLASSES = FileSystems.getDefault().getPath(System.getProperty("test.classes"));
 71     private static final Path USER_DIR = FileSystems.getDefault().getPath(System.getProperty("user.dir", "."));
 72     private static final Path TEST_MODULES = USER_DIR.resolve("testmodules");
 73     private static final String JAVA_PATH = JDKToolFinder.getJDKTool("java");
 74     private static final Path TEST_CLASS = TEST_CLASSES.resolve(TEST_PROCESS_MAIN_CLASS_PACKAGE)
 75             .resolve(TEST_PROCESS_MAIN_CLASS_NAME + ".class");
 76 
 77     private static final String[] CP_OPTIONS = {"-cp", "-classpath", "--class-path"};
 78     private static final String[][] VM_ARGS = {{}, {"-Dtest1=aaa"}, {"-Dtest1=aaa", "-Dtest2=bbb ccc"}};
 79     private static final String[][] ARGS = {{}, {"param1"}, {"param1", "param2"}};
 80     private static final String[] MP_OPTIONS = {"-p", "--module-path"};
 81     private static final String[] MODULE_OPTIONS = {"-m", "--module", "--module="};
 82     private static final String JAR_OPTION = "-jar";
 83     private static final String MODULE_NAME = "module1";
 84     private static final String[][] EXTRA_MODULAR_OPTIONS = {null,
 85             {"--add-opens", "java.base/java.net=ALL-UNNAMED"},
 86             {"--add-exports", "java.base/java.net=ALL-UNNAMED"},
 87             {"--add-reads", "java.base/java.net=ALL-UNNAMED"},
 88             {"--add-modules", "java.management"},
 89             {"--limit-modules", "java.management"},
 90             {"--upgrade-module-path", "test"}};
 91 
 92     private static final String[] PATCH_MODULE_OPTIONS = {"--patch-module", null};
 93 
 94     private static final MethodHandle MH_GET_MAIN_CLASS = resolveMainClassMH();
 95 
 96     private static MethodHandle resolveMainClassMH() {
 97         try {
 98             Method getMainClassMethod = Class
 99                 .forName("sun.tools.common.ProcessHelper")
100                 .getDeclaredMethod("getMainClass", String.class);
101             getMainClassMethod.setAccessible(true);
102             return MethodHandles.lookup().unreflect(getMainClassMethod);
103         } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalAccessException e) {
104             throw new RuntimeException(e);
105         }
106     }
107 
108     private static String callGetMainClass(Process p) {
109         try {
110             return (String)MH_GET_MAIN_CLASS.invoke(Long.toString(p.pid()));
111         } catch (Throwable e) {
112             throw new RuntimeException(e);
113         }
114 
115     }
116 
117     public static void main(String[] args) throws Exception {
118         new TestProcessHelper().runTests();
119     }
120 
121     public void runTests() throws Exception {
122         testClassPath();
123         testJar();
124         testModule();
125     }
126 
127     // Test Java processes that are started with -classpath, -cp, or --class-path options
128     // and with different combinations of VM and program args.
129     private void testClassPath() throws Exception {
130         for (String cp : CP_OPTIONS) {
131             for (String[] vma : VM_ARGS) {
132                 for (String[] arg : ARGS) {
133                     for (String[] modularOptions : EXTRA_MODULAR_OPTIONS) {
134                         List<String> cmd = new LinkedList<>();
135                         cmd.add(JAVA_PATH);
136                         cmd.add(cp);
137                         cmd.add(TEST_CLASSES.toAbsolutePath().toString());
138                         for (String v : vma) {
139                             cmd.add(v);
140                         }
141                         if (modularOptions != null) {
142                             cmd.add(modularOptions[0]);
143                             cmd.add(modularOptions[1]);
144                         }
145                         cmd.add(TEST_PROCESS_MAIN_CLASS);
146                         for (String a : arg) {
147                             cmd.add(a);
148                         }
149                         testProcessHelper(cmd, TEST_PROCESS_MAIN_CLASS);
150                     }
151                 }
152             }
153         }
154     }
155 
156     // Test Java processes that are started with -jar option
157     // and with different combinations of VM and program args.
158     private void testJar() throws Exception {
159         File jarFile = prepareJar();
160         for (String[] vma : VM_ARGS) {
161             for (String[] arg : ARGS) {
162                 List<String> cmd = new LinkedList<>();
163                 cmd.add(JAVA_PATH);
164                 for (String v : vma) {
165                     cmd.add(v);
166                 }
167                 cmd.add(JAR_OPTION);
168                 cmd.add(jarFile.getAbsolutePath());
169                 for (String a : arg) {
170                     cmd.add(a);
171                 }
172                 testProcessHelper(cmd, jarFile.getAbsolutePath());
173             }
174         }
175 
176     }
177 
178     // Test Java processes that are started with -m or --module options
179     // and with different combination of VM and program args.
180     private void testModule() throws Exception {
181         prepareModule();
182         for (String mp : MP_OPTIONS) {
183             for (String m : MODULE_OPTIONS) {
184                 for (String[] vma : VM_ARGS) {
185                     for (String[] arg : ARGS) {
186                         for(String patchModuleOption : PATCH_MODULE_OPTIONS) {
187                             List<String> cmd = new LinkedList<>();
188                             cmd.add(JAVA_PATH);
189                             cmd.add(mp);
190                             cmd.add(TEST_MODULES.toAbsolutePath().toString());
191                             if (patchModuleOption != null) {
192                                 cmd.add(patchModuleOption);
193                                 cmd.add(MODULE_NAME + "=" + TEST_MODULES.toAbsolutePath().toString());
194                             }
195                             for (String v : vma) {
196                                 cmd.add(v);
197                             }
198                             if (m.endsWith("=")) {
199                                 cmd.add(m + MODULE_NAME + "/" + TEST_PROCESS_MAIN_CLASS);
200                             } else {
201                                 cmd.add(m);
202                                 cmd.add(MODULE_NAME + "/" + TEST_PROCESS_MAIN_CLASS);
203                             }
204                             for (String a : arg) {
205                                 cmd.add(a);
206                             }
207                             testProcessHelper(cmd, MODULE_NAME + "/" + TEST_PROCESS_MAIN_CLASS);
208                         }
209                     }
210                 }
211             }
212         }
213     }
214 
215     private void checkMainClass(Process p, String expectedMainClass) {
216         String mainClass = callGetMainClass(p);
217         // getMainClass() may return null, e.g. due to timing issues.
218         // Attempt some limited retries.
219         if (mainClass == null) {
220             System.err.println("Main class returned by ProcessHelper was null.");
221             // sleep time doubles each round, altogether, wait no longer than 1 sec
222             final int MAX_RETRIES = 10;
223             int retrycount = 0;
224             long sleepms = 1;
225             while (retrycount < MAX_RETRIES && mainClass == null) {
226                 System.err.println("Retry " + retrycount + ", sleeping for " + sleepms + "ms.");
227                 try {
228                     Thread.sleep(sleepms);
229                 } catch (InterruptedException e) {
230                     // ignore
231                 }
232                 mainClass = callGetMainClass(p);
233                 retrycount++;
234                 sleepms *= 2;
235             }
236         }
237         p.destroyForcibly();
238         if (!expectedMainClass.equals(mainClass)) {
239             throw new RuntimeException("Main class is wrong: " + mainClass);
240         }
241     }
242 
243     private void testProcessHelper(List<String> args, String expectedValue) throws Exception {
244         ProcessBuilder pb = new ProcessBuilder(args);
245         String cmd = pb.command().stream().collect(Collectors.joining(" "));
246         System.out.println("Starting the process:" + cmd);
247         Process p = ProcessTools.startProcess("test", pb);
248         if (!p.isAlive()) {
249             throw new RuntimeException("Cannot start the process: " + cmd);
250         }
251         checkMainClass(p, expectedValue);
252     }
253 
254     private File prepareJar() throws Exception {
255         Path jarFile = USER_DIR.resolve("testprocess.jar");
256         Manifest manifest = createManifest();
257         JarUtils.createJarFile(jarFile, manifest, TEST_CLASSES, TEST_CLASS);
258         return jarFile.toFile();
259     }
260 
261     private void prepareModule() throws Exception {
262         TEST_MODULES.toFile().mkdirs();
263         Path moduleJar = TEST_MODULES.resolve("mod1.jar");
264         ModuleDescriptor md = createModuleDescriptor();
265         createModuleJarFile(moduleJar, md, TEST_CLASSES, TEST_CLASS);
266     }
267 
268     private Manifest createManifest() {
269         Manifest manifest = new Manifest();
270         manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
271         manifest.getMainAttributes().put(Attributes.Name.MAIN_CLASS, TEST_PROCESS_MAIN_CLASS);
272         return manifest;
273     }
274 
275     private ModuleDescriptor createModuleDescriptor() {
276         ModuleDescriptor.Builder builder
277                 = ModuleDescriptor.newModule(MODULE_NAME).requires("java.base");
278         return builder.build();
279     }
280 
281     private static void createModuleJarFile(Path jarfile, ModuleDescriptor md, Path dir, Path... files)
282             throws IOException {
283 
284         Path parent = jarfile.getParent();
285         if (parent != null) {
286             Files.createDirectories(parent);
287         }
288 
289         List<Path> entries = findAllRegularFiles(dir, files);
290 
291         try (OutputStream out = Files.newOutputStream(jarfile);
292              JarOutputStream jos = new JarOutputStream(out)) {
293             if (md != null) {
294                 JarEntry je = new JarEntry("module-info.class");
295                 jos.putNextEntry(je);
296                 ModuleInfoWriter.write(md, jos);
297                 jos.closeEntry();
298             }
299 
300             for (Path entry : entries) {
301                 String name = toJarEntryName(entry);
302                 jos.putNextEntry(new JarEntry(name));
303                 Files.copy(dir.resolve(entry), jos);
304                 jos.closeEntry();
305             }
306         }
307     }
308 
309     private static String toJarEntryName(Path file) {
310         Path normalized = file.normalize();
311         return normalized.subpath(0, normalized.getNameCount())
312                 .toString()
313                 .replace(File.separatorChar, '/');
314     }
315 
316     private static List<Path> findAllRegularFiles(Path dir, Path[] files) throws IOException {
317         List<Path> entries = new ArrayList<>();
318         for (Path file : files) {
319             try (Stream<Path> stream = Files.find(dir.resolve(file), Integer.MAX_VALUE,
320                     (p, attrs) -> attrs.isRegularFile())) {
321                 stream.map(dir::relativize)
322                         .forEach(entries::add);
323             }
324         }
325         return entries;
326     }
327 
328 }