8230857: Avoid reflection in sun.tools.common.ProcessHelper
Reviewed-by: sspitsyn, dholmes
--- a/src/jdk.jcmd/linux/classes/sun/tools/ProcessHelper.java Mon Sep 23 11:37:08 2019 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,149 +0,0 @@
-/*
- * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package sun.tools;
-
-import java.io.IOException;
-import java.io.UncheckedIOException;
-import java.nio.file.Files;
-import java.nio.file.Paths;
-import java.util.jar.Attributes;
-import java.util.jar.JarFile;
-import java.util.stream.Stream;
-
-/**
- * A helper class that retrieves the main class name for
- * a running Java process using the proc filesystem (procfs)
- */
-public class ProcessHelper implements sun.tools.common.ProcessHelper {
-
-
- private static final String CMD_PREFIX = "cmd:";
- private static final ProcessHelper INSTANCE = new ProcessHelper();
-
- public static ProcessHelper getInstance() {
- return INSTANCE;
- }
-
- /**
- * Gets the main class name for the given Java process by parsing the
- * process command line. If the application was started with the <em>-jar</em>
- * option this method returns the name of the jar file. If the application
- * was started with <em>-m</em> or <em>--module</em> option, the method returns
- * the module name and the main class name.
- * @param pid - process ID (pid)
- * @return the main class name or null if the process no longer exists or
- * was started with a native launcher (e.g. jcmd etc)
- */
-
- public String getMainClass(String pid) {
- String cmdLine = getCommandLine(pid);
- if (cmdLine == null) {
- return null;
- }
- if (cmdLine.startsWith(CMD_PREFIX)) {
- cmdLine = cmdLine.substring(CMD_PREFIX.length());
- }
- String[] parts = cmdLine.split("\0");
- String mainClass = null;
-
- if(parts.length == 0) {
- return null;
- }
-
- // Check the executable
- String[] executablePath = parts[0].split("/");
- if (executablePath.length > 0) {
- String binaryName = executablePath[executablePath.length - 1];
- if (!"java".equals(binaryName)) {
- // Skip the process if it is not started with java launcher
- return null;
- }
- }
-
- // To be consistent with the behavior on other platforms, if -jar, -m, or --module
- // options are used then just return the value (the path to the jar file or module
- // name with a main class). Otherwise, the main class name is the first part that
- // is not a Java option (doesn't start with '-' and is not a classpath or a module
- // whitespace option).
-
- for (int i = 1; i < parts.length && mainClass == null; i++) {
- if (i < parts.length - 1) {
- if (parts[i].equals("-m") || parts[i].equals("--module") || parts[i].equals("-jar")) {
- return parts[i + 1];
- }
- }
-
- if (parts[i].startsWith("--module=")) {
- return parts[i].substring("--module=".length());
- }
-
- // If this is a classpath or a module whitespace option then skip the next part
- // (the classpath or the option value itself)
- if (parts[i].equals("-cp") || parts[i].equals("-classpath") || parts[i].equals("--class-path") ||
- isModuleWhiteSpaceOption(parts[i])) {
- i++;
- continue;
- }
- // Skip all other Java options
- if (parts[i].startsWith("-")) {
- continue;
- }
-
- // If it is a source-file mode then return null
- if (parts[i].endsWith(".java")) {
- return null;
- }
-
- mainClass = parts[i];
- }
- return mainClass;
-
- }
-
- private static String getCommandLine(String pid) {
- try (Stream<String> lines =
- Files.lines(Paths.get("/proc/" + pid + "/cmdline"))) {
- return lines.findFirst().orElse(null);
- } catch (IOException | UncheckedIOException e) {
- return null;
- }
- }
-
- private static boolean isModuleWhiteSpaceOption(String option) {
- return option.equals("-p") ||
- option.equals("--module-path") ||
- option.equals("--upgrade-module-path") ||
- option.equals("--add-modules") ||
- option.equals("--limit-modules") ||
- option.equals("--add-exports") ||
- option.equals("--add-opens") ||
- option.equals("--add-reads") ||
- option.equals("--patch-module");
- }
-
-}
-
-
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/src/jdk.jcmd/linux/classes/sun/tools/common/ProcessHelper.java Mon Sep 23 12:32:13 2019 +0200
@@ -0,0 +1,136 @@
+/*
+ * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.tools.common;
+
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.stream.Stream;
+
+/**
+ * A helper class that retrieves the main class name for
+ * a running Java process using the proc filesystem (procfs)
+ */
+final class ProcessHelper {
+
+ private static final String CMD_PREFIX = "cmd:";
+
+ /**
+ * Gets the main class name for the given Java process by parsing the
+ * process command line. If the application was started with the <em>-jar</em>
+ * option this method returns the name of the jar file. If the application
+ * was started with <em>-m</em> or <em>--module</em> option, the method returns
+ * the module name and the main class name.
+ * @param pid - process ID (pid)
+ * @return the main class name or null if the process no longer exists or
+ * was started with a native launcher (e.g. jcmd etc)
+ */
+ static String getMainClass(String pid) {
+ String cmdLine = getCommandLine(pid);
+ if (cmdLine == null) {
+ return null;
+ }
+ if (cmdLine.startsWith(CMD_PREFIX)) {
+ cmdLine = cmdLine.substring(CMD_PREFIX.length());
+ }
+ String[] parts = cmdLine.split("\0");
+ String mainClass = null;
+
+ if (parts.length == 0) {
+ return null;
+ }
+
+ // Check the executable
+ String[] executablePath = parts[0].split("/");
+ if (executablePath.length > 0) {
+ String binaryName = executablePath[executablePath.length - 1];
+ if (!"java".equals(binaryName)) {
+ // Skip the process if it is not started with java launcher
+ return null;
+ }
+ }
+
+ // To be consistent with the behavior on other platforms, if -jar, -m, or --module
+ // options are used then just return the value (the path to the jar file or module
+ // name with a main class). Otherwise, the main class name is the first part that
+ // is not a Java option (doesn't start with '-' and is not a classpath or a module
+ // whitespace option).
+
+ for (int i = 1; i < parts.length && mainClass == null; i++) {
+ if (i < parts.length - 1) {
+ if (parts[i].equals("-m") || parts[i].equals("--module") || parts[i].equals("-jar")) {
+ return parts[i + 1];
+ }
+ }
+
+ if (parts[i].startsWith("--module=")) {
+ return parts[i].substring("--module=".length());
+ }
+
+ // If this is a classpath or a module whitespace option then skip the next part
+ // (the classpath or the option value itself)
+ if (parts[i].equals("-cp") || parts[i].equals("-classpath") || parts[i].equals("--class-path") ||
+ isModuleWhiteSpaceOption(parts[i])) {
+ i++;
+ continue;
+ }
+ // Skip all other Java options
+ if (parts[i].startsWith("-")) {
+ continue;
+ }
+
+ // If it is a source-file mode then return null
+ if (parts[i].endsWith(".java")) {
+ return null;
+ }
+
+ mainClass = parts[i];
+ }
+ return mainClass;
+ }
+
+ private static String getCommandLine(String pid) {
+ try (Stream<String> lines =
+ Files.lines(Paths.get("/proc/" + pid + "/cmdline"))) {
+ return lines.findFirst().orElse(null);
+ } catch (IOException | UncheckedIOException e) {
+ return null;
+ }
+ }
+
+ private static boolean isModuleWhiteSpaceOption(String option) {
+ return option.equals("-p") ||
+ option.equals("--module-path") ||
+ option.equals("--upgrade-module-path") ||
+ option.equals("--add-modules") ||
+ option.equals("--limit-modules") ||
+ option.equals("--add-exports") ||
+ option.equals("--add-opens") ||
+ option.equals("--add-reads") ||
+ option.equals("--patch-module");
+ }
+}
--- a/src/jdk.jcmd/share/classes/sun/tools/common/ProcessArgumentMatcher.java Mon Sep 23 11:37:08 2019 +0200
+++ b/src/jdk.jcmd/share/classes/sun/tools/common/ProcessArgumentMatcher.java Mon Sep 23 12:32:13 2019 +0200
@@ -79,15 +79,10 @@
private static boolean check(VirtualMachineDescriptor vmd, String excludeClass, String partialMatch) {
- String mainClass = null;
+ // Try to get the main class name using (platform specific) ProcessHelper
+ String mainClass = ProcessHelper.getMainClass(vmd.id());
- // Get the main class name using platform specific helper
- ProcessHelper helper = ProcessHelper.platformProcessHelper();
- if (helper != null) {
- mainClass = helper.getMainClass(vmd.id());
- }
-
- // If the main class name is still unset then retrieve it with the attach mechanism
+ // If the main class name could not be retrieved by ProcessHelper, get it with the attach mechanism
if (mainClass == null) {
try {
VmIdentifier vmId = new VmIdentifier(vmd.id());
--- a/src/jdk.jcmd/share/classes/sun/tools/common/ProcessHelper.java Mon Sep 23 11:37:08 2019 +0200
+++ b/src/jdk.jcmd/share/classes/sun/tools/common/ProcessHelper.java Mon Sep 23 12:32:13 2019 +0200
@@ -25,33 +25,12 @@
package sun.tools.common;
-import java.lang.reflect.Method;
-
/**
* A helper class to retrieve the main class name for a running
- * Java process.
+ * Java process. Default implementation returns null. Platform specific
+ * implementation currently available for Linux only.
*/
-
-public interface ProcessHelper {
-
- /**
- * Returns an instance of the ProcessHelper class.
- *
- * @return ProcessHelper object or null if not supported on this platform.
- */
- public static ProcessHelper platformProcessHelper() {
- try {
- Class<?> c = Class.forName("sun.tools.ProcessHelper");
- @SuppressWarnings("unchecked")
- Method m = c.getMethod("getInstance");
- return (ProcessHelper) m.invoke(null);
- } catch (ClassNotFoundException e) {
- return null;
- } catch (ReflectiveOperationException e) {
- throw new InternalError(e);
- }
- }
-
+final class ProcessHelper {
/**
* Returns the main class name for the given Java process
@@ -59,6 +38,7 @@
* @param pid - process ID (pid)
* @return main class name or null if the main class could not be retrieved
*/
-
- String getMainClass(String pid);
+ static String getMainClass(String pid) {
+ return null;
+ }
}
--- a/test/jdk/sun/tools/jcmd/TestProcessHelper.java Mon Sep 23 11:37:08 2019 +0200
+++ b/test/jdk/sun/tools/jcmd/TestProcessHelper.java Mon Sep 23 12:32:13 2019 +0200
@@ -21,16 +21,13 @@
* questions.
*/
-import jdk.internal.module.ModuleInfoWriter;
-import jdk.test.lib.JDKToolFinder;
-import jdk.test.lib.process.ProcessTools;
-import jdk.test.lib.util.JarUtils;
-import sun.tools.common.ProcessHelper;
-
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
+import java.lang.invoke.MethodHandle;
+import java.lang.invoke.MethodHandles;
import java.lang.module.ModuleDescriptor;
+import java.lang.reflect.Method;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -44,6 +41,11 @@
import java.util.stream.Collectors;
import java.util.stream.Stream;
+import jdk.internal.module.ModuleInfoWriter;
+import jdk.test.lib.JDKToolFinder;
+import jdk.test.lib.process.ProcessTools;
+import jdk.test.lib.util.JarUtils;
+
/*
* @test
* @bug 8205654
@@ -52,15 +54,13 @@
*
* @requires os.family == "linux"
* @library /test/lib
- * @modules jdk.jcmd/sun.tools.common
+ * @modules jdk.jcmd/sun.tools.common:+open
* java.base/jdk.internal.module
* @build test.TestProcess
* @run main/othervm TestProcessHelper
*/
public class TestProcessHelper {
- private ProcessHelper PROCESS_HELPER = ProcessHelper.platformProcessHelper();
-
private static final String TEST_PROCESS_MAIN_CLASS_NAME = "TestProcess";
private static final String TEST_PROCESS_MAIN_CLASS_PACKAGE = "test";
private static final String TEST_PROCESS_MAIN_CLASS = TEST_PROCESS_MAIN_CLASS_PACKAGE + "."
@@ -89,6 +89,29 @@
private static final String[] PATCH_MODULE_OPTIONS = {"--patch-module", null};
+ private static final MethodHandle MH_GET_MAIN_CLASS = resolveMainClassMH();
+
+ private static MethodHandle resolveMainClassMH() {
+ try {
+ Method getMainClassMethod = Class
+ .forName("sun.tools.common.ProcessHelper")
+ .getDeclaredMethod("getMainClass", String.class);
+ getMainClassMethod.setAccessible(true);
+ return MethodHandles.lookup().unreflect(getMainClassMethod);
+ } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalAccessException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private static String callGetMainClass(Process p) {
+ try {
+ return (String)MH_GET_MAIN_CLASS.invoke(Long.toString(p.pid()));
+ } catch (Throwable e) {
+ throw new RuntimeException(e);
+ }
+
+ }
+
public static void main(String[] args) throws Exception {
new TestProcessHelper().runTests();
}
@@ -188,7 +211,7 @@
}
private void checkMainClass(Process p, String expectedMainClass) {
- String mainClass = PROCESS_HELPER.getMainClass(Long.toString(p.pid()));
+ String mainClass = callGetMainClass(p);
// getMainClass() may return null, e.g. due to timing issues.
// Attempt some limited retries.
if (mainClass == null) {
@@ -204,7 +227,7 @@
} catch (InterruptedException e) {
// ignore
}
- mainClass = PROCESS_HELPER.getMainClass(Long.toString(p.pid()));
+ mainClass = callGetMainClass(p);
retrycount++;
sleepms *= 2;
}