From cc8bd63741ce5745c144bf21b737c287d9b53817 Mon Sep 17 00:00:00 2001 From: Matthias Baesken Date: Tue, 19 Nov 2024 13:44:11 +0000 Subject: [PATCH 01/74] 8344036: Tests tools/jlink/runtimeImage fail on AIX after JDK-8311302 Reviewed-by: sgehwolf --- test/jdk/tools/jlink/runtimeImage/AddOptionsTest.java | 2 +- .../tools/jlink/runtimeImage/BasicJlinkMissingJavaBase.java | 2 +- test/jdk/tools/jlink/runtimeImage/BasicJlinkTest.java | 2 +- test/jdk/tools/jlink/runtimeImage/CustomModuleJlinkTest.java | 2 +- test/jdk/tools/jlink/runtimeImage/GenerateJLIClassesTest.java | 2 +- test/jdk/tools/jlink/runtimeImage/JavaSEReproducibleTest.java | 2 +- .../tools/jlink/runtimeImage/KeepPackagedModulesFailTest.java | 2 +- test/jdk/tools/jlink/runtimeImage/ModifiedFilesExitTest.java | 2 +- .../jdk/tools/jlink/runtimeImage/ModifiedFilesWarningTest.java | 2 +- test/jdk/tools/jlink/runtimeImage/MultiHopTest.java | 2 +- .../runtimeImage/PackagedModulesVsRuntimeImageLinkTest.java | 3 ++- .../tools/jlink/runtimeImage/PatchedJDKModuleJlinkTest.java | 2 +- test/jdk/tools/jlink/runtimeImage/SystemModulesTest.java | 2 +- test/jdk/tools/jlink/runtimeImage/SystemModulesTest2.java | 2 +- 14 files changed, 15 insertions(+), 14 deletions(-) diff --git a/test/jdk/tools/jlink/runtimeImage/AddOptionsTest.java b/test/jdk/tools/jlink/runtimeImage/AddOptionsTest.java index 1ffe1240d07e7..827f7da624d30 100644 --- a/test/jdk/tools/jlink/runtimeImage/AddOptionsTest.java +++ b/test/jdk/tools/jlink/runtimeImage/AddOptionsTest.java @@ -40,7 +40,7 @@ * jdk.jlink/jdk.tools.jimage * @build tests.* jdk.test.lib.process.OutputAnalyzer * jdk.test.lib.process.ProcessTools - * @run main/othervm -Xmx1g AddOptionsTest + * @run main/othervm -Xmx1400m AddOptionsTest */ public class AddOptionsTest extends AbstractLinkableRuntimeTest { diff --git a/test/jdk/tools/jlink/runtimeImage/BasicJlinkMissingJavaBase.java b/test/jdk/tools/jlink/runtimeImage/BasicJlinkMissingJavaBase.java index b0d2a2d66f5b3..ebf5b060665fc 100644 --- a/test/jdk/tools/jlink/runtimeImage/BasicJlinkMissingJavaBase.java +++ b/test/jdk/tools/jlink/runtimeImage/BasicJlinkMissingJavaBase.java @@ -41,7 +41,7 @@ * jdk.jlink/jdk.tools.jimage * @build tests.* jdk.test.lib.process.OutputAnalyzer * jdk.test.lib.process.ProcessTools - * @run main/othervm -Xmx1g BasicJlinkMissingJavaBase + * @run main/othervm -Xmx1400m BasicJlinkMissingJavaBase */ public class BasicJlinkMissingJavaBase extends AbstractLinkableRuntimeTest { diff --git a/test/jdk/tools/jlink/runtimeImage/BasicJlinkTest.java b/test/jdk/tools/jlink/runtimeImage/BasicJlinkTest.java index b97ebff9b4906..8cbd74e5ed1cb 100644 --- a/test/jdk/tools/jlink/runtimeImage/BasicJlinkTest.java +++ b/test/jdk/tools/jlink/runtimeImage/BasicJlinkTest.java @@ -39,7 +39,7 @@ * jdk.jlink/jdk.tools.jimage * @build tests.* jdk.test.lib.process.OutputAnalyzer * jdk.test.lib.process.ProcessTools - * @run main/othervm -Xmx1g BasicJlinkTest false + * @run main/othervm -Xmx1400m BasicJlinkTest false */ public class BasicJlinkTest extends AbstractLinkableRuntimeTest { diff --git a/test/jdk/tools/jlink/runtimeImage/CustomModuleJlinkTest.java b/test/jdk/tools/jlink/runtimeImage/CustomModuleJlinkTest.java index 369bccfecfce4..d6c237a173b72 100644 --- a/test/jdk/tools/jlink/runtimeImage/CustomModuleJlinkTest.java +++ b/test/jdk/tools/jlink/runtimeImage/CustomModuleJlinkTest.java @@ -39,7 +39,7 @@ * jdk.jlink/jdk.tools.jimage * @build tests.* jdk.test.lib.process.OutputAnalyzer * jdk.test.lib.process.ProcessTools - * @run main/othervm -Xmx1g CustomModuleJlinkTest + * @run main/othervm -Xmx1400m CustomModuleJlinkTest */ public class CustomModuleJlinkTest extends AbstractLinkableRuntimeTest { diff --git a/test/jdk/tools/jlink/runtimeImage/GenerateJLIClassesTest.java b/test/jdk/tools/jlink/runtimeImage/GenerateJLIClassesTest.java index 533a8db30d0cc..e59d18bd6f05c 100644 --- a/test/jdk/tools/jlink/runtimeImage/GenerateJLIClassesTest.java +++ b/test/jdk/tools/jlink/runtimeImage/GenerateJLIClassesTest.java @@ -39,7 +39,7 @@ * jdk.jlink/jdk.tools.jimage * @build tests.* jdk.test.lib.process.OutputAnalyzer * jdk.test.lib.process.ProcessTools - * @run main/othervm -Xmx1g GenerateJLIClassesTest + * @run main/othervm -Xmx1400m GenerateJLIClassesTest */ public class GenerateJLIClassesTest extends AbstractLinkableRuntimeTest { diff --git a/test/jdk/tools/jlink/runtimeImage/JavaSEReproducibleTest.java b/test/jdk/tools/jlink/runtimeImage/JavaSEReproducibleTest.java index d923358aed90d..a376d075ecd07 100644 --- a/test/jdk/tools/jlink/runtimeImage/JavaSEReproducibleTest.java +++ b/test/jdk/tools/jlink/runtimeImage/JavaSEReproducibleTest.java @@ -40,7 +40,7 @@ * jdk.jlink/jdk.tools.jimage * @build tests.* jdk.test.lib.process.OutputAnalyzer * jdk.test.lib.process.ProcessTools - * @run main/othervm -Xmx1g JavaSEReproducibleTest + * @run main/othervm -Xmx1400m JavaSEReproducibleTest */ public class JavaSEReproducibleTest extends AbstractLinkableRuntimeTest { diff --git a/test/jdk/tools/jlink/runtimeImage/KeepPackagedModulesFailTest.java b/test/jdk/tools/jlink/runtimeImage/KeepPackagedModulesFailTest.java index 8094579ecd505..6fdaf5a9824b8 100644 --- a/test/jdk/tools/jlink/runtimeImage/KeepPackagedModulesFailTest.java +++ b/test/jdk/tools/jlink/runtimeImage/KeepPackagedModulesFailTest.java @@ -41,7 +41,7 @@ * jdk.jlink/jdk.tools.jimage * @build tests.* jdk.test.lib.process.OutputAnalyzer * jdk.test.lib.process.ProcessTools - * @run main/othervm -Xmx1g KeepPackagedModulesFailTest + * @run main/othervm -Xmx1400m KeepPackagedModulesFailTest */ public class KeepPackagedModulesFailTest extends AbstractLinkableRuntimeTest { diff --git a/test/jdk/tools/jlink/runtimeImage/ModifiedFilesExitTest.java b/test/jdk/tools/jlink/runtimeImage/ModifiedFilesExitTest.java index 709494b62566a..90abe14c2148f 100644 --- a/test/jdk/tools/jlink/runtimeImage/ModifiedFilesExitTest.java +++ b/test/jdk/tools/jlink/runtimeImage/ModifiedFilesExitTest.java @@ -40,7 +40,7 @@ * jdk.jlink/jdk.tools.jimage * @build tests.* jdk.test.lib.process.OutputAnalyzer * jdk.test.lib.process.ProcessTools - * @run main/othervm -Xmx1g ModifiedFilesExitTest + * @run main/othervm -Xmx1400m ModifiedFilesExitTest */ public class ModifiedFilesExitTest extends ModifiedFilesTest { diff --git a/test/jdk/tools/jlink/runtimeImage/ModifiedFilesWarningTest.java b/test/jdk/tools/jlink/runtimeImage/ModifiedFilesWarningTest.java index f52691dd85927..935d80dee4fb9 100644 --- a/test/jdk/tools/jlink/runtimeImage/ModifiedFilesWarningTest.java +++ b/test/jdk/tools/jlink/runtimeImage/ModifiedFilesWarningTest.java @@ -39,7 +39,7 @@ * jdk.jlink/jdk.tools.jimage * @build tests.* jdk.test.lib.process.OutputAnalyzer * jdk.test.lib.process.ProcessTools - * @run main/othervm -Xmx1g ModifiedFilesWarningTest + * @run main/othervm -Xmx1400m ModifiedFilesWarningTest */ public class ModifiedFilesWarningTest extends ModifiedFilesTest { diff --git a/test/jdk/tools/jlink/runtimeImage/MultiHopTest.java b/test/jdk/tools/jlink/runtimeImage/MultiHopTest.java index 88f91f238bd87..0e2cabe7425c8 100644 --- a/test/jdk/tools/jlink/runtimeImage/MultiHopTest.java +++ b/test/jdk/tools/jlink/runtimeImage/MultiHopTest.java @@ -40,7 +40,7 @@ * jdk.jlink/jdk.tools.jimage * @build tests.* jdk.test.lib.process.OutputAnalyzer * jdk.test.lib.process.ProcessTools - * @run main/othervm -Xmx1g MultiHopTest + * @run main/othervm -Xmx1400m MultiHopTest */ public class MultiHopTest extends AbstractLinkableRuntimeTest { diff --git a/test/jdk/tools/jlink/runtimeImage/PackagedModulesVsRuntimeImageLinkTest.java b/test/jdk/tools/jlink/runtimeImage/PackagedModulesVsRuntimeImageLinkTest.java index 9910be5f91974..d276e80702b40 100644 --- a/test/jdk/tools/jlink/runtimeImage/PackagedModulesVsRuntimeImageLinkTest.java +++ b/test/jdk/tools/jlink/runtimeImage/PackagedModulesVsRuntimeImageLinkTest.java @@ -49,7 +49,7 @@ * jdk.jlink/jdk.tools.jimage * @build tests.* jdk.test.lib.process.OutputAnalyzer * jdk.test.lib.process.ProcessTools - * @run main/othervm -Xmx1g PackagedModulesVsRuntimeImageLinkTest + * @run main/othervm/timeout=1200 -Xmx1400m PackagedModulesVsRuntimeImageLinkTest */ public class PackagedModulesVsRuntimeImageLinkTest extends AbstractLinkableRuntimeTest { @@ -76,6 +76,7 @@ void runTest(Helper helper, boolean isLinkableRuntime) throws Exception { .output(helper.createNewImageDir("java-se-jmodfull")) .addMods("java.se").call().assertSuccess(); + System.out.println("Now comparing jmod-less and jmod-full) images"); compareRecursively(javaSEruntimeLink, javaSEJmodFull); } diff --git a/test/jdk/tools/jlink/runtimeImage/PatchedJDKModuleJlinkTest.java b/test/jdk/tools/jlink/runtimeImage/PatchedJDKModuleJlinkTest.java index 3baa824e04990..f83c4c698f16b 100644 --- a/test/jdk/tools/jlink/runtimeImage/PatchedJDKModuleJlinkTest.java +++ b/test/jdk/tools/jlink/runtimeImage/PatchedJDKModuleJlinkTest.java @@ -42,7 +42,7 @@ * jdk.jlink/jdk.tools.jimage * @build tests.* jdk.test.lib.process.OutputAnalyzer * jdk.test.lib.process.ProcessTools - * @run main/othervm -Xmx1g PatchedJDKModuleJlinkTest + * @run main/othervm -Xmx1400m PatchedJDKModuleJlinkTest */ public class PatchedJDKModuleJlinkTest extends AbstractLinkableRuntimeTest { diff --git a/test/jdk/tools/jlink/runtimeImage/SystemModulesTest.java b/test/jdk/tools/jlink/runtimeImage/SystemModulesTest.java index fac8cac112d14..d0a6234eec0ce 100644 --- a/test/jdk/tools/jlink/runtimeImage/SystemModulesTest.java +++ b/test/jdk/tools/jlink/runtimeImage/SystemModulesTest.java @@ -41,7 +41,7 @@ * jdk.jlink/jdk.tools.jimage * @build tests.* jdk.test.lib.process.OutputAnalyzer * jdk.test.lib.process.ProcessTools - * @run main/othervm -Xmx1g SystemModulesTest + * @run main/othervm -Xmx1400m SystemModulesTest */ public class SystemModulesTest extends AbstractLinkableRuntimeTest { diff --git a/test/jdk/tools/jlink/runtimeImage/SystemModulesTest2.java b/test/jdk/tools/jlink/runtimeImage/SystemModulesTest2.java index 6be4ad7321cea..ee22a55f3a751 100644 --- a/test/jdk/tools/jlink/runtimeImage/SystemModulesTest2.java +++ b/test/jdk/tools/jlink/runtimeImage/SystemModulesTest2.java @@ -42,7 +42,7 @@ * jdk.jlink/jdk.tools.jimage * @build tests.* jdk.test.lib.process.OutputAnalyzer * jdk.test.lib.process.ProcessTools - * @run main/othervm -Xmx1g SystemModulesTest2 + * @run main/othervm -Xmx1400m SystemModulesTest2 */ public class SystemModulesTest2 extends AbstractLinkableRuntimeTest { From 41436bb0e81ddf08fea189d9e1d020fb0ce8979b Mon Sep 17 00:00:00 2001 From: Alexey Semenyuk Date: Tue, 19 Nov 2024 13:52:31 +0000 Subject: [PATCH 02/74] 8336087: Doccheck: the jpackage command page doesn't show the correct command-line options Reviewed-by: almatvee --- src/jdk.jpackage/share/man/jpackage.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/jdk.jpackage/share/man/jpackage.md b/src/jdk.jpackage/share/man/jpackage.md index 228c0b1325920..21f07db0bb892 100644 --- a/src/jdk.jpackage/share/man/jpackage.md +++ b/src/jdk.jpackage/share/man/jpackage.md @@ -438,7 +438,7 @@ The `jpackage` tool will take as input a Java application and a Java run-time im `--linux-app-category` *category-value* -: Group value of the RPM /.spec file or +: Group value of the RPM \.spec file or Section value of DEB control file `--linux-shortcut` From 0714114fe3e0ac01657053164c61cbb702c0f9a0 Mon Sep 17 00:00:00 2001 From: Alexey Semenyuk Date: Tue, 19 Nov 2024 13:53:45 +0000 Subject: [PATCH 03/74] 8344322: Improve capabilities of jpackage test lib to validate error output of jpackage Reviewed-by: almatvee --- .../jpackage/test/CannedFormattedString.java | 53 +++++++++++++ .../jdk/jpackage/test/JPackageCommand.java | 24 ++++++ .../jpackage/test/JPackageStringBundle.java | 67 ++++++++++++++++ .../helpers/jdk/jpackage/test/TKit.java | 34 ++++++++- test/jdk/tools/jpackage/share/ErrorTest.java | 76 ++++++++++--------- 5 files changed, 217 insertions(+), 37 deletions(-) create mode 100644 test/jdk/tools/jpackage/helpers/jdk/jpackage/test/CannedFormattedString.java create mode 100644 test/jdk/tools/jpackage/helpers/jdk/jpackage/test/JPackageStringBundle.java diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/CannedFormattedString.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/CannedFormattedString.java new file mode 100644 index 0000000000000..8b28049b7b17e --- /dev/null +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/CannedFormattedString.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2024, 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. + * + * 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 jdk.jpackage.test; + +import java.util.List; +import java.util.function.BiFunction; + +public final class CannedFormattedString { + + CannedFormattedString(BiFunction formatter, + String key, Object[] args) { + this.formatter = formatter; + this.key = key; + this.args = args; + } + + public String getValue() { + return formatter.apply(key, args); + } + + @Override + public String toString() { + if (args.length == 0) { + return String.format("%s", key); + } else { + return String.format("%s+%s", key, List.of(args)); + } + } + + private final BiFunction formatter; + private final String key; + private final Object[] args; +} diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/JPackageCommand.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/JPackageCommand.java index 9b25c9058d184..49eeb25a00edb 100644 --- a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/JPackageCommand.java +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/JPackageCommand.java @@ -78,6 +78,7 @@ public JPackageCommand(JPackageCommand cmd) { prerequisiteActions = new Actions(cmd.prerequisiteActions); verifyActions = new Actions(cmd.verifyActions); appLayoutAsserts = cmd.appLayoutAsserts; + outputValidator = cmd.outputValidator; executeInDirectory = cmd.executeInDirectory; } @@ -739,6 +740,24 @@ public JPackageCommand ignoreDefaultVerbose(boolean v) { return this; } + public JPackageCommand validateOutput(TKit.TextStreamVerifier validator) { + return JPackageCommand.this.validateOutput(validator::apply); + } + + public JPackageCommand validateOutput(Consumer> validator) { + if (validator != null) { + saveConsoleOutput(true); + outputValidator = validator; + } else { + outputValidator = null; + } + return this; + } + + public JPackageCommand validateOutput(CannedFormattedString str) { + return JPackageCommand.this.validateOutput(TKit.assertTextStream(str.getValue())); + } + public boolean isWithToolProvider() { return Optional.ofNullable(withToolProvider).orElse( defaultWithToolProvider); @@ -817,6 +836,10 @@ public Executor.Result execute(int expectedExitCode) { .createExecutor() .execute(expectedExitCode); + if (outputValidator != null) { + outputValidator.accept(result.getOutput().stream()); + } + if (result.exitCode == 0) { executeVerifyActions(); } @@ -1187,6 +1210,7 @@ public void run() { private final Actions verifyActions; private Path executeInDirectory; private Set appLayoutAsserts = Set.of(AppLayoutAssert.values()); + private Consumer> outputValidator; private static boolean defaultWithToolProvider; private static final Map PACKAGE_TYPES = Functional.identity( diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/JPackageStringBundle.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/JPackageStringBundle.java new file mode 100644 index 0000000000000..565822d4504c0 --- /dev/null +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/JPackageStringBundle.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2024, 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. + * + * 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 jdk.jpackage.test; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.text.MessageFormat; + +public enum JPackageStringBundle { + + MAIN("jdk.jpackage.internal.I18N"), + ; + + JPackageStringBundle(String i18nClassName) { + try { + i18nClass = Class.forName(i18nClassName); + + i18nClass_getString = i18nClass.getDeclaredMethod("getString", String.class); + i18nClass_getString.setAccessible(true); + } catch (ClassNotFoundException|NoSuchMethodException ex) { + throw Functional.rethrowUnchecked(ex); + } + } + + /** + * Return a string value of the given key from jpackage resources. + */ + private String getString(String key) { + try { + return (String)i18nClass_getString.invoke(i18nClass, key); + } catch (IllegalAccessException|InvocationTargetException ex) { + throw Functional.rethrowUnchecked(ex); + } + } + + private String getFormattedString(String key, Object[] args) { + return MessageFormat.format(getString(key), args); + } + + public CannedFormattedString cannedFormattedString(String key, String ... args) { + return new CannedFormattedString(this::getFormattedString, key, args); + } + + private final Class i18nClass; + private final Method i18nClass_getString; +} diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/TKit.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/TKit.java index 957449697a562..8f91d581ef145 100644 --- a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/TKit.java +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/TKit.java @@ -946,6 +946,16 @@ public TextStreamVerifier negate() { return this; } + public TextStreamVerifier andThen(Consumer> anotherVerifier) { + this.anotherVerifier = anotherVerifier; + return this; + } + + public TextStreamVerifier andThen(TextStreamVerifier anotherVerifier) { + this.anotherVerifier = anotherVerifier::apply; + return this; + } + public TextStreamVerifier orElseThrow(RuntimeException v) { return orElseThrow(() -> v); } @@ -956,9 +966,22 @@ public TextStreamVerifier orElseThrow(Supplier v) { } public void apply(Stream lines) { - String matchedStr = lines.filter(line -> predicate.test(line, value)).findFirst().orElse( - null); - String labelStr = Optional.ofNullable(label).orElse("output"); + final String matchedStr; + + lines = lines.dropWhile(line -> !predicate.test(line, value)); + if (anotherVerifier == null) { + matchedStr = lines.findFirst().orElse(null); + } else { + var tail = lines.toList(); + if (tail.isEmpty()) { + matchedStr = null; + } else { + matchedStr = tail.get(0); + } + lines = tail.stream().skip(1); + } + + final String labelStr = Optional.ofNullable(label).orElse("output"); if (negate) { String msg = String.format( "Check %s doesn't contain [%s] string", labelStr, value); @@ -982,12 +1005,17 @@ public void apply(Stream lines) { } } } + + if (anotherVerifier != null) { + anotherVerifier.accept(lines); + } } private BiPredicate predicate; private String label; private boolean negate; private Supplier createException; + private Consumer> anotherVerifier; private final String value; } diff --git a/test/jdk/tools/jpackage/share/ErrorTest.java b/test/jdk/tools/jpackage/share/ErrorTest.java index f012eac1ced95..ed7338a76dd9a 100644 --- a/test/jdk/tools/jpackage/share/ErrorTest.java +++ b/test/jdk/tools/jpackage/share/ErrorTest.java @@ -24,9 +24,13 @@ import java.util.Collection; import java.util.List; -import jdk.jpackage.test.Annotations.Parameters; +import java.util.Optional; +import java.util.stream.Stream; +import jdk.jpackage.test.Annotations.ParameterSupplier; import jdk.jpackage.test.Annotations.Test; +import jdk.jpackage.test.CannedFormattedString; import jdk.jpackage.test.JPackageCommand; +import jdk.jpackage.test.JPackageStringBundle; import jdk.jpackage.test.TKit; /* @@ -53,81 +57,85 @@ public final class ErrorTest { - private final String expectedError; - private final JPackageCommand cmd; - - @Parameters public static Collection input() { return List.of(new Object[][]{ // non-existent arg {"Hello", new String[]{"--no-such-argument"}, null, - "Invalid Option: [--no-such-argument]"}, + JPackageStringBundle.MAIN.cannedFormattedString("ERR_InvalidOption", "--no-such-argument")}, // no main jar {"Hello", null, new String[]{"--main-jar"}, - "--main-jar or --module"}, + JPackageStringBundle.MAIN.cannedFormattedString("ERR_NoEntryPoint")}, // no main-class {"Hello", null, new String[]{"--main-class"}, - "main class was not specified"}, + JPackageStringBundle.MAIN.cannedFormattedString("error.no-main-class-with-main-jar", "hello.jar"), + JPackageStringBundle.MAIN.cannedFormattedString("error.no-main-class-with-main-jar.advice", "hello.jar")}, // non-existent main jar {"Hello", new String[]{"--main-jar", "non-existent.jar"}, null, - "main jar does not exist"}, + JPackageStringBundle.MAIN.cannedFormattedString("error.main-jar-does-not-exist", "non-existent.jar")}, // non-existent runtime {"Hello", new String[]{"--runtime-image", "non-existent.runtime"}, null, - "does not exist"}, + JPackageStringBundle.MAIN.cannedFormattedString("message.runtime-image-dir-does-not-exist", "runtime-image", "non-existent.runtime")}, // non-existent resource-dir {"Hello", new String[]{"--resource-dir", "non-existent.dir"}, null, - "does not exist"}, + JPackageStringBundle.MAIN.cannedFormattedString("message.resource-dir-does-not-exist", "resource-dir", "non-existent.dir")}, // invalid type {"Hello", new String[]{"--type", "invalid-type"}, null, - "Invalid or unsupported type: [invalid-type]"}, + JPackageStringBundle.MAIN.cannedFormattedString("ERR_InvalidInstallerType", "invalid-type")}, // no --input {"Hello", null, new String[]{"--input"}, - "Missing argument: --input"}, + JPackageStringBundle.MAIN.cannedFormattedString("ERR_MissingArgument", "--input")}, // no --module-path {"com.other/com.other.Hello", null, new String[]{"--module-path"}, - "Missing argument: --runtime-image or --module-path"}, + JPackageStringBundle.MAIN.cannedFormattedString("ERR_MissingArgument", "--runtime-image or --module-path")}, }); } - public ErrorTest(String javaAppDesc, String[] jpackageArgs, - String[] removeArgs, - String expectedError) { - this.expectedError = expectedError; + @Test + @ParameterSupplier("input") + public static void test(String javaAppDesc, String[] jpackageArgs, + String[] removeArgs, CannedFormattedString... expectedErrors) { + // Init default jpackage test command line. + var cmd = JPackageCommand.helloAppImage(javaAppDesc) + // Disable default logic adding `--verbose` option + // to jpackage command line. + // It will affect jpackage error messages if the command line is malformed. + .ignoreDefaultVerbose(true) + // Ignore external runtime as it will interfer + // with jpackage arguments in this test. + .ignoreDefaultRuntime(true); - cmd = JPackageCommand.helloAppImage(javaAppDesc) - .saveConsoleOutput(true).dumpOutput(true); - if (jpackageArgs != null) { - cmd.addArguments(jpackageArgs); - } if (removeArgs != null) { - for (String arg : removeArgs) { - cmd.removeArgumentWithValue(arg); - } - } - } + // Add arguments if requested. + Optional.ofNullable(jpackageArgs).ifPresent(cmd::addArguments); - @Test - public void test() { - List output = cmd.execute(1).getOutput(); - TKit.assertNotNull(output, "output is null"); - TKit.assertTextStream(expectedError).apply(output.stream()); - } + // Remove arguments if requested. + Optional.ofNullable(removeArgs).map(List::of).ifPresent( + args -> args.forEach(cmd::removeArgumentWithValue)); + + // Configure jpackage output verifier to look up the list of provided + // errors in the order they specified. + cmd.validateOutput(Stream.of(expectedErrors) + .map(CannedFormattedString::getValue) + .map(TKit::assertTextStream) + .reduce(TKit.TextStreamVerifier::andThen).get()); + cmd.execute(1); + } } From a28e4d839c9220655d78116be89c3c26b3d17a0e Mon Sep 17 00:00:00 2001 From: Alexey Semenyuk Date: Tue, 19 Nov 2024 13:54:02 +0000 Subject: [PATCH 04/74] 8342299: Document that jpackage includes (possibly old) VC Redistributable MSVCP140.dll from JDK Reviewed-by: almatvee --- src/jdk.jpackage/share/man/jpackage.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/jdk.jpackage/share/man/jpackage.md b/src/jdk.jpackage/share/man/jpackage.md index 21f07db0bb892..9d7a3003c2454 100644 --- a/src/jdk.jpackage/share/man/jpackage.md +++ b/src/jdk.jpackage/share/man/jpackage.md @@ -497,6 +497,14 @@ Sign the predefined application image (on macOS): the set of additional mac signing options and --verbose +## jpackage and jlink + +jpackage will use jlink to create Java Runtime unless the `--runtime-image` option is used. +The created Java Runtime image on Windows will include MS runtime libraries bundled with the JDK. +If MS runtime libraries of a different version are needed for the application, the user will need +to add/replace those themselves. + + ## jpackage resource directory Icons, template files, and other resources of jpackage can be over-ridden by From fea5f2b1458cdd53f437e59caaffaa6e22fb59a7 Mon Sep 17 00:00:00 2001 From: Alexey Semenyuk Date: Tue, 19 Nov 2024 13:54:57 +0000 Subject: [PATCH 05/74] 8344415: Restruct jpackage utility classes Reviewed-by: almatvee --- .../jpackage/internal/DesktopIntegration.java | 10 +- .../internal/LinuxAppImageBuilder.java | 5 +- .../internal/LinuxPackageBundler.java | 5 +- .../internal/MacBaseInstallerBundler.java | 11 +- .../jdk/jpackage/internal/MacDmgBundler.java | 11 +- .../internal/MacLaunchersAsServices.java | 5 +- .../jdk/jpackage/internal/MacPkgBundler.java | 8 +- .../internal/AbstractAppImageBuilder.java | 10 +- .../jpackage/internal/AbstractBundler.java | 5 +- .../jdk/jpackage/internal/AppImageFile.java | 5 +- .../jdk/jpackage/internal/IOUtils.java | 294 +----------------- .../jdk/jpackage/internal/PathGroup.java | 5 +- .../internal/StandardBundlerParam.java | 5 +- .../jdk/jpackage/internal/util/FileUtils.java | 155 +++++++++ .../jdk/jpackage/internal/util/PathUtils.java | 54 ++++ .../internal/util/PrettyPrintHandler.java | 89 ++++++ .../internal/util/SkipDocumentHandler.java | 48 +++ .../jpackage/internal/util/XmlConsumer.java | 34 ++ .../jdk/jpackage/internal/util/XmlUtils.java | 103 ++++++ .../internal/util/function/ExceptionBox.java | 50 +++ .../util/function/ThrowingBiConsumer.java | 42 +++ .../util/function/ThrowingBiFunction.java | 43 +++ .../util/function/ThrowingConsumer.java | 42 +++ .../util/function/ThrowingFunction.java | 42 +++ .../util/function/ThrowingRunnable.java | 40 +++ .../util/function/ThrowingSupplier.java | 42 +++ .../util/function/ThrowingUnaryOperator.java | 43 +++ .../jdk/jpackage/internal/WinExeBundler.java | 5 +- .../jdk/jpackage/internal/WinMsiBundler.java | 5 +- .../internal/WixAppImageFragmentBuilder.java | 11 +- .../jpackage/internal/WixFragmentBuilder.java | 5 +- .../internal/WixLauncherAsService.java | 7 +- .../jdk/jpackage/internal/WixPipeline.java | 3 +- .../jpackage/internal/WixSourceConverter.java | 3 +- .../jdk/jpackage/internal/WixTool.java | 3 +- .../internal/WixUiFragmentBuilder.java | 4 +- test/jdk/tools/jpackage/TEST.properties | 2 + .../jdk/jpackage/test/AnnotationsTest.java | 2 +- .../jdk/jpackage/test/TKitTest.java | 6 +- .../jdk/jpackage/test/AdditionalLauncher.java | 45 +-- .../helpers/jdk/jpackage/test/Executor.java | 4 +- .../jdk/jpackage/test/FileAssociations.java | 10 +- .../helpers/jdk/jpackage/test/Functional.java | 102 ------ .../helpers/jdk/jpackage/test/HelloApp.java | 6 +- .../jdk/jpackage/test/JPackageCommand.java | 12 +- .../test/LauncherAsServiceVerifier.java | 12 +- .../jpackage/test/LauncherIconVerifier.java | 9 +- .../jdk/jpackage/test/LinuxHelper.java | 6 +- .../helpers/jdk/jpackage/test/MacHelper.java | 8 +- .../helpers/jdk/jpackage/test/MethodCall.java | 2 +- .../jdk/jpackage/test/PackageTest.java | 14 +- .../jdk/jpackage/test/PackageType.java | 17 +- .../helpers/jdk/jpackage/test/TKit.java | 8 +- .../jdk/jpackage/test/TestBuilder.java | 6 +- .../jdk/jpackage/test/TestInstance.java | 9 +- .../jdk/jpackage/test/TestMethodSupplier.java | 4 +- .../jdk/jpackage/test/WindowsHelper.java | 2 +- .../tools/jpackage/linux/AppAboutUrlTest.java | 2 +- .../tools/jpackage/share/AppContentTest.java | 8 +- test/jdk/tools/jpackage/share/BasicTest.java | 2 +- test/jdk/tools/jpackage/share/IconTest.java | 8 +- .../tools/jpackage/share/InOutPathTest.java | 2 +- .../tools/jpackage/share/MainClassTest.java | 2 +- .../tools/jpackage/share/PerUserCfgTest.java | 2 +- .../share/RuntimeImageSymbolicLinksTest.java | 9 - .../jpackage/windows/WinLongVersionTest.java | 7 +- .../tools/jpackage/windows/WinScriptTest.java | 5 +- 67 files changed, 1014 insertions(+), 571 deletions(-) create mode 100644 src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/FileUtils.java create mode 100644 src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/PathUtils.java create mode 100644 src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/PrettyPrintHandler.java create mode 100644 src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/SkipDocumentHandler.java create mode 100644 src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/XmlConsumer.java create mode 100644 src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/XmlUtils.java create mode 100644 src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/function/ExceptionBox.java create mode 100644 src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/function/ThrowingBiConsumer.java create mode 100644 src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/function/ThrowingBiFunction.java create mode 100644 src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/function/ThrowingConsumer.java create mode 100644 src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/function/ThrowingFunction.java create mode 100644 src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/function/ThrowingRunnable.java create mode 100644 src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/function/ThrowingSupplier.java create mode 100644 src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/function/ThrowingUnaryOperator.java diff --git a/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/DesktopIntegration.java b/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/DesktopIntegration.java index 6a5b200f8f304..a9cf2682cd700 100644 --- a/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/DesktopIntegration.java +++ b/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/DesktopIntegration.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2024, 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 @@ -54,6 +54,8 @@ import static jdk.jpackage.internal.StandardBundlerParam.ICON; import static jdk.jpackage.internal.StandardBundlerParam.PREDEFINED_APP_IMAGE; import static jdk.jpackage.internal.StandardBundlerParam.SHORTCUT_HINT; +import jdk.jpackage.internal.util.PathUtils; +import jdk.jpackage.internal.util.XmlUtils; /** * Helper to create files for desktop integration. @@ -119,7 +121,7 @@ private DesktopIntegration(PlatformPackage thePackage, if (withDesktopFile) { desktopFile = new DesktopFile(desktopFileName); iconFile = new DesktopFile(escapedAppFileName - + IOUtils.getSuffix(Path.of(DEFAULT_ICON))); + + PathUtils.getSuffix(Path.of(DEFAULT_ICON))); if (curIconResource == null) { // Create default icon. @@ -420,7 +422,7 @@ private void appendFileAssociation(XMLStreamWriter xml, } private void createFileAssociationsMimeInfoFile() throws IOException { - IOUtils.createXml(mimeInfoFile.srcPath(), xml -> { + XmlUtils.createXml(mimeInfoFile.srcPath(), xml -> { xml.writeStartElement("mime-info"); xml.writeDefaultNamespace( "http://www.freedesktop.org/standards/shared-mime-info"); @@ -451,7 +453,7 @@ private void addFileAssociationIconFiles(ShellCommands shellCommands) // Create icon name for mime type from mime type. DesktopFile faIconFile = new DesktopFile(mimeType.replace( - File.separatorChar, '-') + IOUtils.getSuffix( + File.separatorChar, '-') + PathUtils.getSuffix( assoc.data.iconPath)); IOUtils.copyFile(assoc.data.iconPath, diff --git a/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxAppImageBuilder.java b/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxAppImageBuilder.java index 7291d56218a21..ab97e327003ca 100644 --- a/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxAppImageBuilder.java +++ b/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxAppImageBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2024, 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 @@ -35,6 +35,7 @@ import static jdk.jpackage.internal.StandardBundlerParam.APP_NAME; import static jdk.jpackage.internal.StandardBundlerParam.ICON; import static jdk.jpackage.internal.StandardBundlerParam.ADD_LAUNCHERS; +import jdk.jpackage.internal.util.PathUtils; public class LinuxAppImageBuilder extends AbstractAppImageBuilder { @@ -127,7 +128,7 @@ private void createLauncherForEntryPoint(Map params, mainParams); if (iconResource != null) { Path iconTarget = appLayout.destktopIntegrationDirectory().resolve( - APP_NAME.fetchFrom(params) + IOUtils.getSuffix(Path.of( + APP_NAME.fetchFrom(params) + PathUtils.getSuffix(Path.of( DEFAULT_ICON))); iconResource.saveToFile(iconTarget); } diff --git a/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxPackageBundler.java b/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxPackageBundler.java index b510ed414118b..5d160d4128c85 100644 --- a/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxPackageBundler.java +++ b/src/jdk.jpackage/linux/classes/jdk/jpackage/internal/LinuxPackageBundler.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2024, 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 @@ -44,6 +44,7 @@ import static jdk.jpackage.internal.StandardBundlerParam.VENDOR; import static jdk.jpackage.internal.StandardBundlerParam.DESCRIPTION; import static jdk.jpackage.internal.StandardBundlerParam.INSTALL_DIR; +import jdk.jpackage.internal.util.FileUtils; abstract class LinuxPackageBundler extends AbstractBundler { @@ -144,7 +145,7 @@ public final Path execute(Map params, // Application image is a newly created directory tree. // Move it. srcAppLayout.move(thePackage.sourceApplicationLayout()); - IOUtils.deleteRecursive(srcAppImageRoot); + FileUtils.deleteRecursive(srcAppImageRoot); } } diff --git a/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/MacBaseInstallerBundler.java b/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/MacBaseInstallerBundler.java index 8d9db0a007783..69ecce068e733 100644 --- a/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/MacBaseInstallerBundler.java +++ b/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/MacBaseInstallerBundler.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2024, 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 @@ -25,25 +25,20 @@ package jdk.jpackage.internal; -import java.io.ByteArrayOutputStream; import java.io.IOException; -import java.io.PrintStream; import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.Path; import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.regex.Matcher; -import java.util.regex.Pattern; import static jdk.jpackage.internal.StandardBundlerParam.APP_NAME; import static jdk.jpackage.internal.StandardBundlerParam.INSTALLER_NAME; import static jdk.jpackage.internal.StandardBundlerParam.INSTALL_DIR; import static jdk.jpackage.internal.StandardBundlerParam.PREDEFINED_APP_IMAGE; import static jdk.jpackage.internal.StandardBundlerParam.VERSION; import static jdk.jpackage.internal.StandardBundlerParam.SIGN_BUNDLE; +import jdk.jpackage.internal.util.FileUtils; public abstract class MacBaseInstallerBundler extends AbstractBundler { @@ -187,7 +182,7 @@ protected Path prepareAppBundle(Map params) StandardBundlerParam.getPredefinedAppImage(params); if (predefinedImage != null) { appDir = appImageRoot.resolve(APP_NAME.fetchFrom(params) + ".app"); - IOUtils.copyRecursive(predefinedImage, appDir, + FileUtils.copyRecursive(predefinedImage, appDir, LinkOption.NOFOLLOW_LINKS); // Create PackageFile if predefined app image is not signed diff --git a/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/MacDmgBundler.java b/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/MacDmgBundler.java index 7d100832dbaf4..3de8ef5ee2b7e 100644 --- a/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/MacDmgBundler.java +++ b/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/MacDmgBundler.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2024, 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 @@ -48,6 +48,7 @@ import static jdk.jpackage.internal.StandardBundlerParam.TEMP_ROOT; import static jdk.jpackage.internal.StandardBundlerParam.VERBOSE; import static jdk.jpackage.internal.StandardBundlerParam.DMG_CONTENT; +import jdk.jpackage.internal.util.FileUtils; public class MacDmgBundler extends MacBaseInstallerBundler { @@ -294,7 +295,7 @@ private Path buildDMG( Map params, MAC_CF_BUNDLE_IDENTIFIER.fetchFrom(params)); Path dest = root.resolve("Contents/Home"); - IOUtils.copyRecursive(source, dest); + FileUtils.copyRecursive(source, dest); srcFolder = newRoot; } @@ -319,7 +320,7 @@ private Path buildDMG( Map params, List dmgContent = DMG_CONTENT.fetchFrom(params); for (String content : dmgContent) { Path path = Path.of(content); - IOUtils.copyRecursive(path, srcFolder.resolve(path.getFileName())); + FileUtils.copyRecursive(path, srcFolder.resolve(path.getFileName())); } // create temp image ProcessBuilder pb = new ProcessBuilder( @@ -381,9 +382,9 @@ private Path buildDMG( Map params, Path destPath = mountedRoot .resolve(srcFolder.getFileName()); Files.createDirectory(destPath); - IOUtils.copyRecursive(srcFolder, destPath); + FileUtils.copyRecursive(srcFolder, destPath); } else { - IOUtils.copyRecursive(srcFolder, mountedRoot); + FileUtils.copyRecursive(srcFolder, mountedRoot); } } diff --git a/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/MacLaunchersAsServices.java b/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/MacLaunchersAsServices.java index b0ee96e2ee3a7..4f069921f459d 100644 --- a/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/MacLaunchersAsServices.java +++ b/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/MacLaunchersAsServices.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, 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 @@ -33,6 +33,7 @@ import static jdk.jpackage.internal.MacAppImageBuilder.MAC_CF_BUNDLE_IDENTIFIER; import static jdk.jpackage.internal.OverridableResource.createResource; import static jdk.jpackage.internal.StandardBundlerParam.APP_NAME; +import jdk.jpackage.internal.util.PathUtils; /** * Helper to install launchers as services using "launchd". @@ -95,7 +96,7 @@ private static class Launcher extends UnixLauncherAsService { // It is recommended to set value of "label" property in launchd // .plist file equal to the name of this .plist file without the suffix. - String label = IOUtils.replaceSuffix(plistFilename.getFileName(), "").toString(); + String label = PathUtils.replaceSuffix(plistFilename.getFileName(), "").toString(); getResource() .setPublicName(plistFilename) diff --git a/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/MacPkgBundler.java b/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/MacPkgBundler.java index 6ac84975451b4..a4345ecf764e6 100644 --- a/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/MacPkgBundler.java +++ b/src/jdk.jpackage/macosx/classes/jdk/jpackage/internal/MacPkgBundler.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2024, 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 @@ -62,6 +62,8 @@ import static jdk.jpackage.internal.MacAppImageBuilder.MAC_CF_BUNDLE_IDENTIFIER; import static jdk.jpackage.internal.OverridableResource.createResource; import static jdk.jpackage.internal.StandardBundlerParam.RESOURCE_DIR; +import jdk.jpackage.internal.util.FileUtils; +import jdk.jpackage.internal.util.XmlUtils; public class MacPkgBundler extends MacBaseInstallerBundler { @@ -267,7 +269,7 @@ private void prepareDistributionXMLFile(Map params) Log.verbose(MessageFormat.format(I18N.getString( "message.preparing-distribution-dist"), f.toAbsolutePath().toString())); - IOUtils.createXml(f, xml -> { + XmlUtils.createXml(f, xml -> { xml.writeStartElement("installer-gui-script"); xml.writeAttribute("minSpecVersion", "1"); @@ -452,7 +454,7 @@ private String getRoot(Map params, source = appLocation; dest = newRoot.resolve(appLocation.getFileName()); } - IOUtils.copyRecursive(source, dest); + FileUtils.copyRecursive(source, dest); return newRoot.toString(); } diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/AbstractAppImageBuilder.java b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/AbstractAppImageBuilder.java index b507cc955bd75..b523e43f5aad8 100644 --- a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/AbstractAppImageBuilder.java +++ b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/AbstractAppImageBuilder.java @@ -32,8 +32,6 @@ import java.util.ArrayList; import java.util.Map; import java.util.List; -import java.util.Objects; -import java.util.stream.Stream; import static jdk.jpackage.internal.OverridableResource.createResource; import static jdk.jpackage.internal.StandardBundlerParam.APP_NAME; import static jdk.jpackage.internal.StandardBundlerParam.ICON; @@ -42,6 +40,8 @@ import static jdk.jpackage.internal.StandardBundlerParam.OUTPUT_DIR; import static jdk.jpackage.internal.StandardBundlerParam.TEMP_ROOT; import jdk.jpackage.internal.resources.ResourceLocator; +import jdk.jpackage.internal.util.FileUtils; +import jdk.jpackage.internal.util.PathUtils; /* * AbstractAppImageBuilder @@ -92,7 +92,7 @@ protected void copyApplication(Map params) } } - IOUtils.copyRecursive(inputPath, + FileUtils.copyRecursive(inputPath, appLayout.appDirectory().toAbsolutePath(), excludes); } @@ -100,7 +100,7 @@ protected void copyApplication(Map params) List items = APP_CONTENT.fetchFrom(params); for (String item : items) { - IOUtils.copyRecursive(Path.of(item), + FileUtils.copyRecursive(Path.of(item), appLayout.contentDirectory().resolve(Path.of(item).getFileName())); } } @@ -115,7 +115,7 @@ public static OverridableResource createIconResource(String defaultIconName, } final String resourcePublicName = APP_NAME.fetchFrom(params) - + IOUtils.getSuffix(Path.of(defaultIconName)); + + PathUtils.getSuffix(Path.of(defaultIconName)); IconType iconType = getLauncherIconType(params); if (iconType == IconType.NoIcon) { diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/AbstractBundler.java b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/AbstractBundler.java index b615176fd15cf..e28a444a0456b 100644 --- a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/AbstractBundler.java +++ b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/AbstractBundler.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2024, 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 @@ -28,6 +28,7 @@ import java.io.IOException; import java.nio.file.Path; import java.util.Map; +import jdk.jpackage.internal.util.FileUtils; /** @@ -55,7 +56,7 @@ public String toString() { @Override public void cleanup(Map params) { try { - IOUtils.deleteRecursive( + FileUtils.deleteRecursive( StandardBundlerParam.TEMP_ROOT.fetchFrom(params)); } catch (IOException e) { Log.verbose(e.getMessage()); diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/AppImageFile.java b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/AppImageFile.java index 31228a8f5a3e4..256d292350af4 100644 --- a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/AppImageFile.java +++ b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/AppImageFile.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2024, 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 @@ -59,6 +59,7 @@ import static jdk.jpackage.internal.StandardBundlerParam.MENU_HINT; import static jdk.jpackage.internal.StandardBundlerParam.SIGN_BUNDLE; import static jdk.jpackage.internal.StandardBundlerParam.APP_STORE; +import jdk.jpackage.internal.util.XmlUtils; public final class AppImageFile { @@ -247,7 +248,7 @@ private static void save(Path appImageDir, addLauncherInfoSave = appImage.getAddLaunchers(); } - IOUtils.createXml(getPathInAppImage(appImageDir), xml -> { + XmlUtils.createXml(getPathInAppImage(appImageDir), xml -> { xml.writeStartElement("jpackage-state"); xml.writeAttribute("version", getVersion()); xml.writeAttribute("platform", getPlatform()); diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/IOUtils.java b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/IOUtils.java index 573109a004bc0..534786ada13c9 100644 --- a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/IOUtils.java +++ b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/IOUtils.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2024, 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 @@ -25,41 +25,15 @@ package jdk.jpackage.internal; -import jdk.internal.util.OperatingSystem; - import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.io.PrintStream; -import java.io.Writer; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.nio.file.FileVisitResult; import java.nio.file.Files; -import java.nio.file.CopyOption; import java.nio.file.Path; -import java.nio.file.SimpleFileVisitor; import java.nio.file.StandardCopyOption; -import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.atomic.AtomicReference; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.stream.XMLOutputFactory; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamWriter; -import javax.xml.transform.Result; -import javax.xml.transform.Source; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.stax.StAXResult; /** * IOUtils @@ -68,107 +42,6 @@ */ public class IOUtils { - public static void deleteRecursive(Path directory) throws IOException { - final AtomicReference exception = new AtomicReference<>(); - - if (!Files.exists(directory)) { - return; - } - - Files.walkFileTree(directory, new SimpleFileVisitor() { - @Override - public FileVisitResult visitFile(Path file, - BasicFileAttributes attr) throws IOException { - if (OperatingSystem.isWindows()) { - Files.setAttribute(file, "dos:readonly", false); - } - try { - Files.delete(file); - } catch (IOException ex) { - exception.compareAndSet(null, ex); - } - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult preVisitDirectory(Path dir, - BasicFileAttributes attr) throws IOException { - if (OperatingSystem.isWindows()) { - Files.setAttribute(dir, "dos:readonly", false); - } - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult postVisitDirectory(Path dir, IOException e) - throws IOException { - try { - Files.delete(dir); - } catch (IOException ex) { - exception.compareAndSet(null, ex); - } - return FileVisitResult.CONTINUE; - } - }); - if (exception.get() != null) { - throw exception.get(); - } - } - - public static void copyRecursive(Path src, Path dest, CopyOption... options) - throws IOException { - copyRecursive(src, dest, List.of(), options); - } - - public static void copyRecursive(Path src, Path dest, - final List excludes, CopyOption... options) - throws IOException { - - List copyActions = new ArrayList<>(); - - Files.walkFileTree(src, new SimpleFileVisitor() { - @Override - public FileVisitResult preVisitDirectory(final Path dir, - final BasicFileAttributes attrs) { - if (isPathMatch(dir, excludes)) { - return FileVisitResult.SKIP_SUBTREE; - } else { - copyActions.add(new CopyAction(null, dest.resolve(src. - relativize(dir)))); - return FileVisitResult.CONTINUE; - } - } - - @Override - public FileVisitResult visitFile(final Path file, - final BasicFileAttributes attrs) { - if (!isPathMatch(file, excludes)) { - copyActions.add(new CopyAction(file, dest.resolve(src. - relativize(file)))); - } - return FileVisitResult.CONTINUE; - } - }); - - for (var copyAction : copyActions) { - copyAction.apply(options); - } - } - - private static record CopyAction(Path src, Path dest) { - void apply(CopyOption... options) throws IOException { - if (src == null) { - Files.createDirectories(dest); - } else { - Files.copy(src, dest, options); - } - } - } - - private static boolean isPathMatch(Path what, List paths) { - return paths.stream().anyMatch(what::endsWith); - } - public static void copyFile(Path sourceFile, Path destFile) throws IOException { Files.createDirectories(getParent(destFile)); @@ -314,90 +187,6 @@ static void writableOutputDir(Path outdir) throws PackagerException { } } - public static Path replaceSuffix(Path path, String suffix) { - Path parent = path.getParent(); - String filename = getFileName(path).toString().replaceAll("\\.[^.]*$", "") - + Optional.ofNullable(suffix).orElse(""); - return parent != null ? parent.resolve(filename) : Path.of(filename); - } - - public static Path addSuffix(Path path, String suffix) { - Path parent = path.getParent(); - String filename = getFileName(path).toString() + suffix; - return parent != null ? parent.resolve(filename) : Path.of(filename); - } - - public static String getSuffix(Path path) { - String filename = replaceSuffix(getFileName(path), null).toString(); - return getFileName(path).toString().substring(filename.length()); - } - - @FunctionalInterface - public static interface XmlConsumer { - void accept(XMLStreamWriter xml) throws IOException, XMLStreamException; - } - - public static void createXml(Path dstFile, XmlConsumer xmlConsumer) throws - IOException { - XMLOutputFactory xmlFactory = XMLOutputFactory.newInstance(); - Files.createDirectories(getParent(dstFile)); - try (Writer w = Files.newBufferedWriter(dstFile)) { - // Wrap with pretty print proxy - XMLStreamWriter xml = (XMLStreamWriter) Proxy.newProxyInstance( - XMLStreamWriter.class.getClassLoader(), new Class[]{ - XMLStreamWriter.class}, new PrettyPrintHandler( - xmlFactory.createXMLStreamWriter(w))); - - xml.writeStartDocument(); - xmlConsumer.accept(xml); - xml.writeEndDocument(); - xml.flush(); - xml.close(); - } catch (XMLStreamException ex) { - throw new IOException(ex); - } catch (IOException ex) { - throw ex; - } - } - - public static void mergeXmls(XMLStreamWriter xml, Collection sources) - throws XMLStreamException, IOException { - xml = (XMLStreamWriter) Proxy.newProxyInstance( - XMLStreamWriter.class.getClassLoader(), new Class[]{ - XMLStreamWriter.class}, new SkipDocumentHandler(xml)); - - try { - TransformerFactory tf = TransformerFactory.newInstance(); - Result result = new StAXResult(xml); - for (var src : sources) { - tf.newTransformer().transform(src, result); - } - } catch (TransformerException ex) { - // Should never happen - throw new RuntimeException(ex); - } - } - - public static DocumentBuilderFactory initDocumentBuilderFactory() { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newDefaultInstance(); - try { - dbf.setFeature( - "http://apache.org/xml/features/nonvalidating/load-external-dtd", - false); - } catch (ParserConfigurationException ex) { - throw new IllegalStateException(ex); - } - return dbf; - } - - public static DocumentBuilder initDocumentBuilder() { - try { - return initDocumentBuilderFactory().newDocumentBuilder(); - } catch (ParserConfigurationException ex) { - throw new IllegalStateException(ex); - } - } - public static Path getParent(Path p) { Path parent = p.getParent(); if (parent == null) { @@ -430,85 +219,4 @@ public static long getPID(Process p) { return -1; } } - - private static class PrettyPrintHandler implements InvocationHandler { - - PrettyPrintHandler(XMLStreamWriter target) { - this.target = target; - } - - @Override - public Object invoke(Object proxy, Method method, Object[] args) throws - Throwable { - switch (method.getName()) { - case "writeStartElement": - // update state of parent node - if (depth > 0) { - hasChildElement.put(depth - 1, true); - } - // reset state of current node - hasChildElement.put(depth, false); - // indent for current depth - target.writeCharacters(EOL); - target.writeCharacters(repeat(depth, INDENT)); - depth++; - break; - case "writeEndElement": - depth--; - if (hasChildElement.get(depth) == true) { - target.writeCharacters(EOL); - target.writeCharacters(repeat(depth, INDENT)); - } - break; - case "writeProcessingInstruction": - case "writeEmptyElement": - // update state of parent node - if (depth > 0) { - hasChildElement.put(depth - 1, true); - } - // indent for current depth - target.writeCharacters(EOL); - target.writeCharacters(repeat(depth, INDENT)); - break; - default: - break; - } - method.invoke(target, args); - return null; - } - - private static String repeat(int d, String s) { - StringBuilder sb = new StringBuilder(); - while (d-- > 0) { - sb.append(s); - } - return sb.toString(); - } - - private final XMLStreamWriter target; - private int depth = 0; - private final Map hasChildElement = new HashMap<>(); - private static final String INDENT = " "; - private static final String EOL = "\n"; - } - - private static class SkipDocumentHandler implements InvocationHandler { - - SkipDocumentHandler(XMLStreamWriter target) { - this.target = target; - } - - @Override - public Object invoke(Object proxy, Method method, Object[] args) throws - Throwable { - switch (method.getName()) { - case "writeStartDocument", "writeEndDocument" -> { - } - default -> method.invoke(target, args); - } - return null; - } - - private final XMLStreamWriter target; - } } diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/PathGroup.java b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/PathGroup.java index 24fb394e100d0..296164551a118 100644 --- a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/PathGroup.java +++ b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/PathGroup.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2024, 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 @@ -35,6 +35,7 @@ import java.util.function.BiFunction; import java.util.stream.Collectors; import java.util.stream.Stream; +import jdk.jpackage.internal.util.FileUtils; /** @@ -232,7 +233,7 @@ public void createDirectory(Path dir) throws IOException { for (var entry: entries) { Path srcFile = entry.getKey(); if (Files.isDirectory(srcFile)) { - IOUtils.deleteRecursive(srcFile); + FileUtils.deleteRecursive(srcFile); } } } diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/StandardBundlerParam.java b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/StandardBundlerParam.java index 718f186c9547a..0209eea584aee 100644 --- a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/StandardBundlerParam.java +++ b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/StandardBundlerParam.java @@ -44,6 +44,7 @@ import java.util.function.BiFunction; import java.util.function.Function; import java.util.stream.Stream; +import jdk.jpackage.internal.util.FileUtils; /** * StandardBundlerParam @@ -604,7 +605,7 @@ static void copyPredefinedRuntimeImage(Map params, // copy whole runtime, need to skip jmods and src.zip final List excludes = Arrays.asList(Path.of("jmods"), Path.of("src.zip")); - IOUtils.copyRecursive(topImage, appLayout.runtimeHomeDirectory(), + FileUtils.copyRecursive(topImage, appLayout.runtimeHomeDirectory(), excludes, LinkOption.NOFOLLOW_LINKS); // if module-path given - copy modules to appDir/mods @@ -616,7 +617,7 @@ static void copyPredefinedRuntimeImage(Map params, for (Path mp : modulePath) { if (!defaultModulePath.contains(mp)) { Files.createDirectories(dest); - IOUtils.copyRecursive(mp, dest); + FileUtils.copyRecursive(mp, dest); } } } diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/FileUtils.java b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/FileUtils.java new file mode 100644 index 0000000000000..71b8c3d6ddc79 --- /dev/null +++ b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/FileUtils.java @@ -0,0 +1,155 @@ +/* + * Copyright (c) 2024, 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 jdk.jpackage.internal.util; + +import java.io.IOException; +import java.nio.file.CopyOption; +import java.nio.file.FileVisitResult; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.SimpleFileVisitor; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.ArrayList; +import java.util.List; +import jdk.internal.util.OperatingSystem; +import jdk.jpackage.internal.util.function.ExceptionBox; +import jdk.jpackage.internal.util.function.ThrowingConsumer; + +public final class FileUtils { + + public static void deleteRecursive(Path directory) throws IOException { + if (!Files.exists(directory)) { + return; + } + + var callback = new RecursiveDeleter(); + + Files.walkFileTree(directory, callback); + + if (callback.ex != null) { + throw callback.ex; + } + } + + public static void copyRecursive(Path src, Path dest, CopyOption... options) + throws IOException { + copyRecursive(src, dest, List.of(), options); + } + + public static void copyRecursive(Path src, Path dest, + final List excludes, CopyOption... options) + throws IOException { + + List copyActions = new ArrayList<>(); + + Files.walkFileTree(src, new SimpleFileVisitor() { + @Override + public FileVisitResult preVisitDirectory(final Path dir, + final BasicFileAttributes attrs) { + if (isPathMatch(dir, excludes)) { + return FileVisitResult.SKIP_SUBTREE; + } else { + copyActions.add(new CopyAction(null, dest.resolve(src. + relativize(dir)))); + return FileVisitResult.CONTINUE; + } + } + + @Override + public FileVisitResult visitFile(final Path file, + final BasicFileAttributes attrs) { + if (!isPathMatch(file, excludes)) { + copyActions.add(new CopyAction(file, dest.resolve(src. + relativize(file)))); + } + return FileVisitResult.CONTINUE; + } + }); + + for (var copyAction : copyActions) { + copyAction.apply(options); + } + } + + private static boolean isPathMatch(Path what, List paths) { + return paths.stream().anyMatch(what::endsWith); + } + + private static record CopyAction(Path src, Path dest) { + + void apply(CopyOption... options) throws IOException { + if (src == null) { + Files.createDirectories(dest); + } else { + Files.copy(src, dest, options); + } + } + } + + private static class RecursiveDeleter extends SimpleFileVisitor { + + @Override + public FileVisitResult visitFile(Path file, + BasicFileAttributes attr) throws IOException { + adjustAttributes(file); + runActionOnPath(Files::delete, file); + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult preVisitDirectory(Path dir, + BasicFileAttributes attr) throws IOException { + adjustAttributes(dir); + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult postVisitDirectory(Path dir, IOException e) + throws IOException { + runActionOnPath(Files::delete, dir); + return FileVisitResult.CONTINUE; + } + + private static void adjustAttributes(Path path) throws IOException { + if (OperatingSystem.isWindows()) { + Files.setAttribute(path, "dos:readonly", false); + } + } + + private void runActionOnPath(ThrowingConsumer action, Path path) { + try { + action.accept(path); + } catch (IOException ex) { + if (this.ex == null) { + this.ex = ex; + } + } catch (Throwable t) { + throw ExceptionBox.rethrowUnchecked(t); + } + } + + private IOException ex; + } +} diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/PathUtils.java b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/PathUtils.java new file mode 100644 index 0000000000000..267062a2031b6 --- /dev/null +++ b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/PathUtils.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2024, 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 jdk.jpackage.internal.util; + +import java.nio.file.Path; +import java.util.Optional; +import jdk.jpackage.internal.IOUtils; + +public final class PathUtils { + + public static String getSuffix(Path path) { + String filename = replaceSuffix(IOUtils.getFileName(path), null).toString(); + return IOUtils.getFileName(path).toString().substring(filename.length()); + } + + public static Path addSuffix(Path path, String suffix) { + Path parent = path.getParent(); + String filename = IOUtils.getFileName(path).toString() + suffix; + return parent != null ? parent.resolve(filename) : Path.of(filename); + } + + public static Path replaceSuffix(Path path, String suffix) { + Path parent = path.getParent(); + String filename = IOUtils.getFileName(path).toString().replaceAll("\\.[^.]*$", + "") + Optional.ofNullable(suffix).orElse(""); + return parent != null ? parent.resolve(filename) : Path.of(filename); + } + + public static Path resolveNullablePath(Path base, Path path) { + return Optional.ofNullable(path).map(base::resolve).orElse(null); + } +} diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/PrettyPrintHandler.java b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/PrettyPrintHandler.java new file mode 100644 index 0000000000000..ffd5b7641035a --- /dev/null +++ b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/PrettyPrintHandler.java @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2024, 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. + * + * 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 jdk.jpackage.internal.util; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; +import javax.xml.stream.XMLStreamWriter; + +final class PrettyPrintHandler implements InvocationHandler { + + public PrettyPrintHandler(XMLStreamWriter target) { + this.target = target; + } + + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + switch (method.getName()) { + case "writeStartElement": + // update state of parent node + if (depth > 0) { + hasChildElement.put(depth - 1, true); + } + // reset state of current node + hasChildElement.put(depth, false); + // indent for current depth + target.writeCharacters(EOL); + target.writeCharacters(repeat(depth, INDENT)); + depth++; + break; + case "writeEndElement": + depth--; + if (hasChildElement.get(depth) == true) { + target.writeCharacters(EOL); + target.writeCharacters(repeat(depth, INDENT)); + } + break; + case "writeProcessingInstruction": + case "writeEmptyElement": + // update state of parent node + if (depth > 0) { + hasChildElement.put(depth - 1, true); + } + // indent for current depth + target.writeCharacters(EOL); + target.writeCharacters(repeat(depth, INDENT)); + break; + default: + break; + } + method.invoke(target, args); + return null; + } + + private static String repeat(int d, String s) { + StringBuilder sb = new StringBuilder(); + while (d-- > 0) { + sb.append(s); + } + return sb.toString(); + } + + private final XMLStreamWriter target; + private int depth = 0; + private final Map hasChildElement = new HashMap<>(); + private static final String INDENT = " "; + private static final String EOL = "\n"; +} diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/SkipDocumentHandler.java b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/SkipDocumentHandler.java new file mode 100644 index 0000000000000..283dac451a23b --- /dev/null +++ b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/SkipDocumentHandler.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2024, 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 jdk.jpackage.internal.util; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import javax.xml.stream.XMLStreamWriter; + +final class SkipDocumentHandler implements InvocationHandler { + + public SkipDocumentHandler(XMLStreamWriter target) { + this.target = target; + } + + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + switch (method.getName()) { + case "writeStartDocument", "writeEndDocument" -> { + } + default -> method.invoke(target, args); + } + return null; + } + + private final XMLStreamWriter target; +} diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/XmlConsumer.java b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/XmlConsumer.java new file mode 100644 index 0000000000000..429be6aba05ce --- /dev/null +++ b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/XmlConsumer.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2024, 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. + * + * 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 jdk.jpackage.internal.util; + +import java.io.IOException; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamWriter; + +@FunctionalInterface +public interface XmlConsumer { + + void accept(XMLStreamWriter xml) throws IOException, XMLStreamException; + +} diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/XmlUtils.java b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/XmlUtils.java new file mode 100644 index 0000000000000..8012384b67901 --- /dev/null +++ b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/XmlUtils.java @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2024, 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. + * + * 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 jdk.jpackage.internal.util; + +import java.io.IOException; +import java.io.Writer; +import java.lang.reflect.Proxy; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Collection; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.stream.XMLOutputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamWriter; +import javax.xml.transform.Result; +import javax.xml.transform.Source; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.stax.StAXResult; +import jdk.jpackage.internal.IOUtils; + + +public final class XmlUtils { + + public static void createXml(Path dstFile, XmlConsumer xmlConsumer) throws + IOException { + XMLOutputFactory xmlFactory = XMLOutputFactory.newInstance(); + Files.createDirectories(IOUtils.getParent(dstFile)); + try (Writer w = Files.newBufferedWriter(dstFile)) { + // Wrap with pretty print proxy + XMLStreamWriter xml = (XMLStreamWriter) Proxy.newProxyInstance(XMLStreamWriter.class.getClassLoader(), + new Class[]{XMLStreamWriter.class}, + new PrettyPrintHandler(xmlFactory.createXMLStreamWriter(w))); + xml.writeStartDocument(); + xmlConsumer.accept(xml); + xml.writeEndDocument(); + xml.flush(); + xml.close(); + } catch (XMLStreamException ex) { + throw new IOException(ex); + } catch (IOException ex) { + throw ex; + } + } + + public static void mergeXmls(XMLStreamWriter xml, Collection sources) + throws XMLStreamException, IOException { + xml = (XMLStreamWriter) Proxy.newProxyInstance(XMLStreamWriter.class.getClassLoader(), + new Class[]{XMLStreamWriter.class}, + new SkipDocumentHandler(xml)); + try { + TransformerFactory tf = TransformerFactory.newInstance(); + Result result = new StAXResult(xml); + for (Source src : sources) { + tf.newTransformer().transform(src, result); + } + } catch (TransformerException ex) { + // Should never happen + throw new RuntimeException(ex); + } + } + + public static DocumentBuilder initDocumentBuilder() { + try { + return initDocumentBuilderFactory().newDocumentBuilder(); + } catch (ParserConfigurationException ex) { + throw new IllegalStateException(ex); + } + } + + public static DocumentBuilderFactory initDocumentBuilderFactory() { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newDefaultInstance(); + try { + dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", + false); + } catch (ParserConfigurationException ex) { + throw new IllegalStateException(ex); + } + return dbf; + } +} diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/function/ExceptionBox.java b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/function/ExceptionBox.java new file mode 100644 index 0000000000000..55f2964445fdc --- /dev/null +++ b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/function/ExceptionBox.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2024, 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. + * + * 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 jdk.jpackage.internal.util.function; + +import java.lang.reflect.InvocationTargetException; + +public class ExceptionBox extends RuntimeException { + + private static final long serialVersionUID = 1L; + + public static RuntimeException rethrowUnchecked(Throwable throwable) { + if (throwable instanceof RuntimeException err) { + throw err; + } + + if (throwable instanceof Error err) { + throw err; + } + + if (throwable instanceof InvocationTargetException err) { + throw rethrowUnchecked(err.getCause()); + } + + throw new ExceptionBox(throwable); + } + + private ExceptionBox(Throwable throwable) { + super(throwable); + } +} diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/function/ThrowingBiConsumer.java b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/function/ThrowingBiConsumer.java new file mode 100644 index 0000000000000..e5b7704a92e76 --- /dev/null +++ b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/function/ThrowingBiConsumer.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2024, 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. + * + * 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 jdk.jpackage.internal.util.function; + +import java.util.function.BiConsumer; + +@FunctionalInterface +public interface ThrowingBiConsumer { + + void accept(T t, U u) throws Throwable; + + public static BiConsumer toBiConsumer( + ThrowingBiConsumer v) { + return (t, u) -> { + try { + v.accept(t, u); + } catch (Throwable ex) { + throw ExceptionBox.rethrowUnchecked(ex); + } + }; + } +} diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/function/ThrowingBiFunction.java b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/function/ThrowingBiFunction.java new file mode 100644 index 0000000000000..a8119f25bdb76 --- /dev/null +++ b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/function/ThrowingBiFunction.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2024, 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. + * + * 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 jdk.jpackage.internal.util.function; + +import java.util.function.BiFunction; + +@FunctionalInterface +public interface ThrowingBiFunction { + + R apply(T t, U u) throws Throwable; + + public static BiFunction toBiFunction( + ThrowingBiFunction v) { + return (t, u) -> { + try { + return v.apply(t, u); + } catch (Throwable ex) { + throw ExceptionBox.rethrowUnchecked(ex); + } + }; + } + +} diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/function/ThrowingConsumer.java b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/function/ThrowingConsumer.java new file mode 100644 index 0000000000000..5ca33c22d9232 --- /dev/null +++ b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/function/ThrowingConsumer.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2024, 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. + * + * 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 jdk.jpackage.internal.util.function; + +import java.util.function.Consumer; + +@FunctionalInterface +public interface ThrowingConsumer { + + void accept(T t) throws Throwable; + + public static Consumer toConsumer(ThrowingConsumer v) { + return o -> { + try { + v.accept(o); + } catch (Throwable ex) { + throw ExceptionBox.rethrowUnchecked(ex); + } + }; + } + +} diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/function/ThrowingFunction.java b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/function/ThrowingFunction.java new file mode 100644 index 0000000000000..db6b1d260059e --- /dev/null +++ b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/function/ThrowingFunction.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2024, 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. + * + * 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 jdk.jpackage.internal.util.function; + +import java.util.function.Function; + +@FunctionalInterface +public interface ThrowingFunction { + + R apply(T t) throws Throwable; + + public static Function toFunction(ThrowingFunction v) { + return t -> { + try { + return v.apply(t); + } catch (Throwable ex) { + throw ExceptionBox.rethrowUnchecked(ex); + } + }; + } + +} diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/function/ThrowingRunnable.java b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/function/ThrowingRunnable.java new file mode 100644 index 0000000000000..7f3fcda536ced --- /dev/null +++ b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/function/ThrowingRunnable.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2024, 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. + * + * 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 jdk.jpackage.internal.util.function; + +@FunctionalInterface +public interface ThrowingRunnable { + + void run() throws Throwable; + + public static Runnable toRunnable(ThrowingRunnable v) { + return () -> { + try { + v.run(); + } catch (Throwable ex) { + throw ExceptionBox.rethrowUnchecked(ex); + } + }; + } + +} diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/function/ThrowingSupplier.java b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/function/ThrowingSupplier.java new file mode 100644 index 0000000000000..2f5ef135875a9 --- /dev/null +++ b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/function/ThrowingSupplier.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2024, 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. + * + * 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 jdk.jpackage.internal.util.function; + +import java.util.function.Supplier; + +@FunctionalInterface +public interface ThrowingSupplier { + + T get() throws Throwable; + + public static Supplier toSupplier(ThrowingSupplier v) { + return () -> { + try { + return v.get(); + } catch (Throwable ex) { + throw ExceptionBox.rethrowUnchecked(ex); + } + }; + } + +} diff --git a/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/function/ThrowingUnaryOperator.java b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/function/ThrowingUnaryOperator.java new file mode 100644 index 0000000000000..27a3e2f30f5ab --- /dev/null +++ b/src/jdk.jpackage/share/classes/jdk/jpackage/internal/util/function/ThrowingUnaryOperator.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2024, 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. + * + * 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 jdk.jpackage.internal.util.function; + +import java.util.function.UnaryOperator; + +@FunctionalInterface +public interface ThrowingUnaryOperator { + + T apply(T t) throws Throwable; + + public static UnaryOperator toUnaryOperator( + ThrowingUnaryOperator v) { + return t -> { + try { + return v.apply(t); + } catch (Throwable ex) { + throw ExceptionBox.rethrowUnchecked(ex); + } + }; + } + +} diff --git a/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WinExeBundler.java b/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WinExeBundler.java index fa81b4278b06a..cc2e9298e9954 100644 --- a/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WinExeBundler.java +++ b/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WinExeBundler.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2024, 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 @@ -30,6 +30,7 @@ import java.nio.file.Path; import java.text.MessageFormat; import java.util.Map; +import jdk.jpackage.internal.util.PathUtils; @SuppressWarnings("restricted") public class WinExeBundler extends AbstractBundler { @@ -127,7 +128,7 @@ private Path buildEXE(Map params, Path msi, outdir.toAbsolutePath().toString())); // Copy template msi wrapper next to msi file - final Path exePath = IOUtils.replaceSuffix(msi, ".exe"); + final Path exePath = PathUtils.replaceSuffix(msi, ".exe"); try (InputStream is = OverridableResource.readDefault(EXE_WRAPPER_NAME)) { Files.copy(is, exePath); } diff --git a/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WinMsiBundler.java b/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WinMsiBundler.java index c0ae65b3b0bcc..f6b0fb4be2074 100644 --- a/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WinMsiBundler.java +++ b/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WinMsiBundler.java @@ -36,7 +36,6 @@ import java.nio.file.PathMatcher; import java.text.MessageFormat; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashSet; @@ -67,7 +66,7 @@ import static jdk.jpackage.internal.StandardBundlerParam.TEMP_ROOT; import static jdk.jpackage.internal.StandardBundlerParam.VENDOR; import static jdk.jpackage.internal.StandardBundlerParam.VERSION; -import jdk.jpackage.internal.WixToolset.WixToolsetType; +import jdk.jpackage.internal.util.FileUtils; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; @@ -367,7 +366,7 @@ private void prepareProto(Map params) if (appImage != null) { appDir = MSI_IMAGE_DIR.fetchFrom(params).resolve(appName); // copy everything from appImage dir into appDir/name - IOUtils.copyRecursive(appImage, appDir); + FileUtils.copyRecursive(appImage, appDir); } else { appDir = appImageBundler.execute(params, MSI_IMAGE_DIR.fetchFrom( params)); diff --git a/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WixAppImageFragmentBuilder.java b/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WixAppImageFragmentBuilder.java index 5bc20c1413c86..a5d9a5de141ab 100644 --- a/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WixAppImageFragmentBuilder.java +++ b/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WixAppImageFragmentBuilder.java @@ -42,7 +42,6 @@ import java.util.Optional; import java.util.Set; import java.util.UUID; -import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Collectors; @@ -56,7 +55,7 @@ import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import jdk.jpackage.internal.AppImageFile.LauncherInfo; -import jdk.jpackage.internal.IOUtils.XmlConsumer; +import jdk.jpackage.internal.util.XmlConsumer; import static jdk.jpackage.internal.StandardBundlerParam.APP_NAME; import static jdk.jpackage.internal.StandardBundlerParam.INSTALL_DIR; import static jdk.jpackage.internal.StandardBundlerParam.VENDOR; @@ -65,6 +64,8 @@ import static jdk.jpackage.internal.WinMsiBundler.SERVICE_INSTALLER; import static jdk.jpackage.internal.WinMsiBundler.WIN_APP_IMAGE; import jdk.jpackage.internal.WixToolset.WixToolsetType; +import jdk.jpackage.internal.util.PathUtils; +import jdk.jpackage.internal.util.XmlUtils; import org.w3c.dom.NodeList; /** @@ -202,7 +203,7 @@ private void normalizeFileAssociation(FileAssociation fa) { } private static Path addExeSuffixToPath(Path path) { - return IOUtils.addSuffix(path, ".exe"); + return PathUtils.addSuffix(path, ".exe"); } private Path getInstalledFaIcoPath(FileAssociation fa) { @@ -524,7 +525,7 @@ private String addShortcutComponent(XMLStreamWriter xml, Path launcherPath, throw throwInvalidPathException(launcherPath); } - String launcherBasename = IOUtils.replaceSuffix( + String launcherBasename = PathUtils.replaceSuffix( IOUtils.getFileName(launcherPath), "").toString(); Path shortcutPath = folder.getPath(this).resolve(launcherBasename); @@ -774,7 +775,7 @@ private List addServiceConfigs(XMLStreamWriter xml) throws } try { - var buffer = new DOMResult(IOUtils.initDocumentBuilder().newDocument()); + var buffer = new DOMResult(XmlUtils.initDocumentBuilder().newDocument()); var bufferWriter = XMLOutputFactory.newInstance().createXMLStreamWriter( buffer); diff --git a/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WixFragmentBuilder.java b/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WixFragmentBuilder.java index 0276cc96e6521..f0a5840eb6fc3 100644 --- a/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WixFragmentBuilder.java +++ b/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WixFragmentBuilder.java @@ -37,13 +37,14 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.stream.XMLStreamWriter; -import jdk.jpackage.internal.IOUtils.XmlConsumer; +import jdk.jpackage.internal.util.XmlConsumer; import jdk.jpackage.internal.OverridableResource.Source; import static jdk.jpackage.internal.StandardBundlerParam.CONFIG_ROOT; import jdk.internal.util.Architecture; import static jdk.jpackage.internal.OverridableResource.createResource; import jdk.jpackage.internal.WixSourceConverter.ResourceGroup; import jdk.jpackage.internal.WixToolset.WixToolsetType; +import jdk.jpackage.internal.util.XmlUtils; /** * Creates WiX fragment. @@ -159,7 +160,7 @@ final protected void addResource(OverridableResource resource, String saveAsName } private void createWixSource(Path file, XmlConsumer xmlConsumer) throws IOException { - IOUtils.createXml(file, xml -> { + XmlUtils.createXml(file, xml -> { xml.writeStartElement("Wix"); for (var ns : getWixNamespaces().entrySet()) { switch (ns.getKey()) { diff --git a/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WixLauncherAsService.java b/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WixLauncherAsService.java index 9b737c8e1a4b6..ffd5e35b15c99 100644 --- a/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WixLauncherAsService.java +++ b/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WixLauncherAsService.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2024, 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 @@ -39,6 +39,7 @@ import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import static jdk.jpackage.internal.OverridableResource.createResource; +import jdk.jpackage.internal.util.XmlUtils; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; @@ -95,7 +96,7 @@ private void writeResource(OverridableResource resource, XMLStreamWriter xml) resource.saveToStream(buffer); try { - Document doc = IOUtils.initDocumentBuilder().parse( + Document doc = XmlUtils.initDocumentBuilder().parse( new ByteArrayInputStream(buffer.toByteArray())); XPath xPath = XPathFactory.newInstance().newXPath(); @@ -109,7 +110,7 @@ private void writeResource(OverridableResource resource, XMLStreamWriter xml) sources.add(new DOMSource(n)); } - IOUtils.mergeXmls(xml, sources); + XmlUtils.mergeXmls(xml, sources); } catch (SAXException ex) { throw new IOException(ex); diff --git a/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WixPipeline.java b/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WixPipeline.java index 835247ed1debb..5b626c8a565f5 100644 --- a/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WixPipeline.java +++ b/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WixPipeline.java @@ -36,6 +36,7 @@ import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; +import jdk.jpackage.internal.util.PathUtils; /** * WiX pipeline. Compiles and links WiX sources. @@ -180,7 +181,7 @@ private void buildMsiWix3(Path msi) throws IOException { } private Path compileWix3(WixSource wixSource) throws IOException { - Path wixObj = wixObjDir.toAbsolutePath().resolve(IOUtils.replaceSuffix( + Path wixObj = wixObjDir.toAbsolutePath().resolve(PathUtils.replaceSuffix( IOUtils.getFileName(wixSource.source), ".wixobj")); List cmdline = new ArrayList<>(List.of( diff --git a/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WixSourceConverter.java b/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WixSourceConverter.java index 7786d64a78693..86ef70442dcba 100644 --- a/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WixSourceConverter.java +++ b/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WixSourceConverter.java @@ -52,6 +52,7 @@ import javax.xml.transform.stax.StAXResult; import javax.xml.transform.stream.StreamSource; import jdk.jpackage.internal.WixToolset.WixToolsetType; +import jdk.jpackage.internal.util.XmlUtils; import org.w3c.dom.Document; import org.xml.sax.SAXException; @@ -98,7 +99,7 @@ Status appyTo(OverridableResource resource, Path resourceSaveAsFile) throws IOEx Document inputXmlDom; try { - inputXmlDom = IOUtils.initDocumentBuilder().parse(new ByteArrayInputStream(buf)); + inputXmlDom = XmlUtils.initDocumentBuilder().parse(new ByteArrayInputStream(buf)); } catch (SAXException ex) { // Malformed XML, don't run converter, save as is. resource.saveToFile(resourceSaveAsFile); diff --git a/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WixTool.java b/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WixTool.java index f16b28edf2448..ee98327b03233 100644 --- a/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WixTool.java +++ b/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WixTool.java @@ -41,6 +41,7 @@ import java.util.stream.Collectors; import java.util.stream.Stream; import jdk.jpackage.internal.WixToolset.WixToolsetType; +import jdk.jpackage.internal.util.PathUtils; /** * WiX tool. @@ -51,7 +52,7 @@ public enum WixTool { Wix4("wix", DottedVersion.lazy("4.0.4")); WixTool(String commandName, DottedVersion minimalVersion) { - this.toolFileName = IOUtils.addSuffix(Path.of(commandName), ".exe"); + this.toolFileName = PathUtils.addSuffix(Path.of(commandName), ".exe"); this.minimalVersion = minimalVersion; } diff --git a/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WixUiFragmentBuilder.java b/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WixUiFragmentBuilder.java index 4f39a65e3b6ad..5eb23fc58c4e3 100644 --- a/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WixUiFragmentBuilder.java +++ b/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WixUiFragmentBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2024, 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 @@ -39,7 +39,7 @@ import java.util.stream.Stream; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; -import jdk.jpackage.internal.IOUtils.XmlConsumer; +import jdk.jpackage.internal.util.XmlConsumer; import static jdk.jpackage.internal.OverridableResource.createResource; import static jdk.jpackage.internal.StandardBundlerParam.LICENSE_FILE; import jdk.jpackage.internal.WixAppImageFragmentBuilder.ShortcutsFolder; diff --git a/test/jdk/tools/jpackage/TEST.properties b/test/jdk/tools/jpackage/TEST.properties index e01036f0ed36c..a34532d6695c6 100644 --- a/test/jdk/tools/jpackage/TEST.properties +++ b/test/jdk/tools/jpackage/TEST.properties @@ -12,4 +12,6 @@ maxOutputSize=2000000 exclusiveAccess.dirs=share windows modules=jdk.jpackage/jdk.jpackage.internal:+open \ + jdk.jpackage/jdk.jpackage.internal.util \ + jdk.jpackage/jdk.jpackage.internal.util.function \ java.base/jdk.internal.util diff --git a/test/jdk/tools/jpackage/helpers-test/jdk/jpackage/test/AnnotationsTest.java b/test/jdk/tools/jpackage/helpers-test/jdk/jpackage/test/AnnotationsTest.java index 2d23f49cdd757..230b14fd1eac4 100644 --- a/test/jdk/tools/jpackage/helpers-test/jdk/jpackage/test/AnnotationsTest.java +++ b/test/jdk/tools/jpackage/helpers-test/jdk/jpackage/test/AnnotationsTest.java @@ -40,7 +40,7 @@ import jdk.jpackage.test.Annotations.ParameterSupplier; import jdk.jpackage.test.Annotations.Parameters; import jdk.jpackage.test.Annotations.Test; -import static jdk.jpackage.test.Functional.ThrowingSupplier.toSupplier; +import static jdk.jpackage.internal.util.function.ThrowingSupplier.toSupplier; /* * @test diff --git a/test/jdk/tools/jpackage/helpers-test/jdk/jpackage/test/TKitTest.java b/test/jdk/tools/jpackage/helpers-test/jdk/jpackage/test/TKitTest.java index 3f55c3c50aea9..98a7d8731901d 100644 --- a/test/jdk/tools/jpackage/helpers-test/jdk/jpackage/test/TKitTest.java +++ b/test/jdk/tools/jpackage/helpers-test/jdk/jpackage/test/TKitTest.java @@ -37,9 +37,9 @@ import java.util.stream.Stream; import jdk.jpackage.test.Annotations.Parameters; import jdk.jpackage.test.Annotations.Test; -import jdk.jpackage.test.Functional.ThrowingRunnable; -import static jdk.jpackage.test.Functional.ThrowingRunnable.toRunnable; -import static jdk.jpackage.test.Functional.ThrowingSupplier.toSupplier; +import jdk.jpackage.internal.util.function.ThrowingRunnable; +import static jdk.jpackage.internal.util.function.ThrowingRunnable.toRunnable; +import static jdk.jpackage.internal.util.function.ThrowingSupplier.toSupplier; public class TKitTest { diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/AdditionalLauncher.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/AdditionalLauncher.java index 6c388ac77ffb9..70b0e160d24cc 100644 --- a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/AdditionalLauncher.java +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/AdditionalLauncher.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2024, 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 @@ -37,8 +37,9 @@ import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; -import jdk.jpackage.test.Functional.ThrowingBiConsumer; -import static jdk.jpackage.test.Functional.ThrowingFunction.toFunction; +import static jdk.jpackage.internal.util.function.ExceptionBox.rethrowUnchecked; +import jdk.jpackage.internal.util.function.ThrowingBiConsumer; +import static jdk.jpackage.internal.util.function.ThrowingFunction.toFunction; public class AdditionalLauncher { @@ -48,12 +49,12 @@ public AdditionalLauncher(String name) { setPersistenceHandler(null); } - final public AdditionalLauncher setDefaultArguments(String... v) { + public final AdditionalLauncher setDefaultArguments(String... v) { defaultArguments = new ArrayList<>(List.of(v)); return this; } - final public AdditionalLauncher addDefaultArguments(String... v) { + public final AdditionalLauncher addDefaultArguments(String... v) { if (defaultArguments == null) { return setDefaultArguments(v); } @@ -62,12 +63,12 @@ final public AdditionalLauncher addDefaultArguments(String... v) { return this; } - final public AdditionalLauncher setJavaOptions(String... v) { + public final AdditionalLauncher setJavaOptions(String... v) { javaOptions = new ArrayList<>(List.of(v)); return this; } - final public AdditionalLauncher addJavaOptions(String... v) { + public final AdditionalLauncher addJavaOptions(String... v) { if (javaOptions == null) { return setJavaOptions(v); } @@ -76,27 +77,27 @@ final public AdditionalLauncher addJavaOptions(String... v) { return this; } - final public AdditionalLauncher setVerifyUninstalled(boolean value) { + public final AdditionalLauncher setVerifyUninstalled(boolean value) { verifyUninstalled = value; return this; } - final public AdditionalLauncher setLauncherAsService() { + public final AdditionalLauncher setLauncherAsService() { return addRawProperties(LAUNCHER_AS_SERVICE); } - final public AdditionalLauncher addRawProperties( + public final AdditionalLauncher addRawProperties( Map.Entry... v) { return addRawProperties(List.of(v)); } - final public AdditionalLauncher addRawProperties( + public final AdditionalLauncher addRawProperties( Collection> v) { rawProperties.addAll(v); return this; } - final public String getRawPropertyValue( + public final String getRawPropertyValue( String key, Supplier getDefault) { return rawProperties.stream() .filter(item -> item.getKey().equals(key)) @@ -108,13 +109,13 @@ private String getDesciption(JPackageCommand cmd) { "--description", unused -> cmd.name())); } - final public AdditionalLauncher setShortcuts(boolean menu, boolean shortcut) { + public final AdditionalLauncher setShortcuts(boolean menu, boolean shortcut) { withMenuShortcut = menu; withShortcut = shortcut; return this; } - final public AdditionalLauncher setIcon(Path iconPath) { + public final AdditionalLauncher setIcon(Path iconPath) { if (iconPath == NO_ICON) { throw new IllegalArgumentException(); } @@ -123,12 +124,12 @@ final public AdditionalLauncher setIcon(Path iconPath) { return this; } - final public AdditionalLauncher setNoIcon() { + public final AdditionalLauncher setNoIcon() { icon = NO_ICON; return this; } - final public AdditionalLauncher setPersistenceHandler( + public final AdditionalLauncher setPersistenceHandler( ThrowingBiConsumer>> handler) { if (handler != null) { createFileHandler = ThrowingBiConsumer.toBiConsumer(handler); @@ -138,12 +139,12 @@ final public AdditionalLauncher setPersistenceHandler( return this; } - final public void applyTo(JPackageCommand cmd) { + public final void applyTo(JPackageCommand cmd) { cmd.addPrerequisiteAction(this::initialize); cmd.addVerifyAction(this::verify); } - final public void applyTo(PackageTest test) { + public final void applyTo(PackageTest test) { test.addInitializer(this::initialize); test.addInstallVerifier(this::verify); if (verifyUninstalled) { @@ -151,7 +152,7 @@ final public void applyTo(PackageTest test) { } } - final public void verifyRemovedInUpgrade(PackageTest test) { + public final void verifyRemovedInUpgrade(PackageTest test) { test.addInstallVerifier(this::verifyUninstalled); } @@ -189,7 +190,7 @@ private void initialize(JPackageCommand cmd) { propsFile = TKit.createTempFile(propsFile); TKit.deleteIfExists(propsFile); } catch (IOException ex) { - Functional.rethrowUnchecked(ex); + rethrowUnchecked(ex); } } @@ -446,7 +447,7 @@ private static String resolveVariables(JPackageCommand cmd, String str) { private Boolean withMenuShortcut; private Boolean withShortcut; - private final static Path NO_ICON = Path.of(""); - private final static Map.Entry LAUNCHER_AS_SERVICE = Map.entry( + private static final Path NO_ICON = Path.of(""); + private static final Map.Entry LAUNCHER_AS_SERVICE = Map.entry( "launcher-as-service", "true"); } diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/Executor.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/Executor.java index 72ebb64a14294..f182f4f7f7dc4 100644 --- a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/Executor.java +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/Executor.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2024, 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 @@ -42,7 +42,7 @@ import java.util.spi.ToolProvider; import java.util.stream.Collectors; import java.util.stream.Stream; -import jdk.jpackage.test.Functional.ThrowingSupplier; +import jdk.jpackage.internal.util.function.ThrowingSupplier; public final class Executor extends CommandArguments { diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/FileAssociations.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/FileAssociations.java index 4908519782896..091a2206b173b 100644 --- a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/FileAssociations.java +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/FileAssociations.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2024, 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 @@ -32,10 +32,10 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; -import jdk.jpackage.internal.IOUtils; +import jdk.jpackage.internal.util.PathUtils; -final public class FileAssociations { +public final class FileAssociations { public FileAssociations(String faSuffixName) { suffixName = faSuffixName; setFilename("fa"); @@ -79,7 +79,7 @@ Path getLinuxIconFileName() { if (icon == null) { return null; } - return Path.of(getMime().replace('/', '-') + IOUtils.getSuffix(icon)); + return Path.of(getMime().replace('/', '-') + PathUtils.getSuffix(icon)); } Path getPropertiesFile() { @@ -243,7 +243,7 @@ public static enum InvocationType { } private Path file; - final private String suffixName; + private final String suffixName; private String description; private Path icon; private Collection testRuns; diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/Functional.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/Functional.java index a57caa92cb20e..a974670b8e4ce 100644 --- a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/Functional.java +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/Functional.java @@ -31,84 +31,6 @@ public class Functional { - @FunctionalInterface - public interface ThrowingConsumer { - void accept(T t) throws Throwable; - - public static Consumer toConsumer(ThrowingConsumer v) { - return o -> { - try { - v.accept(o); - } catch (Throwable ex) { - rethrowUnchecked(ex); - } - }; - } - } - - @FunctionalInterface - public interface ThrowingBiConsumer { - void accept(T t, U u) throws Throwable; - - public static BiConsumer toBiConsumer(ThrowingBiConsumer v) { - return (t, u) -> { - try { - v.accept(t, u); - } catch (Throwable ex) { - rethrowUnchecked(ex); - } - }; - } - } - - @FunctionalInterface - public interface ThrowingSupplier { - T get() throws Throwable; - - public static Supplier toSupplier(ThrowingSupplier v) { - return () -> { - try { - return v.get(); - } catch (Throwable ex) { - rethrowUnchecked(ex); - } - // Unreachable - return null; - }; - } - } - - @FunctionalInterface - public interface ThrowingFunction { - R apply(T t) throws Throwable; - - public static Function toFunction(ThrowingFunction v) { - return (t) -> { - try { - return v.apply(t); - } catch (Throwable ex) { - rethrowUnchecked(ex); - } - // Unreachable - return null; - }; - } - } - - @FunctionalInterface - public interface ThrowingRunnable { - void run() throws Throwable; - - public static Runnable toRunnable(ThrowingRunnable v) { - return () -> { - try { - v.run(); - } catch (Throwable ex) { - rethrowUnchecked(ex); - } - }; - } - } public static Supplier identity(Supplier v) { return v; @@ -141,28 +63,4 @@ public static Predicate identity(Predicate v) { public static Predicate identityPredicate(Predicate v) { return v; } - - public static class ExceptionBox extends RuntimeException { - public ExceptionBox(Throwable throwable) { - super(throwable); - } - } - - @SuppressWarnings("unchecked") - public static RuntimeException rethrowUnchecked(Throwable throwable) throws - ExceptionBox { - if (throwable instanceof RuntimeException err) { - throw err; - } - - if (throwable instanceof Error err) { - throw err; - } - - if (throwable instanceof InvocationTargetException err) { - throw rethrowUnchecked(err.getCause()); - } - - throw new ExceptionBox(throwable); - } } diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/HelloApp.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/HelloApp.java index bc722e7acd925..bc35912bcbb6c 100644 --- a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/HelloApp.java +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/HelloApp.java @@ -40,9 +40,9 @@ import java.util.stream.Collectors; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; -import jdk.jpackage.test.Functional.ThrowingConsumer; -import jdk.jpackage.test.Functional.ThrowingFunction; -import jdk.jpackage.test.Functional.ThrowingSupplier; +import jdk.jpackage.internal.util.function.ThrowingConsumer; +import jdk.jpackage.internal.util.function.ThrowingFunction; +import jdk.jpackage.internal.util.function.ThrowingSupplier; public final class HelloApp { diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/JPackageCommand.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/JPackageCommand.java index 49eeb25a00edb..4239d8a87c8d3 100644 --- a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/JPackageCommand.java +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/JPackageCommand.java @@ -45,15 +45,15 @@ import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; -import jdk.jpackage.internal.IOUtils; import jdk.jpackage.internal.AppImageFile; import jdk.jpackage.internal.ApplicationLayout; import jdk.jpackage.internal.PackageFile; +import jdk.jpackage.internal.util.XmlUtils; import static jdk.jpackage.test.AdditionalLauncher.forEachAdditionalLauncher; -import jdk.jpackage.test.Functional.ThrowingConsumer; -import jdk.jpackage.test.Functional.ThrowingFunction; -import jdk.jpackage.test.Functional.ThrowingRunnable; -import jdk.jpackage.test.Functional.ThrowingSupplier; +import jdk.jpackage.internal.util.function.ThrowingConsumer; +import jdk.jpackage.internal.util.function.ThrowingFunction; +import jdk.jpackage.internal.util.function.ThrowingRunnable; +import jdk.jpackage.internal.util.function.ThrowingSupplier; /** * jpackage command line with prerequisite actions. Prerequisite actions can be @@ -315,7 +315,7 @@ public void createJPackageXMLFile(String mainLauncher, String mainClass) "Error: --app-image expected"); })); - IOUtils.createXml(jpackageXMLFile, xml -> { + XmlUtils.createXml(jpackageXMLFile, xml -> { xml.writeStartElement("jpackage-state"); xml.writeAttribute("version", AppImageFile.getVersion()); xml.writeAttribute("platform", AppImageFile.getPlatform()); diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/LauncherAsServiceVerifier.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/LauncherAsServiceVerifier.java index 026da0df0eb08..d73029ab153c3 100644 --- a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/LauncherAsServiceVerifier.java +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/LauncherAsServiceVerifier.java @@ -35,8 +35,10 @@ import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; -import jdk.jpackage.internal.IOUtils; -import static jdk.jpackage.test.Functional.ThrowingConsumer.toConsumer; +import jdk.jpackage.internal.util.PathUtils; +import jdk.jpackage.internal.util.function.ThrowingBiConsumer; +import static jdk.jpackage.internal.util.function.ThrowingConsumer.toConsumer; +import jdk.jpackage.internal.util.function.ThrowingRunnable; import static jdk.jpackage.test.PackageType.LINUX; import static jdk.jpackage.test.PackageType.MAC_PKG; import static jdk.jpackage.test.PackageType.WINDOWS; @@ -187,7 +189,7 @@ static List getLaunchersAsServices(JPackageCommand cmd) { } AdditionalLauncher.forEachAdditionalLauncher(cmd, - Functional.ThrowingBiConsumer.toBiConsumer( + ThrowingBiConsumer.toBiConsumer( (launcherName, propFilePath) -> { if (Files.readAllLines(propFilePath).stream().anyMatch( line -> { @@ -335,14 +337,14 @@ private static void verifyMacDaemonPlistFile(JPackageCommand cmd, TKit.assertEquals(installedLauncherPath.toString(), args.get(0), "Check path to launcher in 'ProgramArguments' property in the property file"); - var expectedLabel = IOUtils.replaceSuffix(servicePlistFile.getFileName(), "").toString(); + var expectedLabel = PathUtils.replaceSuffix(servicePlistFile.getFileName(), "").toString(); TKit.assertEquals(expectedLabel, servicePlist.queryValue("Label"), "Check value of 'Label' property in the property file"); } private static void delayInstallVerify() { // Sleep a bit to let system launch the service - Functional.ThrowingRunnable.toRunnable(() -> Thread.sleep(5 * 1000)).run(); + ThrowingRunnable.toRunnable(() -> Thread.sleep(5 * 1000)).run(); } private Path appOutputFilePathInitialize() { diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/LauncherIconVerifier.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/LauncherIconVerifier.java index 2de2e002a9470..39e483f1feeb3 100644 --- a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/LauncherIconVerifier.java +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/LauncherIconVerifier.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2024, 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 @@ -31,6 +31,7 @@ import java.nio.file.Path; import java.util.Optional; import javax.imageio.ImageIO; +import static jdk.jpackage.internal.util.function.ExceptionBox.rethrowUnchecked; public final class LauncherIconVerifier { public LauncherIconVerifier() { @@ -176,7 +177,7 @@ private WinIconVerifier() { iconSwapWrapper.setAccessible(true); } catch (ClassNotFoundException | NoSuchMethodException | SecurityException ex) { - throw Functional.rethrowUnchecked(ex); + throw rethrowUnchecked(ex); } } @@ -254,14 +255,14 @@ private void setIcon(Path iconPath, Path launcherPath) { } } } catch (IllegalAccessException | InvocationTargetException ex) { - throw Functional.rethrowUnchecked(ex); + throw rethrowUnchecked(ex); } } finally { launcherPath.toFile().setWritable(false, true); } } - final static WinIconVerifier instance = new WinIconVerifier(); + static final WinIconVerifier instance = new WinIconVerifier(); private final Class executableRebranderClass; private final Method lockResource; diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/LinuxHelper.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/LinuxHelper.java index a96bab4935598..35baff3d5db5d 100644 --- a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/LinuxHelper.java +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/LinuxHelper.java @@ -41,8 +41,8 @@ import java.util.stream.Collectors; import java.util.stream.Stream; import jdk.jpackage.internal.ApplicationLayout; -import jdk.jpackage.internal.IOUtils; -import jdk.jpackage.test.Functional.ThrowingConsumer; +import jdk.jpackage.internal.util.PathUtils; +import jdk.jpackage.internal.util.function.ThrowingConsumer; import jdk.jpackage.test.PackageTest.PackageHandlers; @@ -578,7 +578,7 @@ private static String queryMimeTypeDefaultHandler(String mimeType) { private static void verifyIconInScriptlet(Scriptlet scriptletType, List scriptletBody, Path iconPathInPackage) { - final String dashMime = IOUtils.replaceSuffix( + final String dashMime = PathUtils.replaceSuffix( iconPathInPackage.getFileName(), null).toString(); final String xdgCmdName = "xdg-icon-resource"; diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/MacHelper.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/MacHelper.java index 63afb6cf9f765..9cadd419ca135 100644 --- a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/MacHelper.java +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/MacHelper.java @@ -43,11 +43,11 @@ import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; -import jdk.jpackage.internal.IOUtils; -import jdk.jpackage.test.Functional.ThrowingConsumer; -import jdk.jpackage.test.Functional.ThrowingSupplier; +import jdk.jpackage.internal.util.function.ThrowingConsumer; +import jdk.jpackage.internal.util.function.ThrowingSupplier; import jdk.jpackage.test.PackageTest.PackageHandlers; import jdk.jpackage.internal.RetryExecutor; +import jdk.jpackage.internal.util.PathUtils; import org.xml.sax.SAXException; import org.w3c.dom.NodeList; @@ -212,7 +212,7 @@ static PackageHandlers createPkgPackageHandlers() { // Unpack all ".pkg" files from $dataDir folder in $unpackDir folder try (var dataListing = Files.list(dataDir)) { dataListing.filter(file -> { - return ".pkg".equals(IOUtils.getSuffix(file.getFileName())); + return ".pkg".equals(PathUtils.getSuffix(file.getFileName())); }).forEach(ThrowingConsumer.toConsumer(pkgDir -> { // Installation root of the package is stored in // /pkg-info@install-location attribute in $pkgDir/PackageInfo xml file diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/MethodCall.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/MethodCall.java index d5b8bd702c8da..51a8ade8a1d64 100644 --- a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/MethodCall.java +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/MethodCall.java @@ -37,7 +37,7 @@ import java.util.function.Predicate; import java.util.stream.IntStream; import java.util.stream.Stream; -import jdk.jpackage.test.Functional.ThrowingConsumer; +import jdk.jpackage.internal.util.function.ThrowingConsumer; import jdk.jpackage.test.TestInstance.TestDesc; class MethodCall implements ThrowingConsumer { diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/PackageTest.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/PackageTest.java index 6f486425e7316..7c6aab29fee57 100644 --- a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/PackageTest.java +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/PackageTest.java @@ -46,13 +46,13 @@ import java.util.stream.Stream; import java.util.stream.StreamSupport; import jdk.jpackage.internal.ApplicationLayout; -import jdk.jpackage.test.Functional.ThrowingBiConsumer; -import static jdk.jpackage.test.Functional.ThrowingBiConsumer.toBiConsumer; -import jdk.jpackage.test.Functional.ThrowingConsumer; -import static jdk.jpackage.test.Functional.ThrowingConsumer.toConsumer; -import jdk.jpackage.test.Functional.ThrowingRunnable; -import static jdk.jpackage.test.Functional.ThrowingSupplier.toSupplier; -import static jdk.jpackage.test.Functional.rethrowUnchecked; +import jdk.jpackage.internal.util.function.ThrowingBiConsumer; +import static jdk.jpackage.internal.util.function.ThrowingBiConsumer.toBiConsumer; +import jdk.jpackage.internal.util.function.ThrowingConsumer; +import static jdk.jpackage.internal.util.function.ThrowingConsumer.toConsumer; +import jdk.jpackage.internal.util.function.ThrowingRunnable; +import static jdk.jpackage.internal.util.function.ThrowingSupplier.toSupplier; +import static jdk.jpackage.internal.util.function.ExceptionBox.rethrowUnchecked; import static jdk.jpackage.test.PackageType.LINUX; import static jdk.jpackage.test.PackageType.LINUX_DEB; import static jdk.jpackage.test.PackageType.LINUX_RPM; diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/PackageType.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/PackageType.java index 71637ef7134a6..8aa7d005adbd3 100644 --- a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/PackageType.java +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/PackageType.java @@ -32,6 +32,7 @@ import java.util.stream.Collectors; import java.util.stream.Stream; import jdk.jpackage.internal.Log; +import static jdk.jpackage.internal.util.function.ExceptionBox.rethrowUnchecked; /** * jpackage type traits. @@ -103,7 +104,7 @@ private static boolean isBundlerSupportedImpl(String bundlerClass) { } catch (ClassNotFoundException | IllegalAccessException ex) { } catch (InstantiationException | NoSuchMethodException | InvocationTargetException ex) { - Functional.rethrowUnchecked(ex); + rethrowUnchecked(ex); } return false; } @@ -127,7 +128,7 @@ private static boolean isBundlerSupported(String bundlerClass) { thread.run(); thread.join(); } catch (InterruptedException ex) { - Functional.rethrowUnchecked(ex); + rethrowUnchecked(ex); } return reply.get(); } @@ -136,15 +137,15 @@ private static boolean isBundlerSupported(String bundlerClass) { private final String suffix; private final boolean supported; - public final static Set LINUX = Set.of(LINUX_DEB, LINUX_RPM); - public final static Set WINDOWS = Set.of(WIN_EXE, WIN_MSI); - public final static Set MAC = Set.of(MAC_PKG, MAC_DMG); - public final static Set NATIVE = Stream.concat( + public static final Set LINUX = Set.of(LINUX_DEB, LINUX_RPM); + public static final Set WINDOWS = Set.of(WIN_EXE, WIN_MSI); + public static final Set MAC = Set.of(MAC_PKG, MAC_DMG); + public static final Set NATIVE = Stream.concat( Stream.concat(LINUX.stream(), WINDOWS.stream()), MAC.stream()).collect(Collectors.toUnmodifiableSet()); - private final static class Inner { - private final static Set DISABLED_PACKAGERS = Optional.ofNullable( + private static final class Inner { + private static final Set DISABLED_PACKAGERS = Optional.ofNullable( TKit.tokenizeConfigProperty("disabledPackagers")).orElse( TKit.isLinuxAPT() ? Set.of("rpm") : Collections.emptySet()); } diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/TKit.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/TKit.java index 8f91d581ef145..b58595645682c 100644 --- a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/TKit.java +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/TKit.java @@ -61,10 +61,10 @@ import static java.util.stream.Collectors.toSet; import java.util.stream.Stream; import jdk.internal.util.OperatingSystem; -import jdk.jpackage.test.Functional.ExceptionBox; -import jdk.jpackage.test.Functional.ThrowingConsumer; -import jdk.jpackage.test.Functional.ThrowingRunnable; -import jdk.jpackage.test.Functional.ThrowingSupplier; +import jdk.jpackage.internal.util.function.ExceptionBox; +import jdk.jpackage.internal.util.function.ThrowingConsumer; +import jdk.jpackage.internal.util.function.ThrowingRunnable; +import jdk.jpackage.internal.util.function.ThrowingSupplier; public final class TKit { diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/TestBuilder.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/TestBuilder.java index c2fc1789a2531..23fd5dd52a508 100644 --- a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/TestBuilder.java +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/TestBuilder.java @@ -40,9 +40,9 @@ import jdk.jpackage.test.Annotations.AfterEach; import jdk.jpackage.test.Annotations.BeforeEach; import jdk.jpackage.test.Annotations.Test; -import jdk.jpackage.test.Functional.ThrowingConsumer; -import static jdk.jpackage.test.Functional.ThrowingConsumer.toConsumer; -import jdk.jpackage.test.Functional.ThrowingFunction; +import jdk.jpackage.internal.util.function.ThrowingConsumer; +import static jdk.jpackage.internal.util.function.ThrowingConsumer.toConsumer; +import jdk.jpackage.internal.util.function.ThrowingFunction; import jdk.jpackage.test.TestMethodSupplier.InvalidAnnotationException; import static jdk.jpackage.test.TestMethodSupplier.MethodQuery.fromQualifiedMethodName; diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/TestInstance.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/TestInstance.java index f619c9e222e24..871ddc2427784 100644 --- a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/TestInstance.java +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/TestInstance.java @@ -40,9 +40,10 @@ import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; -import jdk.jpackage.test.Functional.ThrowingConsumer; -import jdk.jpackage.test.Functional.ThrowingFunction; -import jdk.jpackage.test.Functional.ThrowingRunnable; +import jdk.jpackage.internal.util.function.ThrowingConsumer; +import jdk.jpackage.internal.util.function.ThrowingFunction; +import jdk.jpackage.internal.util.function.ThrowingRunnable; +import jdk.jpackage.internal.util.function.ThrowingSupplier; final class TestInstance implements ThrowingRunnable { @@ -258,7 +259,7 @@ private static Class enclosingMainMethodClass() { StackTraceElement st[] = Thread.currentThread().getStackTrace(); for (StackTraceElement ste : st) { if ("main".equals(ste.getMethodName())) { - return Functional.ThrowingSupplier.toSupplier(() -> Class.forName( + return ThrowingSupplier.toSupplier(() -> Class.forName( ste.getClassName())).get(); } } diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/TestMethodSupplier.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/TestMethodSupplier.java index 83b1c19bd9553..0d701d0ec6f55 100644 --- a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/TestMethodSupplier.java +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/TestMethodSupplier.java @@ -49,8 +49,8 @@ import jdk.jpackage.test.Annotations.ParameterSupplierGroup; import jdk.jpackage.test.Annotations.Parameters; import jdk.jpackage.test.Annotations.Test; -import static jdk.jpackage.test.Functional.ThrowingFunction.toFunction; -import static jdk.jpackage.test.Functional.ThrowingSupplier.toSupplier; +import static jdk.jpackage.internal.util.function.ThrowingFunction.toFunction; +import static jdk.jpackage.internal.util.function.ThrowingSupplier.toSupplier; import static jdk.jpackage.test.MethodCall.mapArgs; final class TestMethodSupplier { diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/WindowsHelper.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/WindowsHelper.java index 1976a5cf72c19..42ea9e3e9a74f 100644 --- a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/WindowsHelper.java +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/WindowsHelper.java @@ -36,7 +36,7 @@ import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; -import jdk.jpackage.test.Functional.ThrowingRunnable; +import jdk.jpackage.internal.util.function.ThrowingRunnable; import jdk.jpackage.test.PackageTest.PackageHandlers; public class WindowsHelper { diff --git a/test/jdk/tools/jpackage/linux/AppAboutUrlTest.java b/test/jdk/tools/jpackage/linux/AppAboutUrlTest.java index 0d8f0ec4805e1..aef46e2972519 100644 --- a/test/jdk/tools/jpackage/linux/AppAboutUrlTest.java +++ b/test/jdk/tools/jpackage/linux/AppAboutUrlTest.java @@ -22,7 +22,7 @@ */ import jdk.jpackage.test.Annotations.Test; -import jdk.jpackage.test.Functional.ThrowingConsumer; +import jdk.jpackage.internal.util.function.ThrowingConsumer; import jdk.jpackage.test.JPackageCommand; import jdk.jpackage.test.PackageTest; import jdk.jpackage.test.PackageType; diff --git a/test/jdk/tools/jpackage/share/AppContentTest.java b/test/jdk/tools/jpackage/share/AppContentTest.java index e056070a5fca4..d33960092ee88 100644 --- a/test/jdk/tools/jpackage/share/AppContentTest.java +++ b/test/jdk/tools/jpackage/share/AppContentTest.java @@ -33,8 +33,8 @@ import java.util.List; import static java.util.stream.Collectors.joining; import java.util.stream.Stream; -import jdk.jpackage.internal.IOUtils; -import jdk.jpackage.test.Functional.ThrowingFunction; +import jdk.jpackage.internal.util.FileUtils; +import jdk.jpackage.internal.util.function.ThrowingFunction; import jdk.jpackage.test.JPackageCommand; @@ -65,7 +65,7 @@ public class AppContentTest { // In particular, random files should be placed in "Contents/Resources" folder // otherwise "codesign" will fail to sign. // Need to prepare arguments for `--app-content` accordingly. - private final static boolean copyInResources = TKit.isOSX(); + private static final boolean copyInResources = TKit.isOSX(); private final List testPathArgs; @@ -148,7 +148,7 @@ private static Path copyAppContentPath(Path appContentPath) throws IOException { var srcPath = TKit.TEST_SRC_ROOT.resolve(appContentPath); var dstPath = appContentArg.resolve(srcPath.getFileName()); Files.createDirectories(dstPath.getParent()); - IOUtils.copyRecursive(srcPath, dstPath); + FileUtils.copyRecursive(srcPath, dstPath); return appContentArg; } diff --git a/test/jdk/tools/jpackage/share/BasicTest.java b/test/jdk/tools/jpackage/share/BasicTest.java index 61668b9e87896..c6e4e93015519 100644 --- a/test/jdk/tools/jpackage/share/BasicTest.java +++ b/test/jdk/tools/jpackage/share/BasicTest.java @@ -41,7 +41,7 @@ import jdk.jpackage.test.JavaTool; import jdk.jpackage.test.Annotations.Test; import jdk.jpackage.test.Annotations.Parameter; -import jdk.jpackage.test.Functional.ThrowingConsumer; +import jdk.jpackage.internal.util.function.ThrowingConsumer; import static jdk.jpackage.test.RunnablePackageTest.Action.CREATE_AND_UNPACK; /* diff --git a/test/jdk/tools/jpackage/share/IconTest.java b/test/jdk/tools/jpackage/share/IconTest.java index 2d6469f5f2e8b..d5edbc9324566 100644 --- a/test/jdk/tools/jpackage/share/IconTest.java +++ b/test/jdk/tools/jpackage/share/IconTest.java @@ -41,8 +41,8 @@ import jdk.jpackage.test.Executor; import jdk.jpackage.test.LinuxHelper; import jdk.jpackage.test.AdditionalLauncher; -import jdk.jpackage.test.Functional.ThrowingConsumer; -import jdk.jpackage.test.Functional.ThrowingBiConsumer; +import jdk.jpackage.internal.util.function.ThrowingConsumer; +import jdk.jpackage.internal.util.function.ThrowingBiConsumer; import jdk.jpackage.test.Annotations.Parameters; import jdk.jpackage.test.Annotations.Test; @@ -428,7 +428,7 @@ private enum Launcher { private final Path cmdlineIcon; private final Path resourceDirIcon; - private final static Set PRIMARY = Set.of(Main, Additional); + private static final Set PRIMARY = Set.of(Main, Additional); } private final boolean appImage; @@ -440,7 +440,7 @@ private static Path iconPath(String name) { + TKit.ICON_SUFFIX)); } - private final static Path[] ICONS = Stream.of("icon", "icon2", "icon3", + private static final Path[] ICONS = Stream.of("icon", "icon2", "icon3", "icon4") .map(IconTest::iconPath) .collect(Collectors.toList()).toArray(Path[]::new); diff --git a/test/jdk/tools/jpackage/share/InOutPathTest.java b/test/jdk/tools/jpackage/share/InOutPathTest.java index 15d96283ef4a7..b257913314893 100644 --- a/test/jdk/tools/jpackage/share/InOutPathTest.java +++ b/test/jdk/tools/jpackage/share/InOutPathTest.java @@ -36,7 +36,7 @@ import jdk.jpackage.internal.PackageFile; import jdk.jpackage.test.Annotations.Parameters; import jdk.jpackage.test.Annotations.Test; -import jdk.jpackage.test.Functional.ThrowingConsumer; +import jdk.jpackage.internal.util.function.ThrowingConsumer; import jdk.jpackage.test.JPackageCommand; import jdk.jpackage.test.JPackageCommand.AppLayoutAssert; import jdk.jpackage.test.PackageTest; diff --git a/test/jdk/tools/jpackage/share/MainClassTest.java b/test/jdk/tools/jpackage/share/MainClassTest.java index d9188e8f18fd3..a031bbc278802 100644 --- a/test/jdk/tools/jpackage/share/MainClassTest.java +++ b/test/jdk/tools/jpackage/share/MainClassTest.java @@ -44,7 +44,7 @@ import jdk.jpackage.test.Annotations.Parameters; import jdk.jpackage.test.Annotations.Test; import jdk.jpackage.test.CfgFile; -import jdk.jpackage.test.Functional.ThrowingConsumer; +import jdk.jpackage.internal.util.function.ThrowingConsumer; diff --git a/test/jdk/tools/jpackage/share/PerUserCfgTest.java b/test/jdk/tools/jpackage/share/PerUserCfgTest.java index 0fff7eb3a2de7..2e62aa5c5d631 100644 --- a/test/jdk/tools/jpackage/share/PerUserCfgTest.java +++ b/test/jdk/tools/jpackage/share/PerUserCfgTest.java @@ -29,7 +29,7 @@ import jdk.jpackage.test.AdditionalLauncher; import jdk.jpackage.test.PackageTest; import jdk.jpackage.test.Annotations.Test; -import jdk.jpackage.test.Functional.ThrowingConsumer; +import jdk.jpackage.internal.util.function.ThrowingConsumer; import jdk.jpackage.test.HelloApp; import jdk.jpackage.test.JPackageCommand; import jdk.jpackage.test.LinuxHelper; diff --git a/test/jdk/tools/jpackage/share/RuntimeImageSymbolicLinksTest.java b/test/jdk/tools/jpackage/share/RuntimeImageSymbolicLinksTest.java index 0e48df630afc9..649ac0a369513 100644 --- a/test/jdk/tools/jpackage/share/RuntimeImageSymbolicLinksTest.java +++ b/test/jdk/tools/jpackage/share/RuntimeImageSymbolicLinksTest.java @@ -21,20 +21,11 @@ * questions. */ -import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.util.HashSet; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; import jdk.jpackage.internal.ApplicationLayout; import jdk.jpackage.test.TKit; -import jdk.jpackage.test.PackageTest; -import jdk.jpackage.test.PackageType; -import jdk.jpackage.test.Functional; import jdk.jpackage.test.Annotations.Test; -import jdk.jpackage.test.Annotations.Parameter; import jdk.jpackage.test.JPackageCommand; import jdk.jpackage.test.JavaTool; import jdk.jpackage.test.Executor; diff --git a/test/jdk/tools/jpackage/windows/WinLongVersionTest.java b/test/jdk/tools/jpackage/windows/WinLongVersionTest.java index 0d52da65630e5..7a915b5c123fd 100644 --- a/test/jdk/tools/jpackage/windows/WinLongVersionTest.java +++ b/test/jdk/tools/jpackage/windows/WinLongVersionTest.java @@ -24,7 +24,6 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.util.Set; import java.util.UUID; import java.util.function.Supplier; import javax.xml.transform.Result; @@ -36,7 +35,7 @@ import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; -import jdk.jpackage.internal.IOUtils; +import jdk.jpackage.internal.util.XmlUtils; import jdk.jpackage.test.Annotations.Test; import jdk.jpackage.test.Executor; import jdk.jpackage.test.PackageTest; @@ -148,7 +147,7 @@ public static void test() throws IOException { Path scriptPath = resourceDir.resolve(String.format( "%s-post-msi.wsf", cmd.name())); - IOUtils.createXml(scriptPath, xml -> { + XmlUtils.createXml(scriptPath, xml -> { xml.writeStartElement("job"); xml.writeAttribute("id", "main"); xml.writeStartElement("script"); @@ -194,7 +193,7 @@ public static void testNoUpgradeTable() throws IOException { cmd.setFakeRuntime(); // Create package without Upgrade table - Document doc = IOUtils.initDocumentBuilder().parse( + Document doc = XmlUtils.initDocumentBuilder().parse( Files.newInputStream(TKit.SRC_ROOT.resolve( "windows/classes/jdk/jpackage/internal/resources/main.wxs"))); XPath xPath = XPathFactory.newInstance().newXPath(); diff --git a/test/jdk/tools/jpackage/windows/WinScriptTest.java b/test/jdk/tools/jpackage/windows/WinScriptTest.java index 296da482bb075..98b4922826dda 100644 --- a/test/jdk/tools/jpackage/windows/WinScriptTest.java +++ b/test/jdk/tools/jpackage/windows/WinScriptTest.java @@ -24,8 +24,7 @@ import java.io.IOException; import java.nio.file.Path; import java.util.List; -import java.util.ArrayList; -import jdk.jpackage.internal.IOUtils; +import jdk.jpackage.internal.util.XmlUtils; import jdk.jpackage.test.TKit; import jdk.jpackage.test.PackageTest; import jdk.jpackage.test.PackageType; @@ -147,7 +146,7 @@ void assertJPackageOutput(List output) { } void createScript(JPackageCommand cmd) throws IOException { - IOUtils.createXml(Path.of(cmd.getArgumentValue("--resource-dir"), + XmlUtils.createXml(Path.of(cmd.getArgumentValue("--resource-dir"), String.format("%s-%s.wsf", cmd.name(), scriptSuffixName)), xml -> { xml.writeStartElement("job"); xml.writeAttribute("id", "main"); From 1717946c1b6494a4a44622027ac1dd175fcb9563 Mon Sep 17 00:00:00 2001 From: Ivan Walulya Date: Tue, 19 Nov 2024 14:31:40 +0000 Subject: [PATCH 06/74] 8344302: G1: Refactor G1CMTask::do_marking_step to use smaller wrapper methods Reviewed-by: tschatzl, ayang --- src/hotspot/share/gc/g1/g1ConcurrentMark.cpp | 431 ++++++++++--------- src/hotspot/share/gc/g1/g1ConcurrentMark.hpp | 15 + 2 files changed, 237 insertions(+), 209 deletions(-) diff --git a/src/hotspot/share/gc/g1/g1ConcurrentMark.cpp b/src/hotspot/share/gc/g1/g1ConcurrentMark.cpp index 52d26418af6cf..d0879e9967cd3 100644 --- a/src/hotspot/share/gc/g1/g1ConcurrentMark.cpp +++ b/src/hotspot/share/gc/g1/g1ConcurrentMark.cpp @@ -2483,6 +2483,214 @@ bool G1ConcurrentMark::try_stealing(uint worker_id, G1TaskQueueEntry& task_entry return _task_queues->steal(worker_id, task_entry); } +void G1CMTask::process_current_region(G1CMBitMapClosure& bitmap_closure) { + if (has_aborted() || _curr_region == nullptr) { + return; + } + + // This means that we're already holding on to a region. + assert(_finger != nullptr, "if region is not null, then the finger " + "should not be null either"); + + // We might have restarted this task after an evacuation pause + // which might have evacuated the region we're holding on to + // underneath our feet. Let's read its limit again to make sure + // that we do not iterate over a region of the heap that + // contains garbage (update_region_limit() will also move + // _finger to the start of the region if it is found empty). + update_region_limit(); + // We will start from _finger not from the start of the region, + // as we might be restarting this task after aborting half-way + // through scanning this region. In this case, _finger points to + // the address where we last found a marked object. If this is a + // fresh region, _finger points to start(). + MemRegion mr = MemRegion(_finger, _region_limit); + + assert(!_curr_region->is_humongous() || mr.start() == _curr_region->bottom(), + "humongous regions should go around loop once only"); + + // Some special cases: + // If the memory region is empty, we can just give up the region. + // If the current region is humongous then we only need to check + // the bitmap for the bit associated with the start of the object, + // scan the object if it's live, and give up the region. + // Otherwise, let's iterate over the bitmap of the part of the region + // that is left. + // If the iteration is successful, give up the region. + if (mr.is_empty()) { + giveup_current_region(); + abort_marking_if_regular_check_fail(); + } else if (_curr_region->is_humongous() && mr.start() == _curr_region->bottom()) { + if (_mark_bitmap->is_marked(mr.start())) { + // The object is marked - apply the closure + bitmap_closure.do_addr(mr.start()); + } + // Even if this task aborted while scanning the humongous object + // we can (and should) give up the current region. + giveup_current_region(); + abort_marking_if_regular_check_fail(); + } else if (_mark_bitmap->iterate(&bitmap_closure, mr)) { + giveup_current_region(); + abort_marking_if_regular_check_fail(); + } else { + assert(has_aborted(), "currently the only way to do so"); + // The only way to abort the bitmap iteration is to return + // false from the do_bit() method. However, inside the + // do_bit() method we move the _finger to point to the + // object currently being looked at. So, if we bail out, we + // have definitely set _finger to something non-null. + assert(_finger != nullptr, "invariant"); + + // Region iteration was actually aborted. So now _finger + // points to the address of the object we last scanned. If we + // leave it there, when we restart this task, we will rescan + // the object. It is easy to avoid this. We move the finger by + // enough to point to the next possible object header. + assert(_finger < _region_limit, "invariant"); + HeapWord* const new_finger = _finger + cast_to_oop(_finger)->size(); + if (new_finger >= _region_limit) { + giveup_current_region(); + } else { + move_finger_to(new_finger); + } + } +} + +void G1CMTask::claim_new_region() { + // Read the note on the claim_region() method on why it might + // return null with potentially more regions available for + // claiming and why we have to check out_of_regions() to determine + // whether we're done or not. + while (!has_aborted() && _curr_region == nullptr && !_cm->out_of_regions()) { + // We are going to try to claim a new region. We should have + // given up on the previous one. + // Separated the asserts so that we know which one fires. + assert(_curr_region == nullptr, "invariant"); + assert(_finger == nullptr, "invariant"); + assert(_region_limit == nullptr, "invariant"); + G1HeapRegion* claimed_region = _cm->claim_region(_worker_id); + if (claimed_region != nullptr) { + // Yes, we managed to claim one + setup_for_region(claimed_region); + assert(_curr_region == claimed_region, "invariant"); + } + // It is important to call the regular clock here. It might take + // a while to claim a region if, for example, we hit a large + // block of empty regions. So we need to call the regular clock + // method once round the loop to make sure it's called + // frequently enough. + abort_marking_if_regular_check_fail(); + } +} + +void G1CMTask::attempt_stealing() { + // We cannot check whether the global stack is empty, since other + // tasks might be pushing objects to it concurrently. + assert(_cm->out_of_regions() && _task_queue->size() == 0, + "only way to reach here"); + while (!has_aborted()) { + G1TaskQueueEntry entry; + if (_cm->try_stealing(_worker_id, entry)) { + scan_task_entry(entry); + + // And since we're towards the end, let's totally drain the + // local queue and global stack. + drain_local_queue(false); + drain_global_stack(false); + } else { + break; + } + } +} + +void G1CMTask::attempt_termination(bool is_serial) { + // We cannot check whether the global stack is empty, since other + // tasks might be concurrently pushing objects on it. + // Separated the asserts so that we know which one fires. + assert(_cm->out_of_regions(), "only way to reach here"); + assert(_task_queue->size() == 0, "only way to reach here"); + double termination_start_time_ms = os::elapsedTime() * 1000.0; + + // The G1CMTask class also extends the TerminatorTerminator class, + // hence its should_exit_termination() method will also decide + // whether to exit the termination protocol or not. + bool finished = (is_serial || + _cm->terminator()->offer_termination(this)); + _termination_time_ms += (os::elapsedTime() * 1000.0 - termination_start_time_ms); + + if (finished) { + // We're all done. + + // We can now guarantee that the global stack is empty, since + // all other tasks have finished. We separated the guarantees so + // that, if a condition is false, we can immediately find out + // which one. + guarantee(_cm->out_of_regions(), "only way to reach here"); + guarantee(_cm->mark_stack_empty(), "only way to reach here"); + guarantee(_task_queue->size() == 0, "only way to reach here"); + guarantee(!_cm->has_overflown(), "only way to reach here"); + guarantee(!has_aborted(), "should never happen if termination has completed"); + } else { + // Apparently there's more work to do. Let's abort this task. We + // will restart it and hopefully we can find more things to do. + set_has_aborted(); + } +} + +void G1CMTask::handle_abort(bool is_serial, double elapsed_time_ms) { + if (_has_timed_out) { + double diff_ms = elapsed_time_ms - _time_target_ms; + // Keep statistics of how well we did with respect to hitting + // our target only if we actually timed out (if we aborted for + // other reasons, then the results might get skewed). + _marking_step_diff_ms.add(diff_ms); + } + + if (!_cm->has_overflown()) { + return; + } + + // This is the interesting one. We aborted because a global + // overflow was raised. This means we have to restart the + // marking phase and start iterating over regions. However, in + // order to do this we have to make sure that all tasks stop + // what they are doing and re-initialize in a safe manner. We + // will achieve this with the use of two barrier sync points. + if (!is_serial) { + // We only need to enter the sync barrier if being called + // from a parallel context + _cm->enter_first_sync_barrier(_worker_id); + + // When we exit this sync barrier we know that all tasks have + // stopped doing marking work. So, it's now safe to + // re-initialize our data structures. + } + + clear_region_fields(); + flush_mark_stats_cache(); + + if (!is_serial) { + // If we're executing the concurrent phase of marking, reset the marking + // state; otherwise the marking state is reset after reference processing, + // during the remark pause. + // If we reset here as a result of an overflow during the remark we will + // see assertion failures from any subsequent set_concurrency_and_phase() + // calls. + if (_cm->concurrent() && _worker_id == 0) { + // Worker 0 is responsible for clearing the global data structures because + // of an overflow. During STW we should not clear the overflow flag (in + // G1ConcurrentMark::reset_marking_state()) since we rely on it being true when we exit + // method to abort the pause and restart concurrent marking. + _cm->reset_marking_for_restart(); + + log_info(gc, marking)("Concurrent Mark reset for overflow"); + } + + // ...and enter the second barrier. + _cm->enter_second_sync_barrier(_worker_id); + } +} + /***************************************************************************** The do_marking_step(time_target_ms, ...) method is the building @@ -2653,123 +2861,27 @@ void G1CMTask::do_marking_step(double time_target_ms, drain_global_stack(true); do { - if (!has_aborted() && _curr_region != nullptr) { - // This means that we're already holding on to a region. - assert(_finger != nullptr, "if region is not null, then the finger " - "should not be null either"); - - // We might have restarted this task after an evacuation pause - // which might have evacuated the region we're holding on to - // underneath our feet. Let's read its limit again to make sure - // that we do not iterate over a region of the heap that - // contains garbage (update_region_limit() will also move - // _finger to the start of the region if it is found empty). - update_region_limit(); - // We will start from _finger not from the start of the region, - // as we might be restarting this task after aborting half-way - // through scanning this region. In this case, _finger points to - // the address where we last found a marked object. If this is a - // fresh region, _finger points to start(). - MemRegion mr = MemRegion(_finger, _region_limit); - - assert(!_curr_region->is_humongous() || mr.start() == _curr_region->bottom(), - "humongous regions should go around loop once only"); - - // Some special cases: - // If the memory region is empty, we can just give up the region. - // If the current region is humongous then we only need to check - // the bitmap for the bit associated with the start of the object, - // scan the object if it's live, and give up the region. - // Otherwise, let's iterate over the bitmap of the part of the region - // that is left. - // If the iteration is successful, give up the region. - if (mr.is_empty()) { - giveup_current_region(); - abort_marking_if_regular_check_fail(); - } else if (_curr_region->is_humongous() && mr.start() == _curr_region->bottom()) { - if (_mark_bitmap->is_marked(mr.start())) { - // The object is marked - apply the closure - bitmap_closure.do_addr(mr.start()); - } - // Even if this task aborted while scanning the humongous object - // we can (and should) give up the current region. - giveup_current_region(); - abort_marking_if_regular_check_fail(); - } else if (_mark_bitmap->iterate(&bitmap_closure, mr)) { - giveup_current_region(); - abort_marking_if_regular_check_fail(); - } else { - assert(has_aborted(), "currently the only way to do so"); - // The only way to abort the bitmap iteration is to return - // false from the do_bit() method. However, inside the - // do_bit() method we move the _finger to point to the - // object currently being looked at. So, if we bail out, we - // have definitely set _finger to something non-null. - assert(_finger != nullptr, "invariant"); - - // Region iteration was actually aborted. So now _finger - // points to the address of the object we last scanned. If we - // leave it there, when we restart this task, we will rescan - // the object. It is easy to avoid this. We move the finger by - // enough to point to the next possible object header. - assert(_finger < _region_limit, "invariant"); - HeapWord* const new_finger = _finger + cast_to_oop(_finger)->size(); - // Check if bitmap iteration was aborted while scanning the last object - if (new_finger >= _region_limit) { - giveup_current_region(); - } else { - move_finger_to(new_finger); - } - } - } + process_current_region(bitmap_closure); // At this point we have either completed iterating over the // region we were holding on to, or we have aborted. // We then partially drain the local queue and the global stack. - // (Do we really need this?) drain_local_queue(true); drain_global_stack(true); - // Read the note on the claim_region() method on why it might - // return null with potentially more regions available for - // claiming and why we have to check out_of_regions() to determine - // whether we're done or not. - while (!has_aborted() && _curr_region == nullptr && !_cm->out_of_regions()) { - // We are going to try to claim a new region. We should have - // given up on the previous one. - // Separated the asserts so that we know which one fires. - assert(_curr_region == nullptr, "invariant"); - assert(_finger == nullptr, "invariant"); - assert(_region_limit == nullptr, "invariant"); - G1HeapRegion* claimed_region = _cm->claim_region(_worker_id); - if (claimed_region != nullptr) { - // Yes, we managed to claim one - setup_for_region(claimed_region); - assert(_curr_region == claimed_region, "invariant"); - } - // It is important to call the regular clock here. It might take - // a while to claim a region if, for example, we hit a large - // block of empty regions. So we need to call the regular clock - // method once round the loop to make sure it's called - // frequently enough. - abort_marking_if_regular_check_fail(); - } + claim_new_region(); - if (!has_aborted() && _curr_region == nullptr) { - assert(_cm->out_of_regions(), - "at this point we should be out of regions"); - } + assert(has_aborted() || _curr_region != nullptr || _cm->out_of_regions(), + "at this point we should be out of regions"); } while ( _curr_region != nullptr && !has_aborted()); - if (!has_aborted()) { - // We cannot check whether the global stack is empty, since other - // tasks might be pushing objects to it concurrently. - assert(_cm->out_of_regions(), - "at this point we should be out of regions"); - // Try to reduce the number of available SATB buffers so that - // remark has less work to do. - drain_satb_buffers(); - } + // We cannot check whether the global stack is empty, since other + // tasks might be pushing objects to it concurrently. + assert(has_aborted() || _cm->out_of_regions(), + "at this point we should be out of regions"); + // Try to reduce the number of available SATB buffers so that + // remark has less work to do. + drain_satb_buffers(); // Since we've done everything else, we can now totally drain the // local queue and global stack. @@ -2780,60 +2892,13 @@ void G1CMTask::do_marking_step(double time_target_ms, if (do_stealing && !has_aborted()) { // We have not aborted. This means that we have finished all that // we could. Let's try to do some stealing... - - // We cannot check whether the global stack is empty, since other - // tasks might be pushing objects to it concurrently. - assert(_cm->out_of_regions() && _task_queue->size() == 0, - "only way to reach here"); - while (!has_aborted()) { - G1TaskQueueEntry entry; - if (_cm->try_stealing(_worker_id, entry)) { - scan_task_entry(entry); - - // And since we're towards the end, let's totally drain the - // local queue and global stack. - drain_local_queue(false); - drain_global_stack(false); - } else { - break; - } - } + attempt_stealing(); } // We still haven't aborted. Now, let's try to get into the // termination protocol. if (do_termination && !has_aborted()) { - // We cannot check whether the global stack is empty, since other - // tasks might be concurrently pushing objects on it. - // Separated the asserts so that we know which one fires. - assert(_cm->out_of_regions(), "only way to reach here"); - assert(_task_queue->size() == 0, "only way to reach here"); - double termination_start_time_ms = os::elapsedTime() * 1000.0; - - // The G1CMTask class also extends the TerminatorTerminator class, - // hence its should_exit_termination() method will also decide - // whether to exit the termination protocol or not. - bool finished = (is_serial || - _cm->terminator()->offer_termination(this)); - _termination_time_ms += (os::elapsedTime() * 1000.0 - termination_start_time_ms); - - if (finished) { - // We're all done. - - // We can now guarantee that the global stack is empty, since - // all other tasks have finished. We separated the guarantees so - // that, if a condition is false, we can immediately find out - // which one. - guarantee(_cm->out_of_regions(), "only way to reach here"); - guarantee(_cm->mark_stack_empty(), "only way to reach here"); - guarantee(_task_queue->size() == 0, "only way to reach here"); - guarantee(!_cm->has_overflown(), "only way to reach here"); - guarantee(!has_aborted(), "should never happen if termination has completed"); - } else { - // Apparently there's more work to do. Let's abort this task. It - // will restart it and we can hopefully find more things to do. - set_has_aborted(); - } + attempt_termination(is_serial); } // Mainly for debugging purposes to make sure that a pointer to the @@ -2847,59 +2912,7 @@ void G1CMTask::do_marking_step(double time_target_ms, if (has_aborted()) { // The task was aborted for some reason. - if (_has_timed_out) { - double diff_ms = elapsed_time_ms - _time_target_ms; - // Keep statistics of how well we did with respect to hitting - // our target only if we actually timed out (if we aborted for - // other reasons, then the results might get skewed). - _marking_step_diff_ms.add(diff_ms); - } - - if (_cm->has_overflown()) { - // This is the interesting one. We aborted because a global - // overflow was raised. This means we have to restart the - // marking phase and start iterating over regions. However, in - // order to do this we have to make sure that all tasks stop - // what they are doing and re-initialize in a safe manner. We - // will achieve this with the use of two barrier sync points. - - if (!is_serial) { - // We only need to enter the sync barrier if being called - // from a parallel context - _cm->enter_first_sync_barrier(_worker_id); - - // When we exit this sync barrier we know that all tasks have - // stopped doing marking work. So, it's now safe to - // re-initialize our data structures. - } - - clear_region_fields(); - flush_mark_stats_cache(); - - if (!is_serial) { - // If we're executing the concurrent phase of marking, reset the marking - // state; otherwise the marking state is reset after reference processing, - // during the remark pause. - // If we reset here as a result of an overflow during the remark we will - // see assertion failures from any subsequent set_concurrency_and_phase() - // calls. - if (_cm->concurrent() && _worker_id == 0) { - // Worker 0 is responsible for clearing the global data structures because - // of an overflow. During STW we should not clear the overflow flag (in - // G1ConcurrentMark::reset_marking_state()) since we rely on it being true when we exit - // method to abort the pause and restart concurrent marking. - _cm->reset_marking_for_restart(); - - log_info(gc, marking)("Concurrent Mark reset for overflow"); - } - - // ...and enter the second barrier. - _cm->enter_second_sync_barrier(_worker_id); - } - // At this point, if we're during the concurrent phase of - // marking, everything has been re-initialized and we're - // ready to restart. - } + handle_abort(is_serial, elapsed_time_ms); } } diff --git a/src/hotspot/share/gc/g1/g1ConcurrentMark.hpp b/src/hotspot/share/gc/g1/g1ConcurrentMark.hpp index b197afc65eefc..fed624df85179 100644 --- a/src/hotspot/share/gc/g1/g1ConcurrentMark.hpp +++ b/src/hotspot/share/gc/g1/g1ConcurrentMark.hpp @@ -810,6 +810,21 @@ class G1CMTask : public TerminatorTerminator { // Makes the limit of the region up-to-date void update_region_limit(); + // Handles the processing of the current region. + void process_current_region(G1CMBitMapClosure& bitmap_closure); + + // Claims a new region if available. + void claim_new_region(); + + // Attempts to steal work from other tasks. + void attempt_stealing(); + + // Handles the termination protocol. + void attempt_termination(bool is_serial); + + // Handles the has_aborted scenario. + void handle_abort(bool is_serial, double elapsed_time_ms); + // Called when either the words scanned or the refs visited limit // has been reached void reached_limit(); From 59fcfae63090f6659a94a9e3dd0705739ec1b074 Mon Sep 17 00:00:00 2001 From: SendaoYan Date: Tue, 19 Nov 2024 15:17:34 +0000 Subject: [PATCH 07/74] 8343129: Disable unstable check of ThreadsListHandle.sanity_vm ThreadList values Reviewed-by: dholmes --- .../gtest/runtime/test_ThreadsListHandle.cpp | 30 ++++++++++++------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/test/hotspot/gtest/runtime/test_ThreadsListHandle.cpp b/test/hotspot/gtest/runtime/test_ThreadsListHandle.cpp index 5caa19fae9537..81d36670c9a82 100644 --- a/test/hotspot/gtest/runtime/test_ThreadsListHandle.cpp +++ b/test/hotspot/gtest/runtime/test_ThreadsListHandle.cpp @@ -171,8 +171,10 @@ TEST_VM(ThreadsListHandle, sanity) { // Verify the current thread refers to tlh2: EXPECT_EQ(ThreadsListHandleTest::get_Thread_threads_hazard_ptr(thr), tlh2.list()) << "thr->_threads_hazard_ptr must match tlh2.list()"; - EXPECT_EQ(tlh1.list(), tlh2.list()) - << "tlh1.list() must match tlh2.list()"; + // Disable unstable check of ThreadsListHandle.sanity_vm ThreadList values, + // until the root cause of test failure(JDK-8315141) has been fixed + // EXPECT_EQ(tlh1.list(), tlh2.list()) + // << "tlh1.list() must match tlh2.list()"; EXPECT_EQ(ThreadsListHandleTest::get_Thread_threads_list_ptr(thr), list_ptr2) << "thr->_threads_list_ptr must match list_ptr2"; EXPECT_NE(list_ptr1, list_ptr2) @@ -291,8 +293,10 @@ TEST_VM(ThreadsListHandle, sanity) { // Verify the current thread refers to tlh2: EXPECT_EQ(ThreadsListHandleTest::get_Thread_threads_hazard_ptr(thr), tlh2.list()) << "thr->_threads_hazard_ptr must match tlh2.list()"; - EXPECT_EQ(tlh1.list(), tlh2.list()) - << "tlh1.list() must match tlh2.list()"; + // Disable unstable check of ThreadsListHandle.sanity_vm ThreadList values, + // until the root cause of test failure(JDK-8315141) has been fixed + // EXPECT_EQ(tlh1.list(), tlh2.list()) + // << "tlh1.list() must match tlh2.list()"; EXPECT_EQ(ThreadsListHandleTest::get_Thread_threads_list_ptr(thr), list_ptr2) << "thr->_threads_list_ptr must match list_ptr2"; EXPECT_NE(list_ptr1, list_ptr2) @@ -339,8 +343,10 @@ TEST_VM(ThreadsListHandle, sanity) { // Verify the current thread refers to tlh3: EXPECT_EQ(ThreadsListHandleTest::get_Thread_threads_hazard_ptr(thr), tlh3.list()) << "thr->_threads_hazard_ptr must match tlh3.list()"; - EXPECT_EQ(tlh1.list(), tlh3.list()) - << "tlh1.list() must match tlh3.list()"; + // Disable unstable check of ThreadsListHandle.sanity_vm ThreadList values, + // until the root cause of test failure(JDK-8315141) has been fixed + // EXPECT_EQ(tlh1.list(), tlh3.list()) + // << "tlh1.list() must match tlh3.list()"; EXPECT_EQ(ThreadsListHandleTest::get_Thread_threads_list_ptr(thr), list_ptr3) << "thr->_threads_list_ptr must match list_ptr3"; EXPECT_NE(list_ptr1, list_ptr3) @@ -523,8 +529,10 @@ TEST_VM(ThreadsListHandle, sanity) { // Verify the current thread refers to tlh2a: EXPECT_EQ(ThreadsListHandleTest::get_Thread_threads_hazard_ptr(thr), tlh2a.list()) << "thr->_threads_hazard_ptr must match tlh2a.list()"; - EXPECT_EQ(tlh1.list(), tlh2a.list()) - << "tlh1.list() must match tlh2a.list()"; + // Disable unstable check of ThreadsListHandle.sanity_vm ThreadList values, + // until the root cause of test failure(JDK-8315141) has been fixed + // EXPECT_EQ(tlh1.list(), tlh2a.list()) + // << "tlh1.list() must match tlh2a.list()"; EXPECT_EQ(ThreadsListHandleTest::get_Thread_threads_list_ptr(thr), list_ptr2a) << "thr->_threads_list_ptr must match list_ptr2a"; EXPECT_NE(list_ptr1, list_ptr2a) @@ -601,8 +609,10 @@ TEST_VM(ThreadsListHandle, sanity) { // Verify the current thread refers to tlh2b: EXPECT_EQ(ThreadsListHandleTest::get_Thread_threads_hazard_ptr(thr), tlh2b.list()) << "thr->_threads_hazard_ptr must match tlh2b.list()"; - EXPECT_EQ(tlh1.list(), tlh2b.list()) - << "tlh1.list() must match tlh2b.list()"; + // Disable unstable check of ThreadsListHandle.sanity_vm ThreadList values, + // until the root cause of test failure(JDK-8315141) has been fixed + // EXPECT_EQ(tlh1.list(), tlh2b.list()) + // << "tlh1.list() must match tlh2b.list()"; EXPECT_EQ(ThreadsListHandleTest::get_Thread_threads_list_ptr(thr), list_ptr2b) << "thr->_threads_list_ptr must match list_ptr2b"; EXPECT_NE(list_ptr1, list_ptr2b) From ded01e4316a46d4c4a74d494db61d03f8591fd67 Mon Sep 17 00:00:00 2001 From: Roger Riggs Date: Tue, 19 Nov 2024 15:21:02 +0000 Subject: [PATCH 08/74] 8344327: SM cleanup in jdk.unsupported ReflectionFactory Reviewed-by: liach, mullan, alanb --- .../sun/reflect/ReflectionFactory.java | 34 ++----------------- 1 file changed, 3 insertions(+), 31 deletions(-) diff --git a/src/jdk.unsupported/share/classes/sun/reflect/ReflectionFactory.java b/src/jdk.unsupported/share/classes/sun/reflect/ReflectionFactory.java index f6f9b3976fc0d..b6c538c507f67 100644 --- a/src/jdk.unsupported/share/classes/sun/reflect/ReflectionFactory.java +++ b/src/jdk.unsupported/share/classes/sun/reflect/ReflectionFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2024, 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 @@ -29,60 +29,32 @@ import java.lang.invoke.MethodHandle; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; -import java.security.AccessController; -import java.security.Permission; -import java.security.PrivilegedAction; /** * ReflectionFactory supports custom serialization. * Its methods support the creation of uninitialized objects, invoking serialization * private methods for readObject, writeObject, readResolve, and writeReplace. - *

- * ReflectionFactory access is restricted, if a security manager is active, - * unless the permission {@code RuntimePermission("reflectionFactoryAccess")} - * is granted. */ public class ReflectionFactory { private static final ReflectionFactory soleInstance = new ReflectionFactory(); - @SuppressWarnings("removal") - private static final jdk.internal.reflect.ReflectionFactory delegate = AccessController.doPrivileged( - new PrivilegedAction() { - public jdk.internal.reflect.ReflectionFactory run() { - return jdk.internal.reflect.ReflectionFactory.getReflectionFactory(); - } - }); + private static final jdk.internal.reflect.ReflectionFactory delegate = + jdk.internal.reflect.ReflectionFactory.getReflectionFactory(); private ReflectionFactory() {} - private static final Permission REFLECTION_FACTORY_ACCESS_PERM - = new RuntimePermission("reflectionFactoryAccess"); - /** * Provides the caller with the capability to instantiate reflective * objects. * - *

First, if there is a security manager, its {@code checkPermission} - * method is called with a {@link java.lang.RuntimePermission} with target - * {@code "reflectionFactoryAccess"}. This may result in a security - * exception. - * *

The returned {@code ReflectionFactory} object should be carefully * guarded by the caller, since it can be used to read and write private * data and invoke private methods, as well as to load unverified bytecodes. * It must never be passed to untrusted code. * * @return the ReflectionFactory - * @throws SecurityException if a security manager exists and its - * {@code checkPermission} method doesn't allow access to - * the RuntimePermission "reflectionFactoryAccess". */ public static ReflectionFactory getReflectionFactory() { - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); - if (security != null) { - security.checkPermission(REFLECTION_FACTORY_ACCESS_PERM); - } return soleInstance; } From dc940ec8afcd3cd12ed3785d547f4cd602f65c15 Mon Sep 17 00:00:00 2001 From: Hamlin Li Date: Tue, 19 Nov 2024 15:59:30 +0000 Subject: [PATCH 09/74] 8344387: RISC-V: C2: Improve encoding of LoadNKlass for compact headers Reviewed-by: fyang, luhenry --- src/hotspot/cpu/riscv/c2_MacroAssembler_riscv.cpp | 10 ---------- src/hotspot/cpu/riscv/c2_MacroAssembler_riscv.hpp | 2 -- src/hotspot/cpu/riscv/riscv.ad | 8 ++++++-- 3 files changed, 6 insertions(+), 14 deletions(-) diff --git a/src/hotspot/cpu/riscv/c2_MacroAssembler_riscv.cpp b/src/hotspot/cpu/riscv/c2_MacroAssembler_riscv.cpp index 7b0316e208fd3..bf553b3577038 100644 --- a/src/hotspot/cpu/riscv/c2_MacroAssembler_riscv.cpp +++ b/src/hotspot/cpu/riscv/c2_MacroAssembler_riscv.cpp @@ -3124,13 +3124,3 @@ void C2_MacroAssembler::extract_fp_v(FloatRegister dst, VectorRegister src, Basi vfmv_f_s(dst, tmp); } } - -void C2_MacroAssembler::load_narrow_klass_compact_c2(Register dst, Address src) { - // The incoming address is pointing into obj-start + klass_offset_in_bytes. We need to extract - // obj-start, so that we can load from the object's mark-word instead. Usually the address - // comes as obj-start in obj and klass_offset_in_bytes in disp. - assert(UseCompactObjectHeaders, "must"); - int offset = oopDesc::mark_offset_in_bytes() - oopDesc::klass_offset_in_bytes(); - ld(dst, Address(src.base(), src.offset() + offset)); - srli(dst, dst, markWord::klass_shift); -} diff --git a/src/hotspot/cpu/riscv/c2_MacroAssembler_riscv.hpp b/src/hotspot/cpu/riscv/c2_MacroAssembler_riscv.hpp index 8f9d9cd2ccd24..8736294e72cf5 100644 --- a/src/hotspot/cpu/riscv/c2_MacroAssembler_riscv.hpp +++ b/src/hotspot/cpu/riscv/c2_MacroAssembler_riscv.hpp @@ -281,6 +281,4 @@ void extract_v(Register dst, VectorRegister src, BasicType bt, int idx, VectorRegister tmp); void extract_fp_v(FloatRegister dst, VectorRegister src, BasicType bt, int idx, VectorRegister tmp); - void load_narrow_klass_compact_c2(Register dst, Address src); - #endif // CPU_RISCV_C2_MACROASSEMBLER_RISCV_HPP diff --git a/src/hotspot/cpu/riscv/riscv.ad b/src/hotspot/cpu/riscv/riscv.ad index b944cc5b4b996..ae8565e1bcf7c 100644 --- a/src/hotspot/cpu/riscv/riscv.ad +++ b/src/hotspot/cpu/riscv/riscv.ad @@ -4814,10 +4814,14 @@ instruct loadNKlassCompactHeaders(iRegNNoSp dst, memory mem) match(Set dst (LoadNKlass mem)); ins_cost(LOAD_COST); - format %{ "load_narrow_klass_compact $dst, $mem\t# compressed class ptr, #@loadNKlassCompactHeaders" %} + format %{ + "lwu $dst, $mem\t# compressed klass ptr, shifted\n\t" + "srli $dst, $dst, markWord::klass_shift_at_offset" + %} ins_encode %{ - __ load_narrow_klass_compact_c2(as_Register($dst$$reg), Address(as_Register($mem$$base), $mem$$disp)); + __ lwu(as_Register($dst$$reg), Address(as_Register($mem$$base), $mem$$disp)); + __ srli(as_Register($dst$$reg), as_Register($dst$$reg), (unsigned) markWord::klass_shift_at_offset); %} ins_pipe(iload_reg_mem); From d4cd27e875ba7d44b0c614d48888340990b94169 Mon Sep 17 00:00:00 2001 From: Coleen Phillimore Date: Tue, 19 Nov 2024 16:13:11 +0000 Subject: [PATCH 10/74] 8344445: MethodCounters don't need a vptr Reviewed-by: kbarrett, dlong --- src/hotspot/share/oops/metadata.hpp | 5 ++--- src/hotspot/share/oops/methodCounters.cpp | 5 ++--- src/hotspot/share/oops/methodCounters.hpp | 18 ++++++++---------- 3 files changed, 12 insertions(+), 16 deletions(-) diff --git a/src/hotspot/share/oops/metadata.hpp b/src/hotspot/share/oops/metadata.hpp index f5aee34c80da7..ff18cef60a7ab 100644 --- a/src/hotspot/share/oops/metadata.hpp +++ b/src/hotspot/share/oops/metadata.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2024, 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 @@ -44,11 +44,10 @@ class Metadata : public MetaspaceObj { virtual bool is_method() const { return false; } virtual bool is_methodData() const { return false; } virtual bool is_constantPool() const { return false; } - virtual bool is_methodCounters() const { return false; } virtual int size() const = 0; virtual MetaspaceObj::Type type() const = 0; virtual const char* internal_name() const = 0; - virtual void metaspace_pointers_do(MetaspaceClosure* iter) {} + virtual void metaspace_pointers_do(MetaspaceClosure* iter) = 0; void print() const; void print_value() const; diff --git a/src/hotspot/share/oops/methodCounters.cpp b/src/hotspot/share/oops/methodCounters.cpp index 00096c5012cbd..93fd7e65c6bcd 100644 --- a/src/hotspot/share/oops/methodCounters.cpp +++ b/src/hotspot/share/oops/methodCounters.cpp @@ -50,12 +50,12 @@ MethodCounters::MethodCounters(const methodHandle& mh) : MethodCounters* MethodCounters::allocate_no_exception(const methodHandle& mh) { ClassLoaderData* loader_data = mh->method_holder()->class_loader_data(); - return new(loader_data, method_counters_size(), MetaspaceObj::MethodCountersType) MethodCounters(mh); + return new(loader_data, size(), MetaspaceObj::MethodCountersType) MethodCounters(mh); } MethodCounters* MethodCounters::allocate_with_exception(const methodHandle& mh, TRAPS) { ClassLoaderData* loader_data = mh->method_holder()->class_loader_data(); - return new(loader_data, method_counters_size(), MetaspaceObj::MethodCountersType, THREAD) MethodCounters(mh); + return new(loader_data, size(), MetaspaceObj::MethodCountersType, THREAD) MethodCounters(mh); } void MethodCounters::clear_counters() { @@ -70,7 +70,6 @@ void MethodCounters::clear_counters() { } void MethodCounters::print_value_on(outputStream* st) const { - assert(is_methodCounters(), "must be methodCounters"); st->print("method counters"); print_address_on(st); } diff --git a/src/hotspot/share/oops/methodCounters.hpp b/src/hotspot/share/oops/methodCounters.hpp index 80cfb159b50ce..bdf033a46a855 100644 --- a/src/hotspot/share/oops/methodCounters.hpp +++ b/src/hotspot/share/oops/methodCounters.hpp @@ -30,7 +30,7 @@ #include "interpreter/invocationCounter.hpp" #include "utilities/align.hpp" -class MethodCounters : public Metadata { +class MethodCounters : public MetaspaceObj { friend class VMStructs; friend class JVMCIVMStructs; private: @@ -52,19 +52,18 @@ class MethodCounters : public Metadata { MethodCounters(const methodHandle& mh); public: - virtual bool is_methodCounters() const { return true; } - static MethodCounters* allocate_no_exception(const methodHandle& mh); static MethodCounters* allocate_with_exception(const methodHandle& mh, TRAPS); + DEBUG_ONLY(bool on_stack() { return false; }) void deallocate_contents(ClassLoaderData* loader_data) {} - static int method_counters_size() { + void metaspace_pointers_do(MetaspaceClosure* it) { return; } + + static int size() { return align_up((int)sizeof(MethodCounters), wordSize) / wordSize; } - virtual int size() const { - return method_counters_size(); - } + MetaspaceObj::Type type() const { return MethodCountersType; } void clear_counters(); @@ -128,8 +127,7 @@ class MethodCounters : public Metadata { return byte_offset_of(MethodCounters, _backedge_mask); } - virtual const char* internal_name() const { return "{method counters}"; } - virtual void print_value_on(outputStream* st) const; - + const char* internal_name() const { return "{method counters}"; } + void print_value_on(outputStream* st) const; }; #endif // SHARE_OOPS_METHODCOUNTERS_HPP From 48223f7b9c6fbaf4e6751a5b41ea9e9046a48f91 Mon Sep 17 00:00:00 2001 From: Alan Bateman Date: Tue, 19 Nov 2024 16:37:43 +0000 Subject: [PATCH 11/74] 8344143: Test jdk/java/lang/Thread/virtual/stress/GetStackTraceALotWhenPinned.java timed out on macosx-x64 Reviewed-by: pchilanomate --- .../stress/GetStackTraceALotWhenBlocking.java | 18 +++++++++++++----- .../stress/GetStackTraceALotWhenPinned.java | 17 +++++++++++------ 2 files changed, 24 insertions(+), 11 deletions(-) diff --git a/test/jdk/java/lang/Thread/virtual/stress/GetStackTraceALotWhenBlocking.java b/test/jdk/java/lang/Thread/virtual/stress/GetStackTraceALotWhenBlocking.java index 5e15ea083e492..b68496bc7db6f 100644 --- a/test/jdk/java/lang/Thread/virtual/stress/GetStackTraceALotWhenBlocking.java +++ b/test/jdk/java/lang/Thread/virtual/stress/GetStackTraceALotWhenBlocking.java @@ -28,7 +28,7 @@ * @requires vm.debug != true * @modules jdk.management * @library /test/lib - * @run main/othervm GetStackTraceALotWhenBlocking 500000 + * @run main/othervm/timeout=300 GetStackTraceALotWhenBlocking 100000 */ /* @@ -68,16 +68,24 @@ public static void main(String[] args) throws Exception { var thread1 = Thread.ofVirtual().start(task); var thread2 = Thread.ofVirtual().start(task); + long lastTime = System.nanoTime(); try { for (int i = 1; i <= iterations; i++) { - if ((i % 10_000) == 0) { - System.out.format("%s => %d of %d%n", Instant.now(), i, iterations); - } - thread1.getStackTrace(); pause(); thread2.getStackTrace(); pause(); + + long currentTime = System.nanoTime(); + if (i == iterations || ((currentTime - lastTime) > 1_000_000_000L)) { + System.out.format("%s => %d of %d%n", Instant.now(), i, iterations); + lastTime = currentTime; + } + + if (Thread.currentThread().isInterrupted()) { + // fail quickly if interrupted by jtreg + throw new RuntimeException("interrupted"); + } } } finally { done.set(true); diff --git a/test/jdk/java/lang/Thread/virtual/stress/GetStackTraceALotWhenPinned.java b/test/jdk/java/lang/Thread/virtual/stress/GetStackTraceALotWhenPinned.java index 260446a1e3de5..9d9d3eddce108 100644 --- a/test/jdk/java/lang/Thread/virtual/stress/GetStackTraceALotWhenPinned.java +++ b/test/jdk/java/lang/Thread/virtual/stress/GetStackTraceALotWhenPinned.java @@ -28,7 +28,7 @@ * @requires vm.debug != true * @modules jdk.management * @library /test/lib - * @run main/othervm --enable-native-access=ALL-UNNAMED GetStackTraceALotWhenPinned 500000 + * @run main/othervm/timeout=300 --enable-native-access=ALL-UNNAMED GetStackTraceALotWhenPinned 100000 */ /* @@ -36,7 +36,7 @@ * @requires vm.debug == true * @modules jdk.management * @library /test/lib - * @run main/othervm/timeout=300 --enable-native-access=ALL-UNNAMED GetStackTraceALotWhenPinned 200000 + * @run main/othervm/timeout=300 --enable-native-access=ALL-UNNAMED GetStackTraceALotWhenPinned 50000 */ import java.time.Instant; @@ -78,7 +78,7 @@ public static void main(String[] args) throws Exception { } }); - long lastTimestamp = System.currentTimeMillis(); + long lastTime = System.nanoTime(); for (int i = 1; i <= iterations; i++) { // wait for virtual thread to arrive barrier.await(); @@ -86,10 +86,15 @@ public static void main(String[] args) throws Exception { thread.getStackTrace(); LockSupport.unpark(thread); - long currentTime = System.currentTimeMillis(); - if (i == iterations || ((currentTime - lastTimestamp) > 500)) { + long currentTime = System.nanoTime(); + if (i == iterations || ((currentTime - lastTime) > 1_000_000_000L)) { System.out.format("%s => %d of %d%n", Instant.now(), i, iterations); - lastTimestamp = currentTime; + lastTime = currentTime; + } + + if (Thread.currentThread().isInterrupted()) { + // fail quickly if interrupted by jtreg + throw new RuntimeException("interrupted"); } } } From 7f672eb266b76a9310dcf108f72adf2469e63dee Mon Sep 17 00:00:00 2001 From: Alexey Semenyuk Date: Tue, 19 Nov 2024 16:56:11 +0000 Subject: [PATCH 12/74] 8344550: Compilation error of jpackage test JPackageStringBundle.java source Reviewed-by: rriggs --- .../helpers/jdk/jpackage/test/JPackageStringBundle.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/JPackageStringBundle.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/JPackageStringBundle.java index 565822d4504c0..4757f54fdfd2c 100644 --- a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/JPackageStringBundle.java +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/JPackageStringBundle.java @@ -26,6 +26,7 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.text.MessageFormat; +import static jdk.jpackage.internal.util.function.ExceptionBox.rethrowUnchecked; public enum JPackageStringBundle { @@ -39,7 +40,7 @@ public enum JPackageStringBundle { i18nClass_getString = i18nClass.getDeclaredMethod("getString", String.class); i18nClass_getString.setAccessible(true); } catch (ClassNotFoundException|NoSuchMethodException ex) { - throw Functional.rethrowUnchecked(ex); + throw rethrowUnchecked(ex); } } @@ -50,7 +51,7 @@ private String getString(String key) { try { return (String)i18nClass_getString.invoke(i18nClass, key); } catch (IllegalAccessException|InvocationTargetException ex) { - throw Functional.rethrowUnchecked(ex); + throw rethrowUnchecked(ex); } } From 78602be1fe6803503d4382cc9797ec70ee49eba6 Mon Sep 17 00:00:00 2001 From: Andrey Turbanov Date: Tue, 19 Nov 2024 16:59:06 +0000 Subject: [PATCH 13/74] 8344024: Unnecessary Hashtable usage in RSAPSSSignature.DIGEST_LENGTHS Reviewed-by: valeriep --- .../sun/security/rsa/RSAPSSSignature.java | 32 +++++++++---------- 1 file changed, 15 insertions(+), 17 deletions(-) diff --git a/src/java.base/share/classes/sun/security/rsa/RSAPSSSignature.java b/src/java.base/share/classes/sun/security/rsa/RSAPSSSignature.java index f15b058014a8f..6ccb3823e0a3a 100644 --- a/src/java.base/share/classes/sun/security/rsa/RSAPSSSignature.java +++ b/src/java.base/share/classes/sun/security/rsa/RSAPSSSignature.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, 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 @@ -35,7 +35,7 @@ import java.security.interfaces.*; import java.util.Arrays; -import java.util.Hashtable; +import java.util.Map; import sun.security.util.*; import sun.security.jca.JCAUtil; @@ -81,21 +81,19 @@ private boolean isDigestEqual(String stdAlg, String givenAlg) { private static final byte[] EIGHT_BYTES_OF_ZEROS = new byte[8]; - private static final Hashtable DIGEST_LENGTHS = - new Hashtable<>(); - static { - DIGEST_LENGTHS.put(KnownOIDs.SHA_1, 20); - DIGEST_LENGTHS.put(KnownOIDs.SHA_224, 28); - DIGEST_LENGTHS.put(KnownOIDs.SHA_256, 32); - DIGEST_LENGTHS.put(KnownOIDs.SHA_384, 48); - DIGEST_LENGTHS.put(KnownOIDs.SHA_512, 64); - DIGEST_LENGTHS.put(KnownOIDs.SHA_512$224, 28); - DIGEST_LENGTHS.put(KnownOIDs.SHA_512$256, 32); - DIGEST_LENGTHS.put(KnownOIDs.SHA3_224, 28); - DIGEST_LENGTHS.put(KnownOIDs.SHA3_256, 32); - DIGEST_LENGTHS.put(KnownOIDs.SHA3_384, 48); - DIGEST_LENGTHS.put(KnownOIDs.SHA3_512, 64); - } + private static final Map DIGEST_LENGTHS = Map.ofEntries( + Map.entry(KnownOIDs.SHA_1, 20), + Map.entry(KnownOIDs.SHA_224, 28), + Map.entry(KnownOIDs.SHA_256, 32), + Map.entry(KnownOIDs.SHA_384, 48), + Map.entry(KnownOIDs.SHA_512, 64), + Map.entry(KnownOIDs.SHA_512$224, 28), + Map.entry(KnownOIDs.SHA_512$256, 32), + Map.entry(KnownOIDs.SHA3_224, 28), + Map.entry(KnownOIDs.SHA3_256, 32), + Map.entry(KnownOIDs.SHA3_384, 48), + Map.entry(KnownOIDs.SHA3_512, 64) + ); // message digest implementation we use for hashing the data private MessageDigest md; From 47ebf8d868b2e15b943a227ad3cf2ee12eed10f6 Mon Sep 17 00:00:00 2001 From: "naveen.n.narayanan" <“naveen.n.narayanan@oracle.com”> Date: Tue, 19 Nov 2024 17:15:24 +0000 Subject: [PATCH 14/74] 8342098: Write a test to compare the images Reviewed-by: aivanov, abhiscxk --- .../awt/Robot/ScreenCaptureRobotTest.java | 166 ++++++++++++++++++ 1 file changed, 166 insertions(+) create mode 100644 test/jdk/java/awt/Robot/ScreenCaptureRobotTest.java diff --git a/test/jdk/java/awt/Robot/ScreenCaptureRobotTest.java b/test/jdk/java/awt/Robot/ScreenCaptureRobotTest.java new file mode 100644 index 0000000000000..944636ebf2aa8 --- /dev/null +++ b/test/jdk/java/awt/Robot/ScreenCaptureRobotTest.java @@ -0,0 +1,166 @@ +/* + * Copyright (c) 2000, 2024, 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. + * + * 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. + */ + +import java.awt.BorderLayout; +import java.awt.Canvas; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.EventQueue; +import java.awt.Font; +import java.awt.Frame; +import java.awt.Graphics; +import java.awt.GraphicsEnvironment; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.Robot; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; +import javax.imageio.ImageIO; + +/* + * @test + * @key headful + * @bug 8342098 + * @summary Verify that the image captured from the screen using a Robot + * and the source image are same. + * @run main/othervm -Dsun.java2d.uiScale=1 ScreenCaptureRobotTest + */ +public class ScreenCaptureRobotTest { + + private static final int IMAGE_WIDTH = 200; + private static final int IMAGE_HEIGHT = 100; + private static final int OFFSET = 10; + + private static Frame frame; + private static Canvas canvas; + + private static BufferedImage realImage; + + private static volatile Point point; + + public static void main(String[] args) throws Exception { + try { + EventQueue.invokeAndWait(ScreenCaptureRobotTest::initializeGUI); + doTest(); + } finally { + EventQueue.invokeAndWait(ScreenCaptureRobotTest::disposeFrame); + } + } + + private static void initializeGUI() { + frame = new Frame("ScreenCaptureRobotTest Frame"); + realImage = GraphicsEnvironment.getLocalGraphicsEnvironment() + .getDefaultScreenDevice() + .getDefaultConfiguration() + .createCompatibleImage(IMAGE_WIDTH, IMAGE_HEIGHT); + + Graphics g = realImage.createGraphics(); + g.setColor(Color.YELLOW); + g.fillRect(0, 0, IMAGE_WIDTH, IMAGE_HEIGHT); + g.setColor(Color.RED); + g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 20)); + g.drawString("Capture This", 10, 40); + g.dispose(); + + canvas = new ImageCanvas(); + canvas.setBackground(Color.YELLOW); + canvas.setPreferredSize(new Dimension(IMAGE_WIDTH + (OFFSET * 2), + IMAGE_HEIGHT + (OFFSET * 2))); + frame.setLayout(new BorderLayout()); + frame.add(canvas); + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + + private static void doTest() throws Exception { + Robot robot = new Robot(); + robot.waitForIdle(); + robot.delay(500); + + EventQueue.invokeAndWait(() -> point = canvas.getLocationOnScreen()); + + Rectangle rect = new Rectangle(point.x + OFFSET, point.y + OFFSET, + IMAGE_WIDTH, IMAGE_HEIGHT); + + BufferedImage capturedImage = robot.createScreenCapture(rect); + + if (!compareImages(capturedImage, realImage)) { + String errorMessage = "FAIL : Captured Image is different from " + + "the real image"; + saveImage(capturedImage, "CapturedImage.png"); + saveImage(realImage, "RealImage.png"); + throw new RuntimeException(errorMessage); + } + } + + private static boolean compareImages(BufferedImage capturedImg, + BufferedImage realImg) { + int capturedPixel; + int realPixel; + int imgWidth = capturedImg.getWidth(); + int imgHeight = capturedImg.getHeight(); + + if (imgWidth != IMAGE_WIDTH || imgHeight != IMAGE_HEIGHT) { + System.out.println("Captured and real images are different in size"); + return false; + } + + for (int i = 0; i < imgWidth; i++) { + for (int j = 0; j < imgHeight; j++) { + capturedPixel = capturedImg.getRGB(i, j); + realPixel = realImg.getRGB(i, j); + if (capturedPixel != realPixel) { + System.out.println("Captured pixel (" + + Integer.toHexString(capturedPixel) + ") at " + + "(" + i + ", " + j + ") is not equal to real pixel (" + + Integer.toHexString(realPixel) + ")"); + return false; + } + } + } + return true; + } + + private static class ImageCanvas extends Canvas { + @Override + public void paint(Graphics g) { + g.drawImage(realImage, OFFSET, OFFSET, this); + } + } + + private static void saveImage(BufferedImage image, String fileName) { + try { + ImageIO.write(image, "png", new File(fileName)); + } catch (IOException ignored) { + System.err.println(ignored.getMessage()); + } + } + + private static void disposeFrame() { + if (frame != null) { + frame.dispose(); + } + } +} From 02ec8ca2d6ccbabc6740b60be8fe1f8b2110f0ca Mon Sep 17 00:00:00 2001 From: Alexey Ivanov Date: Tue, 19 Nov 2024 17:15:46 +0000 Subject: [PATCH 15/74] 8342508: Use latch in BasicMenuUI/bug4983388.java instead of delay Reviewed-by: azvegint, abhiscxk, serb --- .../basic/BasicMenuUI/4983388/bug4983388.java | 57 +++++++++++-------- 1 file changed, 33 insertions(+), 24 deletions(-) diff --git a/test/jdk/javax/swing/plaf/basic/BasicMenuUI/4983388/bug4983388.java b/test/jdk/javax/swing/plaf/basic/BasicMenuUI/4983388/bug4983388.java index 18f78d88f52e6..e495c929891d9 100644 --- a/test/jdk/javax/swing/plaf/basic/BasicMenuUI/4983388/bug4983388.java +++ b/test/jdk/javax/swing/plaf/basic/BasicMenuUI/4983388/bug4983388.java @@ -26,28 +26,41 @@ * @key headful * @bug 4983388 8015600 * @summary shortcuts on menus do not work on JDS - * @author Oleg Mokhovikov * @library ../../../../regtesthelpers * @build Util * @run main bug4983388 */ -import java.awt.*; -import javax.swing.*; -import javax.swing.event.MenuListener; -import javax.swing.event.MenuEvent; +import java.awt.Robot; import java.awt.event.KeyEvent; +import java.util.concurrent.CountDownLatch; + +import javax.swing.JFrame; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; +import javax.swing.UnsupportedLookAndFeelException; +import javax.swing.event.MenuEvent; +import javax.swing.event.MenuListener; + +import static java.util.concurrent.TimeUnit.SECONDS; public class bug4983388 { - static volatile boolean bMenuSelected = false; static JFrame frame; + private static final CountDownLatch menuSelected = new CountDownLatch(1); + private static class TestMenuListener implements MenuListener { + @Override public void menuCanceled(MenuEvent e) {} + @Override public void menuDeselected(MenuEvent e) {} + + @Override public void menuSelected(MenuEvent e) { System.out.println("menuSelected"); - bMenuSelected = true; + menuSelected.countDown(); } } @@ -56,28 +69,24 @@ private static void createAndShowGUI() { JMenu menu = new JMenu("File"); menu.setMnemonic('F'); menuBar.add(menu); - frame = new JFrame(); + menu.addMenuListener(new TestMenuListener()); + + frame = new JFrame("bug4983388"); frame.setJMenuBar(menuBar); frame.setLocationRelativeTo(null); - frame.pack(); + frame.setSize(250, 100); frame.setVisible(true); - MenuListener listener = new TestMenuListener(); - menu.addMenuListener(listener); } public static void main(String[] args) throws Exception { - try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel"); } catch (UnsupportedLookAndFeelException | ClassNotFoundException ex) { - System.err.println("GTKLookAndFeel is not supported on this platform. Using defailt LaF for this platform."); + System.err.println("GTKLookAndFeel is not supported on this platform. " + + "Using default LaF for this platform."); } - SwingUtilities.invokeAndWait(new Runnable() { - public void run() { - createAndShowGUI(); - } - }); + SwingUtilities.invokeAndWait(bug4983388::createAndShowGUI); Robot robot = new Robot(); robot.setAutoDelay(50); @@ -85,13 +94,13 @@ public void run() { robot.delay(500); Util.hitMnemonics(robot, KeyEvent.VK_F); - robot.waitForIdle(); - robot.delay(500); - - SwingUtilities.invokeAndWait(() -> frame.dispose()); - if (!bMenuSelected) { - throw new RuntimeException("shortcuts on menus do not work"); + try { + if (!menuSelected.await(1, SECONDS)) { + throw new RuntimeException("shortcuts on menus do not work"); + } + } finally { + SwingUtilities.invokeAndWait(frame::dispose); } } } From 087a07b5ededc6381d3d12cad045d3522434709e Mon Sep 17 00:00:00 2001 From: Archie Cobbs Date: Tue, 19 Nov 2024 17:43:48 +0000 Subject: [PATCH 16/74] 8343479: Remove unnecessary @SuppressWarnings annotations (hotspot) Reviewed-by: chagedorn, epeter --- .../share/classes/jdk/vm/ci/hotspot/HotSpotJVMCIRuntime.java | 3 --- .../jdk/vm/ci/hotspot/IndirectHotSpotObjectConstantImpl.java | 3 +-- .../share/classes/jdk/vm/ci/meta/AnnotationData.java | 4 +--- 3 files changed, 2 insertions(+), 8 deletions(-) diff --git a/src/jdk.internal.vm.ci/share/classes/jdk/vm/ci/hotspot/HotSpotJVMCIRuntime.java b/src/jdk.internal.vm.ci/share/classes/jdk/vm/ci/hotspot/HotSpotJVMCIRuntime.java index 3fd92f8dee5df..616b5a23f64e2 100644 --- a/src/jdk.internal.vm.ci/share/classes/jdk/vm/ci/hotspot/HotSpotJVMCIRuntime.java +++ b/src/jdk.internal.vm.ci/share/classes/jdk/vm/ci/hotspot/HotSpotJVMCIRuntime.java @@ -959,7 +959,6 @@ public Map, JVMCIBackend> getJVMCIBackends() { return Collections.unmodifiableMap(backends); } - @SuppressWarnings("try") @VMEntryPoint private HotSpotCompilationRequestResult compileMethod(HotSpotResolvedJavaMethod method, int entryBCI, long compileState, int id) { HotSpotCompilationRequest request = new HotSpotCompilationRequest(method, entryBCI, compileState, id); @@ -981,13 +980,11 @@ private HotSpotCompilationRequestResult compileMethod(HotSpotResolvedJavaMethod return hsResult; } - @SuppressWarnings("try") @VMEntryPoint private boolean isGCSupported(int gcIdentifier) { return getCompiler().isGCSupported(gcIdentifier); } - @SuppressWarnings("try") @VMEntryPoint private boolean isIntrinsicSupported(int intrinsicIdentifier) { return getCompiler().isIntrinsicSupported(intrinsicIdentifier); diff --git a/src/jdk.internal.vm.ci/share/classes/jdk/vm/ci/hotspot/IndirectHotSpotObjectConstantImpl.java b/src/jdk.internal.vm.ci/share/classes/jdk/vm/ci/hotspot/IndirectHotSpotObjectConstantImpl.java index fe268e9047662..2b8f717840e27 100644 --- a/src/jdk.internal.vm.ci/share/classes/jdk/vm/ci/hotspot/IndirectHotSpotObjectConstantImpl.java +++ b/src/jdk.internal.vm.ci/share/classes/jdk/vm/ci/hotspot/IndirectHotSpotObjectConstantImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, 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 @@ -70,7 +70,6 @@ private static class Audit { */ private Object rawAudit; - @SuppressWarnings("serial") @VMEntryPoint private IndirectHotSpotObjectConstantImpl(long objectHandle, boolean compressed, boolean skipRegister) { super(compressed); diff --git a/src/jdk.internal.vm.ci/share/classes/jdk/vm/ci/meta/AnnotationData.java b/src/jdk.internal.vm.ci/share/classes/jdk/vm/ci/meta/AnnotationData.java index 17b6b714ba4eb..76edb8c83a77e 100644 --- a/src/jdk.internal.vm.ci/share/classes/jdk/vm/ci/meta/AnnotationData.java +++ b/src/jdk.internal.vm.ci/share/classes/jdk/vm/ci/meta/AnnotationData.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2024, 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 @@ -69,7 +69,6 @@ public final class AnnotationData { * @throws NullPointerException if any of the above parameters is null or any entry in * {@code elements} is null */ - @SuppressWarnings({"rawtypes", "unchecked"}) public AnnotationData(JavaType type, Map.Entry[] elements) { this.type = Objects.requireNonNull(type); for (Map.Entry e : elements) { @@ -125,7 +124,6 @@ public JavaType getAnnotationType() { * there was an error parsing or creating the element value */ // @formatter:on - @SuppressWarnings("unchecked") public V get(String name, Class elementType) { Object val = elements.get(name); if (val == null) { From bb7a8403ba1b32b2d97c0bd3ec78dac1832f5289 Mon Sep 17 00:00:00 2001 From: Renjith Kannath Pariyangad Date: Tue, 19 Nov 2024 18:19:28 +0000 Subject: [PATCH 17/74] 8342541: Exclude List/KeyEventsTest/KeyEventsTest.java from running on macOS Reviewed-by: aivanov, prr --- .../awt/List/KeyEventsTest/KeyEventsTest.java | 30 ++++++++----------- 1 file changed, 12 insertions(+), 18 deletions(-) diff --git a/test/jdk/java/awt/List/KeyEventsTest/KeyEventsTest.java b/test/jdk/java/awt/List/KeyEventsTest/KeyEventsTest.java index 16fbccdafd16a..919ea72a49490 100644 --- a/test/jdk/java/awt/List/KeyEventsTest/KeyEventsTest.java +++ b/test/jdk/java/awt/List/KeyEventsTest/KeyEventsTest.java @@ -21,17 +21,6 @@ * questions. */ -/* - @test - @key headful - @bug 6190768 6190778 - @summary Tests that triggering events on AWT list by pressing CTRL + HOME, - CTRL + END, PG-UP, PG-DOWN similar Motif behavior - @library /test/lib - @build jdk.test.lib.Platform - @run main KeyEventsTest -*/ - import java.awt.BorderLayout; import java.awt.EventQueue; import java.awt.KeyboardFocusManager; @@ -50,6 +39,17 @@ import jdk.test.lib.Platform; +/* + * @test + * @key headful + * @bug 6190768 6190778 + * @requires os.family != "mac" + * @summary Tests that triggering events on AWT list by pressing CTRL + HOME, + * CTRL + END, PG-UP, PG-DOWN similar Motif behavior + * @library /test/lib + * @build jdk.test.lib.Platform + * @run main KeyEventsTest + */ public class KeyEventsTest { TestState currentState; final Object LOCK = new Object(); @@ -261,13 +261,7 @@ private void test(TestState currentState) throws Exception { private void doTest() throws Exception { - boolean isWin = false; - if (Platform.isWindows()) { - isWin = true; - } else if (Platform.isOSX()) { - System.out.println("Not for OS X"); - return; - } + boolean isWin = Platform.isWindows(); System.out.println("multiple? selectedMoved? ?scrollMoved keyID? template? action?"); test(new TestState(false, false, false, KeyEvent.VK_PAGE_UP, isWin?false:false)); From 93e889b48cb6eb6872201a28ee19d8fd17c5d821 Mon Sep 17 00:00:00 2001 From: Larry Cable Date: Tue, 19 Nov 2024 18:45:45 +0000 Subject: [PATCH 18/74] 8342449: reimplement: JDK-8327114 Attach in Linux may have wrong behavior when pid == ns_pid Reviewed-by: kevinw --- .../sun/tools/attach/VirtualMachineImpl.java | 203 +++++++++--------- 1 file changed, 104 insertions(+), 99 deletions(-) diff --git a/src/jdk.attach/linux/classes/sun/tools/attach/VirtualMachineImpl.java b/src/jdk.attach/linux/classes/sun/tools/attach/VirtualMachineImpl.java index 35ce808c18756..69cd4dcdb99b3 100644 --- a/src/jdk.attach/linux/classes/sun/tools/attach/VirtualMachineImpl.java +++ b/src/jdk.attach/linux/classes/sun/tools/attach/VirtualMachineImpl.java @@ -34,7 +34,8 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import java.util.Optional; + +import java.util.regex.Pattern; import static java.nio.charset.StandardCharsets.UTF_8; @@ -51,26 +52,9 @@ public class VirtualMachineImpl extends HotSpotVirtualMachine { private static final Path TMPDIR = Path.of("/tmp"); private static final Path PROC = Path.of("/proc"); - private static final Path NS_MNT = Path.of("ns/mnt"); - private static final Path NS_PID = Path.of("ns/pid"); - private static final Path SELF = PROC.resolve("self"); private static final Path STATUS = Path.of("status"); private static final Path ROOT_TMP = Path.of("root/tmp"); - private static final Optional SELF_MNT_NS; - - static { - Path nsPath = null; - - try { - nsPath = Files.readSymbolicLink(SELF.resolve(NS_MNT)); - } catch (IOException _) { - // do nothing - } finally { - SELF_MNT_NS = Optional.ofNullable(nsPath); - } - } - String socket_path; /** @@ -97,13 +81,16 @@ public class VirtualMachineImpl extends HotSpotVirtualMachine { if (!socket_file.exists()) { // Keep canonical version of File, to delete, in case target process ends and /proc link has gone: File f = createAttachFile(pid, ns_pid).getCanonicalFile(); + + boolean timedout = false; + try { - sendQuitTo(pid); + checkCatchesAndSendQuitTo(pid, false); // give the target VM time to start the attach mechanism final int delay_step = 100; final long timeout = attachTimeout(); - long time_spend = 0; + long time_spent = 0; long delay = 0; do { // Increase timeout on each attempt to reduce polling @@ -112,18 +99,19 @@ public class VirtualMachineImpl extends HotSpotVirtualMachine { Thread.sleep(delay); } catch (InterruptedException x) { } - time_spend += delay; - if (time_spend > timeout/2 && !socket_file.exists()) { + timedout = (time_spent += delay) > timeout; + + if (time_spent > timeout/2 && !socket_file.exists()) { // Send QUIT again to give target VM the last chance to react - sendQuitTo(pid); + checkCatchesAndSendQuitTo(pid, !timedout); } - } while (time_spend <= timeout && !socket_file.exists()); + } while (!timedout && !socket_file.exists()); + if (!socket_file.exists()) { throw new AttachNotSupportedException( String.format("Unable to open socket file %s: " + "target process %d doesn't respond within %dms " + - "or HotSpot VM not loaded", socket_path, pid, - time_spend)); + "or HotSpot VM not loaded", socket_path, pid, time_spent)); } } finally { f.delete(); @@ -257,79 +245,32 @@ private File createAttachFile(long pid, long ns_pid) throws AttachNotSupportedEx } private String findTargetProcessTmpDirectory(long pid, long ns_pid) throws AttachNotSupportedException, IOException { - // We need to handle at least 4 different cases: - // 1. Caller and target processes share PID namespace and root filesystem (host to host or container to - // container with both /tmp mounted between containers). - // 2. Caller and target processes share PID namespace and root filesystem but the target process has elevated - // privileges (host to host). - // 3. Caller and target processes share PID namespace but NOT root filesystem (container to container). - // 4. Caller and target processes share neither PID namespace nor root filesystem (host to container). - - Optional target = ProcessHandle.of(pid); - Optional ph = target; - long nsPid = ns_pid; - Optional prevPidNS = Optional.empty(); - - while (ph.isPresent()) { - final var curPid = ph.get().pid(); - final var procPidPath = PROC.resolve(Long.toString(curPid)); - Optional targetMountNS = Optional.empty(); - - try { - // attempt to read the target's mnt ns id - targetMountNS = Optional.ofNullable(Files.readSymbolicLink(procPidPath.resolve(NS_MNT))); - } catch (IOException _) { - // if we fail to read the target's mnt ns id then we either don't have access or it no longer exists! - if (!Files.exists(procPidPath)) { - throw new IOException(String.format("unable to attach, %s non-existent! process: %d terminated", procPidPath, pid)); - } - // the process still exists, but we don't have privileges to read its procfs - } - - final var sameMountNS = SELF_MNT_NS.isPresent() && SELF_MNT_NS.equals(targetMountNS); - - if (sameMountNS) { - return TMPDIR.toString(); // we share TMPDIR in common! - } else { - // we could not read the target's mnt ns - final var procPidRootTmp = procPidPath.resolve(ROOT_TMP); - if (Files.isReadable(procPidRootTmp)) { - return procPidRootTmp.toString(); // not in the same mnt ns but tmp is accessible via /proc - } - } - - // let's attempt to obtain the pid ns, best efforts to avoid crossing pid ns boundaries (as with a container) - Optional curPidNS = Optional.empty(); - - try { - // attempt to read the target's pid ns id - curPidNS = Optional.ofNullable(Files.readSymbolicLink(procPidPath.resolve(NS_PID))); - } catch (IOException _) { - // if we fail to read the target's pid ns id then we either don't have access or it no longer exists! - if (!Files.exists(procPidPath)) { - throw new IOException(String.format("unable to attach, %s non-existent! process: %d terminated", procPidPath, pid)); - } - // the process still exists, but we don't have privileges to read its procfs - } - - // recurse "up" the process hierarchy if appropriate. PID 1 cannot have a parent in the same namespace - final var havePidNSes = prevPidNS.isPresent() && curPidNS.isPresent(); - final var ppid = ph.get().parent(); - - if (ppid.isPresent() && (havePidNSes && curPidNS.equals(prevPidNS)) || (!havePidNSes && nsPid > 1)) { - ph = ppid; - nsPid = getNamespacePid(ph.get().pid()); // get the ns pid of the parent - prevPidNS = curPidNS; - } else { - ph = Optional.empty(); - } - } - - if (target.orElseThrow(AttachNotSupportedException::new).isAlive()) { - return TMPDIR.toString(); // fallback... - } else { - throw new IOException(String.format("unable to attach, process: %d terminated", pid)); - } + final var procPidRoot = PROC.resolve(Long.toString(pid)).resolve(ROOT_TMP); + + /* We need to handle at least 4 different cases: + * 1. Caller and target processes share PID namespace and root filesystem (host to host or container to + * container with both /tmp mounted between containers). + * 2. Caller and target processes share PID namespace and root filesystem but the target process has elevated + * privileges (host to host). + * 3. Caller and target processes share PID namespace but NOT root filesystem (container to container). + * 4. Caller and target processes share neither PID namespace nor root filesystem (host to container) + * + * if target is elevated, we cant use /proc//... so we have to fallback to /tmp, but that may not be shared + * with the target/attachee process, we can try, except in the case where the ns_pid also exists in this pid ns + * which is ambiguous, if we share /tmp with the intended target, the attach will succeed, if we do not, + * then we will potentially attempt to attach to some arbitrary process with the same pid (in this pid ns) + * as that of the intended target (in its * pid ns). + * + * so in that case we should prehaps throw - or risk sending SIGQUIT to some arbitrary process... which could kill it + * + * however we can also check the target pid's signal masks to see if it catches SIGQUIT and only do so if in + * fact it does ... this reduces the risk of killing an innocent process in the current ns as opposed to + * attaching to the actual target JVM ... c.f: checkCatchesAndSendQuitTo() below. + * + * note that if pid == ns_pid we are in a shared pid ns with the target and may (potentially) share /tmp + */ + + return (Files.isWritable(procPidRoot) ? procPidRoot : TMPDIR).toString(); } /* @@ -378,6 +319,70 @@ private long getNamespacePid(long pid) throws AttachNotSupportedException, IOExc } } + private static final String FIELD = "field"; + private static final String MASK = "mask"; + + private static final Pattern SIGNAL_MASK_PATTERN = Pattern.compile("(?<" + FIELD + ">Sig\\p{Alpha}{3}):\\s+(?<" + MASK + ">\\p{XDigit}{16}).*"); + + private static final long SIGQUIT = 0b100; // mask bit for SIGQUIT + + private static boolean checkCatchesAndSendQuitTo(int pid, boolean throwIfNotReady) throws AttachNotSupportedException, IOException { + var quitIgn = false; + var quitBlk = false; + var quitCgt = false; + + final var procPid = PROC.resolve(Integer.toString(pid)); + + var readBlk = false; + var readIgn = false; + var readCgt = false; + + + if (!Files.exists(procPid)) throw new IOException("non existent JVM pid: " + pid); + + for (var line : Files.readAllLines(procPid.resolve("status"))) { + + if (!line.startsWith("Sig")) continue; // to speed things up ... avoids the matcher/RE invocation... + + final var m = SIGNAL_MASK_PATTERN.matcher(line); + + if (!m.matches()) continue; + + var sigmask = m.group(MASK); + final var slen = sigmask.length(); + + sigmask = sigmask.substring(slen / 2 , slen); // only really interested in the non r/t signals ... + + final var sigquit = (Long.valueOf(sigmask, 16) & SIGQUIT) != 0L; + + switch (m.group(FIELD)) { + case "SigBlk": { quitBlk = sigquit; readBlk = true; break; } + case "SigIgn": { quitIgn = sigquit; readIgn = true; break; } + case "SigCgt": { quitCgt = sigquit; readCgt = true; break; } + } + + if (readBlk && readIgn && readCgt) break; + } + + final boolean okToSendQuit = (!quitIgn && quitCgt); // ignore blocked as it may be temporary ... + + if (okToSendQuit) { + sendQuitTo(pid); + } else if (throwIfNotReady) { + final var cmdline = Files.lines(procPid.resolve("cmdline")).findFirst(); + + var cmd = "null"; // default + + if (cmdline.isPresent()) { + cmd = cmdline.get(); + cmd = cmd.substring(0, cmd.length() - 1); // remove trailing \0 + } + + throw new AttachNotSupportedException("pid: " + pid + " cmd: '" + cmd + "' state is not ready to participate in attach handshake!"); + } + + return okToSendQuit; + } //-- native methods From 0b1f57105d5af72b2cd47fa5c9a2b4e2961318cd Mon Sep 17 00:00:00 2001 From: Chris Plummer Date: Tue, 19 Nov 2024 18:58:00 +0000 Subject: [PATCH 19/74] 8253440: serviceability/sa/TestJhsdbJstackLineNumbers.java failed with "Didn't find enough line numbers" Reviewed-by: kevinw, lmesnik --- .../sa/TestJhsdbJstackLineNumbers.java | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/test/hotspot/jtreg/serviceability/sa/TestJhsdbJstackLineNumbers.java b/test/hotspot/jtreg/serviceability/sa/TestJhsdbJstackLineNumbers.java index 5d9c3982fb644..87e664ef308f0 100644 --- a/test/hotspot/jtreg/serviceability/sa/TestJhsdbJstackLineNumbers.java +++ b/test/hotspot/jtreg/serviceability/sa/TestJhsdbJstackLineNumbers.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2024, 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 @@ -35,6 +35,7 @@ /** * @test + * @bug 8214226 8243500 * @requires vm.hasSA * @requires os.arch=="amd64" | os.arch=="x86_64" * @requires os.family=="windows" | os.family == "linux" | os.family == "mac" @@ -53,7 +54,7 @@ * * The test works by spawning a process that sits in a 10 line loop in the busywork() method, * all while the main test does repeated jstacks on the process. The expectation is - * that at least 5 of the lines in the busywork() loop will eventually show up in at + * that at least 4 of the lines in the busywork() loop will eventually show up in at * least one of the jstack runs. */ @@ -94,8 +95,11 @@ public static void main(String... args) { public class TestJhsdbJstackLineNumbers { // This is the number of lines in the busywork main loop static final int TOTAL_BUSYWORK_LOOP_LINES = 10; - // The minimum number of lines that we must at some point see in the jstack output - static final int MIN_BUSYWORK_LOOP_LINES = 5; + // The minimum number of lines that we must see at some point in the jstack output. + // There's always a chance we could see fewer, but the chances are so low that + // it is unlikely to ever happen. We can always decrease the odds by lowering + // the required number of lines or increasing the number of jstack runs. + static final int MIN_BUSYWORK_LOOP_LINES = 4; static final int MAX_NUMBER_OF_JSTACK_RUNS = 25; From 6a5256ec042e16a2157475e86e7859b345a91bd0 Mon Sep 17 00:00:00 2001 From: Stuart Marks Date: Tue, 19 Nov 2024 18:58:23 +0000 Subject: [PATCH 20/74] 8344149: Remove usage of Security Manager from java.rmi Reviewed-by: rriggs, kevinw, aefimov --- .../classes/java/rmi/MarshalledObject.java | 16 +-- .../classes/java/rmi/server/LogStream.java | 10 +- .../share/classes/java/rmi/server/ObjID.java | 8 +- .../java/rmi/server/RMIClassLoader.java | 14 +- .../java/rmi/server/RMISocketFactory.java | 10 -- .../classes/sun/rmi/log/ReliableLog.java | 22 +-- .../sun/rmi/registry/RegistryImpl.java | 2 - .../share/classes/sun/rmi/runtime/Log.java | 44 ++---- .../sun/rmi/runtime/NewThreadAction.java | 56 +++----- .../classes/sun/rmi/runtime/RuntimeUtil.java | 50 +------ .../sun/rmi/server/MarshalInputStream.java | 10 +- .../sun/rmi/server/MarshalOutputStream.java | 11 +- .../classes/sun/rmi/server/UnicastRef.java | 8 +- .../sun/rmi/server/UnicastServerRef.java | 41 ++---- .../share/classes/sun/rmi/server/Util.java | 27 +--- .../sun/rmi/transport/DGCAckHandler.java | 12 +- .../classes/sun/rmi/transport/DGCClient.java | 70 ++-------- .../classes/sun/rmi/transport/DGCImpl.java | 98 ++++---------- .../sun/rmi/transport/DGCImpl_Stub.java | 4 +- .../share/classes/sun/rmi/transport/GC.java | 30 ++--- .../sun/rmi/transport/ObjectTable.java | 20 +-- .../sun/rmi/transport/StreamRemoteCall.java | 10 +- .../classes/sun/rmi/transport/Target.java | 33 +---- .../classes/sun/rmi/transport/Transport.java | 50 +------ .../sun/rmi/transport/tcp/TCPChannel.java | 84 ++---------- .../sun/rmi/transport/tcp/TCPEndpoint.java | 22 +-- .../sun/rmi/transport/tcp/TCPTransport.java | 127 ++---------------- 27 files changed, 173 insertions(+), 716 deletions(-) diff --git a/src/java.rmi/share/classes/java/rmi/MarshalledObject.java b/src/java.rmi/share/classes/java/rmi/MarshalledObject.java index 148cc97ef94ee..acf402db4d9be 100644 --- a/src/java.rmi/share/classes/java/rmi/MarshalledObject.java +++ b/src/java.rmi/share/classes/java/rmi/MarshalledObject.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2024, 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 @@ -35,8 +35,6 @@ import java.io.ObjectStreamConstants; import java.io.OutputStream; import java.io.Serializable; -import java.security.AccessController; -import java.security.PrivilegedAction; import sun.rmi.server.MarshalInputStream; import sun.rmi.server.MarshalOutputStream; @@ -317,7 +315,6 @@ private static class MarshalledObjectInputStream * null, then all annotations will be * null. */ - @SuppressWarnings("removal") MarshalledObjectInputStream(InputStream objIn, InputStream locIn, ObjectInputFilter filter) throws IOException @@ -325,13 +322,10 @@ private static class MarshalledObjectInputStream super(objIn); this.locIn = (locIn == null ? null : new ObjectInputStream(locIn)); if (filter != null) { - AccessController.doPrivileged((PrivilegedAction) () -> { - MarshalledObjectInputStream.this.setObjectInputFilter(filter); - if (MarshalledObjectInputStream.this.locIn != null) { - MarshalledObjectInputStream.this.locIn.setObjectInputFilter(filter); - } - return null; - }); + MarshalledObjectInputStream.this.setObjectInputFilter(filter); + if (MarshalledObjectInputStream.this.locIn != null) { + MarshalledObjectInputStream.this.locIn.setObjectInputFilter(filter); + } } } diff --git a/src/java.rmi/share/classes/java/rmi/server/LogStream.java b/src/java.rmi/share/classes/java/rmi/server/LogStream.java index ca554569d3b58..8ac2677026329 100644 --- a/src/java.rmi/share/classes/java/rmi/server/LogStream.java +++ b/src/java.rmi/share/classes/java/rmi/server/LogStream.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2024, 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 @@ -120,14 +120,6 @@ public static synchronized PrintStream getDefaultStream() { */ @Deprecated public static synchronized void setDefaultStream(PrintStream newDefault) { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - - if (sm != null) { - sm.checkPermission( - new java.util.logging.LoggingPermission("control", null)); - } - defaultStream = newDefault; } diff --git a/src/java.rmi/share/classes/java/rmi/server/ObjID.java b/src/java.rmi/share/classes/java/rmi/server/ObjID.java index ae3a61277ec39..894ee317d28e8 100644 --- a/src/java.rmi/share/classes/java/rmi/server/ObjID.java +++ b/src/java.rmi/share/classes/java/rmi/server/ObjID.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2024, 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 @@ -30,8 +30,6 @@ import java.io.ObjectInput; import java.io.ObjectOutput; import java.io.Serializable; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.security.SecureRandom; import java.util.concurrent.atomic.AtomicLong; @@ -242,9 +240,7 @@ public String toString() { } private static boolean useRandomIDs() { - @SuppressWarnings("removal") - String value = AccessController.doPrivileged( - (PrivilegedAction) () -> System.getProperty("java.rmi.server.randomIDs")); + String value = System.getProperty("java.rmi.server.randomIDs"); return value == null ? true : Boolean.parseBoolean(value); } } diff --git a/src/java.rmi/share/classes/java/rmi/server/RMIClassLoader.java b/src/java.rmi/share/classes/java/rmi/server/RMIClassLoader.java index 6736c33f0a028..004ea27e30ac6 100644 --- a/src/java.rmi/share/classes/java/rmi/server/RMIClassLoader.java +++ b/src/java.rmi/share/classes/java/rmi/server/RMIClassLoader.java @@ -27,8 +27,6 @@ import java.net.MalformedURLException; import java.net.URL; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.Iterator; import java.util.ServiceLoader; @@ -112,12 +110,7 @@ public class RMIClassLoader { newDefaultProviderInstance(); /** provider instance */ - @SuppressWarnings("removal") - private static final RMIClassLoaderSpi provider = - AccessController.doPrivileged( - new PrivilegedAction() { - public RMIClassLoaderSpi run() { return initializeProvider(); } - }); + private static final RMIClassLoaderSpi provider = initializeProvider(); /* * Disallow anyone from creating one of these. @@ -538,11 +531,6 @@ public static String getClassAnnotation(Class cl) { * @since 1.4 */ public static RMIClassLoaderSpi getDefaultProviderInstance() { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPermission(new RuntimePermission("setFactory")); - } return defaultProvider; } diff --git a/src/java.rmi/share/classes/java/rmi/server/RMISocketFactory.java b/src/java.rmi/share/classes/java/rmi/server/RMISocketFactory.java index fedc4b22d9b04..a7fc07f3d4bef 100644 --- a/src/java.rmi/share/classes/java/rmi/server/RMISocketFactory.java +++ b/src/java.rmi/share/classes/java/rmi/server/RMISocketFactory.java @@ -131,11 +131,6 @@ public static synchronized void setSocketFactory(RMISocketFactory fac) if (factory != null) { throw new SocketException("factory already defined"); } - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); - if (security != null) { - security.checkSetFactory(); - } factory = fac; } @@ -181,11 +176,6 @@ public static synchronized RMISocketFactory getDefaultSocketFactory() { */ public static synchronized void setFailureHandler(RMIFailureHandler fh) { - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); - if (security != null) { - security.checkSetFactory(); - } handler = fh; } diff --git a/src/java.rmi/share/classes/sun/rmi/log/ReliableLog.java b/src/java.rmi/share/classes/sun/rmi/log/ReliableLog.java index 293e2ccdec3c7..ce2aa84d31282 100644 --- a/src/java.rmi/share/classes/sun/rmi/log/ReliableLog.java +++ b/src/java.rmi/share/classes/sun/rmi/log/ReliableLog.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2024, 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 @@ -27,9 +27,6 @@ import java.io.*; import java.lang.reflect.Constructor; -import java.rmi.server.RMIClassLoader; -import java.security.AccessController; -import java.security.PrivilegedAction; /** * This class is a simple implementation of a reliable Log. The @@ -132,15 +129,13 @@ public class ReliableLog { * if an exception occurs during invocation of the handler's * snapshot method or if other IOException occurs. */ - @SuppressWarnings("removal") public ReliableLog(String dirPath, LogHandler handler, boolean pad) throws IOException { super(); - this.Debug = AccessController.doPrivileged( - (PrivilegedAction) () -> Boolean.getBoolean("sun.rmi.log.debug")); + this.Debug = Boolean.getBoolean("sun.rmi.log.debug"); dir = new File(dirPath); if (!(dir.exists() && dir.isDirectory())) { // create directory @@ -331,19 +326,10 @@ public synchronized void update(Object value, boolean forceToDisk) private static Constructor getLogClassConstructor() { - @SuppressWarnings("removal") - String logClassName = AccessController.doPrivileged( - (PrivilegedAction) () -> System.getProperty("sun.rmi.log.class")); + String logClassName = System.getProperty("sun.rmi.log.class"); if (logClassName != null) { try { - @SuppressWarnings("removal") - ClassLoader loader = - AccessController.doPrivileged( - new PrivilegedAction() { - public ClassLoader run() { - return ClassLoader.getSystemClassLoader(); - } - }); + ClassLoader loader = ClassLoader.getSystemClassLoader(); Class cl = loader.loadClass(logClassName).asSubclass(LogFile.class); return cl.getConstructor(String.class, String.class); diff --git a/src/java.rmi/share/classes/sun/rmi/registry/RegistryImpl.java b/src/java.rmi/share/classes/sun/rmi/registry/RegistryImpl.java index 91bb92d983333..406e16b637672 100644 --- a/src/java.rmi/share/classes/sun/rmi/registry/RegistryImpl.java +++ b/src/java.rmi/share/classes/sun/rmi/registry/RegistryImpl.java @@ -263,7 +263,6 @@ public String[] list() * Check that the caller has access to perform indicated operation. * The client must be on same the same host as this server. */ - @SuppressWarnings("removal") public static void checkAccess(String op) throws AccessException { try { @@ -370,7 +369,6 @@ private static URL[] pathToURLs(String path) { * {@link ObjectInputFilter.Status#REJECTED} if rejected, * otherwise {@link ObjectInputFilter.Status#UNDECIDED} */ - @SuppressWarnings("removal") private static ObjectInputFilter.Status registryFilter(ObjectInputFilter.FilterInfo filterInfo) { if (registryFilter != null) { ObjectInputFilter.Status status = registryFilter.checkInput(filterInfo); diff --git a/src/java.rmi/share/classes/sun/rmi/runtime/Log.java b/src/java.rmi/share/classes/sun/rmi/runtime/Log.java index 849b35688d14b..78154bb21c834 100644 --- a/src/java.rmi/share/classes/sun/rmi/runtime/Log.java +++ b/src/java.rmi/share/classes/sun/rmi/runtime/Log.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2024, 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 @@ -30,7 +30,6 @@ import java.io.OutputStream; import java.lang.StackWalker.StackFrame; import java.rmi.server.LogStream; -import java.security.PrivilegedAction; import java.util.Set; import java.util.logging.Handler; import java.util.logging.SimpleFormatter; @@ -69,9 +68,7 @@ public abstract class Log { /* selects log implementation */ private static final LogFactory logFactory; static { - @SuppressWarnings("removal") - boolean useOld = java.security.AccessController.doPrivileged( - (PrivilegedAction) () -> Boolean.getBoolean("sun.rmi.log.useOld")); + boolean useOld = Boolean.getBoolean("sun.rmi.log.useOld"); /* set factory to select the logging facility to use */ logFactory = (useOld ? (LogFactory) new LogStreamLogFactory() : @@ -177,17 +174,12 @@ public Log createLog(final String loggerName, String oldLogName, private static class LoggerLog extends Log { /* alternate console handler for RMI loggers */ - @SuppressWarnings("removal") - private static final Handler alternateConsole = - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Handler run() { - InternalStreamHandler alternate = - new InternalStreamHandler(System.err); - alternate.setLevel(Level.ALL); - return alternate; - } - }); + private static final Handler alternateConsole; + static { + var alternate = new InternalStreamHandler(System.err); + alternate.setLevel(Level.ALL); + alternateConsole = alternate; + } /** handler to which messages are copied */ private InternalStreamHandler copyHandler = null; @@ -199,22 +191,14 @@ public Handler run() { private LoggerPrintStream loggerSandwich; /** creates a Log which will delegate to the given logger */ - @SuppressWarnings("removal") private LoggerLog(final Logger logger, final Level level) { this.logger = logger; - if (level != null){ - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Void run() { - if (!logger.isLoggable(level)) { - logger.setLevel(level); - } - logger.addHandler(alternateConsole); - return null; - } - } - ); + if (level != null) { + if (!logger.isLoggable(level)) { + logger.setLevel(level); + } + logger.addHandler(alternateConsole); } } @@ -247,8 +231,6 @@ public String toString() { /** * Set the output stream associated with the RMI server call * logger. - * - * Calling code needs LoggingPermission "control". */ public synchronized void setOutputStream(OutputStream out) { if (out != null) { diff --git a/src/java.rmi/share/classes/sun/rmi/runtime/NewThreadAction.java b/src/java.rmi/share/classes/sun/rmi/runtime/NewThreadAction.java index aebd200afe689..f9be382d0fc7a 100644 --- a/src/java.rmi/share/classes/sun/rmi/runtime/NewThreadAction.java +++ b/src/java.rmi/share/classes/sun/rmi/runtime/NewThreadAction.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2024, 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 @@ -25,13 +25,11 @@ package sun.rmi.runtime; -import java.security.AccessController; -import java.security.PrivilegedAction; -import sun.security.util.SecurityConstants; - /** - * A PrivilegedAction for creating a new thread conveniently with an - * AccessController.doPrivileged construct. + * A utility class for creating threads. The constructors take a + * variety of parameters to configure the thread. The run() method + * creates and sets up the thread and returns it, but does not + * start it. * * All constructors allow the choice of the Runnable for the new * thread to execute, the name of the new thread (which will be @@ -48,34 +46,27 @@ * * @author Peter Jones **/ -public final class NewThreadAction implements PrivilegedAction { +public final class NewThreadAction { /** cached reference to the system (root) thread group */ - @SuppressWarnings("removal") - static final ThreadGroup systemThreadGroup = - AccessController.doPrivileged(new PrivilegedAction() { - public ThreadGroup run() { - ThreadGroup group = Thread.currentThread().getThreadGroup(); - ThreadGroup parent; - while ((parent = group.getParent()) != null) { - group = parent; - } - return group; - } - }); + static final ThreadGroup systemThreadGroup; + static { + ThreadGroup group = Thread.currentThread().getThreadGroup(); + ThreadGroup parent; + while ((parent = group.getParent()) != null) { + group = parent; + } + systemThreadGroup = group; + } + /** - * special child of the system thread group for running tasks that - * may execute user code, so that the security policy for threads in - * the system thread group will not apply + * Special child of the system thread group for running tasks that + * may execute user code. The need for a separate thread group may + * be a vestige of it having had a different security policy from + * the system thread group, so this might no longer be necessary. */ - @SuppressWarnings("removal") - static final ThreadGroup userThreadGroup = - AccessController.doPrivileged(new PrivilegedAction() { - public ThreadGroup run() { - return new ThreadGroup(systemThreadGroup, "RMI Runtime"); - } - }); + static final ThreadGroup userThreadGroup = new ThreadGroup(systemThreadGroup, "RMI Runtime"); private final ThreadGroup group; private final Runnable runnable; @@ -128,11 +119,6 @@ public NewThreadAction(Runnable runnable, String name, boolean daemon, } public Thread run() { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION); - } Thread t = new Thread(group, runnable, "RMI " + name); t.setContextClassLoader(ClassLoader.getSystemClassLoader()); t.setDaemon(daemon); diff --git a/src/java.rmi/share/classes/sun/rmi/runtime/RuntimeUtil.java b/src/java.rmi/share/classes/sun/rmi/runtime/RuntimeUtil.java index b45bbe5f3a334..4be706e57bb20 100644 --- a/src/java.rmi/share/classes/sun/rmi/runtime/RuntimeUtil.java +++ b/src/java.rmi/share/classes/sun/rmi/runtime/RuntimeUtil.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2024, 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 @@ -25,9 +25,6 @@ package sun.rmi.runtime; -import java.security.AccessController; -import java.security.Permission; -import java.security.PrivilegedAction; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; @@ -37,10 +34,7 @@ * RMI runtime implementation utilities. * * There is a single instance of this class, which can be obtained - * with a GetInstanceAction. Getting the instance requires - * RuntimePermission("sun.rmi.runtime.RuntimeUtil.getInstance") - * because the public methods of this class expose security-sensitive - * capabilities. + * with a getInstance() call. * * @author Peter Jones **/ @@ -51,14 +45,8 @@ public final class RuntimeUtil { Log.getLog("sun.rmi.runtime", null, false); /** number of scheduler threads */ - @SuppressWarnings("removal") private static final int schedulerThreads = // default 1 - AccessController.doPrivileged((PrivilegedAction) () -> - Integer.getInteger("sun.rmi.runtime.schedulerThreads", 1)); - - /** permission required to get instance */ - private static final Permission GET_INSTANCE_PERMISSION = - new RuntimePermission("sun.rmi.runtime.RuntimeUtil.getInstance"); + Integer.getInteger("sun.rmi.runtime.schedulerThreads", 1); /** the singleton instance of this class */ private static final RuntimeUtil instance = new RuntimeUtil(); @@ -71,13 +59,11 @@ private RuntimeUtil() { schedulerThreads, new ThreadFactory() { private final AtomicInteger count = new AtomicInteger(); - @SuppressWarnings("removal") public Thread newThread(Runnable runnable) { try { - return AccessController.doPrivileged( - new NewThreadAction(runnable, - "Scheduler(" + count.getAndIncrement() + ")", - true)); + return new NewThreadAction(runnable, + "Scheduler(" + count.getAndIncrement() + ")", + true).run(); } catch (Throwable t) { runtimeLog.log(Level.WARNING, "scheduler thread factory throws", t); @@ -94,29 +80,7 @@ public Thread newThread(Runnable runnable) { // stpe.allowCoreThreadTimeOut(true); } - /** - * A PrivilegedAction for getting the RuntimeUtil instance. - **/ - public static class GetInstanceAction - implements PrivilegedAction - { - /** - * Creates an action that returns the RuntimeUtil instance. - **/ - public GetInstanceAction() { - } - - public RuntimeUtil run() { - return getInstance(); - } - } - - private static RuntimeUtil getInstance() { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPermission(GET_INSTANCE_PERMISSION); - } + public static RuntimeUtil getInstance() { return instance; } diff --git a/src/java.rmi/share/classes/sun/rmi/server/MarshalInputStream.java b/src/java.rmi/share/classes/sun/rmi/server/MarshalInputStream.java index 5574da072eb02..30b6c47ed3d38 100644 --- a/src/java.rmi/share/classes/sun/rmi/server/MarshalInputStream.java +++ b/src/java.rmi/share/classes/sun/rmi/server/MarshalInputStream.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2024, 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 @@ -34,7 +34,6 @@ import java.security.AccessControlException; import java.security.Permission; import java.rmi.server.RMIClassLoader; -import java.security.PrivilegedAction; /** * MarshalInputStream is an extension of ObjectInputStream. When resolving @@ -62,12 +61,9 @@ public class MarshalInputStream extends ObjectInputStream { * The value is only false when the property is present * and is equal to "false". */ - @SuppressWarnings("removal") private static final boolean useCodebaseOnlyProperty = - ! java.security.AccessController.doPrivileged( - (PrivilegedAction) () -> System.getProperty( - "java.rmi.server.useCodebaseOnly", "true")) - .equalsIgnoreCase("false"); + ! System.getProperty("java.rmi.server.useCodebaseOnly", "true") + .equalsIgnoreCase("false"); /** table to hold sun classes to which access is explicitly permitted */ protected static Map> permittedSunClasses diff --git a/src/java.rmi/share/classes/sun/rmi/server/MarshalOutputStream.java b/src/java.rmi/share/classes/sun/rmi/server/MarshalOutputStream.java index 26dae06c2d7fd..81bf7bf42e77c 100644 --- a/src/java.rmi/share/classes/sun/rmi/server/MarshalOutputStream.java +++ b/src/java.rmi/share/classes/sun/rmi/server/MarshalOutputStream.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2024, 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 @@ -58,19 +58,12 @@ public MarshalOutputStream(OutputStream out) throws IOException { /** * Creates a marshal output stream with the given protocol version. */ - @SuppressWarnings("removal") public MarshalOutputStream(OutputStream out, int protocolVersion) throws IOException { super(out); this.useProtocolVersion(protocolVersion); - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Void run() { - enableReplaceObject(true); - return null; - } - }); + enableReplaceObject(true); } /** diff --git a/src/java.rmi/share/classes/sun/rmi/server/UnicastRef.java b/src/java.rmi/share/classes/sun/rmi/server/UnicastRef.java index 0e41b5615b5be..39ff8ce8f202a 100644 --- a/src/java.rmi/share/classes/sun/rmi/server/UnicastRef.java +++ b/src/java.rmi/share/classes/sun/rmi/server/UnicastRef.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2024, 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 @@ -38,8 +38,6 @@ import java.rmi.server.RemoteCall; import java.rmi.server.RemoteObject; import java.rmi.server.RemoteRef; -import java.security.AccessController; -import java.security.PrivilegedAction; import jdk.internal.access.SharedSecrets; import sun.rmi.runtime.Log; @@ -64,11 +62,9 @@ public class UnicastRef implements RemoteRef { /** * Client-side call log. */ - @SuppressWarnings("removal") public static final Log clientCallLog = Log.getLog("sun.rmi.client.call", "RMI", - AccessController.doPrivileged((PrivilegedAction) () -> - Boolean.getBoolean("sun.rmi.client.logCalls"))); + Boolean.getBoolean("sun.rmi.client.logCalls")); private static final long serialVersionUID = 8258372400816541186L; @SuppressWarnings("serial") // Type of field is not Serializable diff --git a/src/java.rmi/share/classes/sun/rmi/server/UnicastServerRef.java b/src/java.rmi/share/classes/sun/rmi/server/UnicastServerRef.java index 7c5b8f911f78f..6263bf6d599fe 100644 --- a/src/java.rmi/share/classes/sun/rmi/server/UnicastServerRef.java +++ b/src/java.rmi/share/classes/sun/rmi/server/UnicastServerRef.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2024, 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 @@ -48,14 +48,11 @@ import java.rmi.server.ServerRef; import java.rmi.server.Skeleton; import java.rmi.server.SkeletonNotFoundException; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.WeakHashMap; -import java.util.concurrent.atomic.AtomicInteger; import sun.rmi.runtime.Log; import sun.rmi.transport.LiveRef; import sun.rmi.transport.StreamRemoteCall; @@ -80,9 +77,7 @@ public class UnicastServerRef extends UnicastRef implements ServerRef, Dispatcher { /** value of server call log property */ - @SuppressWarnings("removal") - public static final boolean logCalls = AccessController.doPrivileged( - (PrivilegedAction) () -> Boolean.getBoolean("java.rmi.server.logCalls")); + public static final boolean logCalls = Boolean.getBoolean("java.rmi.server.logCalls"); /** server call log */ public static final Log callLog = @@ -92,10 +87,8 @@ public class UnicastServerRef extends UnicastRef private static final long serialVersionUID = -7384275867073752268L; /** flag to enable writing exceptions to System.err */ - @SuppressWarnings("removal") private static final boolean wantExceptionLog = - AccessController.doPrivileged((PrivilegedAction) () -> - Boolean.getBoolean("sun.rmi.server.exceptionTrace")); + Boolean.getBoolean("sun.rmi.server.exceptionTrace"); private boolean forceStubUse = false; @@ -103,10 +96,8 @@ public class UnicastServerRef extends UnicastRef * flag to remove server-side stack traces before marshalling * exceptions thrown by remote invocations to this VM */ - @SuppressWarnings("removal") private static final boolean suppressStackTraces = - AccessController.doPrivileged((PrivilegedAction) () -> - Boolean.getBoolean("sun.rmi.server.suppressStackTraces")); + Boolean.getBoolean("sun.rmi.server.suppressStackTraces"); /** * skeleton to dispatch remote calls through, for 1.1 stub protocol @@ -413,18 +404,10 @@ public void dispatch(Remote obj, RemoteCall call) throws IOException { * Sets a filter for invocation arguments, if a filter has been set. * Called by dispatch before the arguments are read. */ - @SuppressWarnings("removal") protected void unmarshalCustomCallData(ObjectInput in) throws IOException, ClassNotFoundException { - if (filter != null && - in instanceof ObjectInputStream) { - // Set the filter on the stream - ObjectInputStream ois = (ObjectInputStream) in; - - AccessController.doPrivileged((PrivilegedAction)() -> { - ois.setObjectInputFilter(filter); - return null; - }); + if (filter != null && in instanceof ObjectInputStream ois) { + ois.setObjectInputFilter(filter); } } @@ -576,7 +559,6 @@ private static class HashToMethod_Maps { HashToMethod_Maps() {} - @SuppressWarnings("removal") protected Map computeValue(Class remoteClass) { Map map = new HashMap<>(); for (Class cl = remoteClass; @@ -586,20 +568,13 @@ protected Map computeValue(Class remoteClass) { for (Class intf : cl.getInterfaces()) { if (Remote.class.isAssignableFrom(intf)) { for (Method method : intf.getMethods()) { - final Method m = method; /* * Set this Method object to override language * access checks so that the dispatcher can invoke * methods from non-public remote interfaces. */ - AccessController.doPrivileged( - new PrivilegedAction() { - public Void run() { - m.setAccessible(true); - return null; - } - }); - map.put(Util.computeMethodHash(m), m); + method.setAccessible(true); + map.put(Util.computeMethodHash(method), method); } } } diff --git a/src/java.rmi/share/classes/sun/rmi/server/Util.java b/src/java.rmi/share/classes/sun/rmi/server/Util.java index 2c1cfe52ffee4..8b9896bf2a956 100644 --- a/src/java.rmi/share/classes/sun/rmi/server/Util.java +++ b/src/java.rmi/share/classes/sun/rmi/server/Util.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2024, 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 @@ -35,28 +35,20 @@ import java.rmi.Remote; import java.rmi.RemoteException; import java.rmi.StubNotFoundException; -import java.rmi.registry.Registry; import java.rmi.server.LogStream; -import java.rmi.server.ObjID; -import java.rmi.server.RMIClientSocketFactory; import java.rmi.server.RemoteObjectInvocationHandler; import java.rmi.server.RemoteRef; import java.rmi.server.RemoteStub; import java.rmi.server.Skeleton; import java.rmi.server.SkeletonNotFoundException; -import java.security.AccessController; import java.security.MessageDigest; import java.security.DigestOutputStream; import java.security.NoSuchAlgorithmException; -import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Collections; import java.util.Map; import java.util.WeakHashMap; -import sun.rmi.registry.RegistryImpl; import sun.rmi.runtime.Log; -import sun.rmi.transport.LiveRef; -import sun.rmi.transport.tcp.TCPEndpoint; /** * A utility class with static methods for creating stubs/proxies and @@ -66,20 +58,15 @@ public final class Util { /** "server" package log level */ - @SuppressWarnings("removal") - static final int logLevel = LogStream.parseLevel( - AccessController.doPrivileged( - (PrivilegedAction) () -> System.getProperty("sun.rmi.server.logLevel"))); + static final int logLevel = LogStream.parseLevel(System.getProperty("sun.rmi.server.logLevel")); /** server reference log */ public static final Log serverRefLog = Log.getLog("sun.rmi.server.ref", "transport", Util.logLevel); /** cached value of property java.rmi.server.ignoreStubClasses */ - @SuppressWarnings("removal") private static final boolean ignoreStubClasses = - AccessController.doPrivileged( - (PrivilegedAction) () -> Boolean.getBoolean("java.rmi.server.ignoreStubClasses")); + Boolean.getBoolean("java.rmi.server.ignoreStubClasses"); /** cache of impl classes that have no corresponding stub class */ private static final Map, Void> withoutStubs = @@ -120,7 +107,6 @@ private Util() { * @throws StubNotFoundException if problem locating/creating stub or * creating the dynamic proxy instance **/ - @SuppressWarnings("removal") public static Remote createProxy(Class implClass, RemoteRef clientRef, boolean forceStubUse) @@ -150,12 +136,7 @@ public static Remote createProxy(Class implClass, /* REMIND: private remote interfaces? */ try { - return AccessController.doPrivileged(new PrivilegedAction() { - public Remote run() { - return (Remote) Proxy.newProxyInstance(loader, - interfaces, - handler); - }}); + return (Remote) Proxy.newProxyInstance(loader, interfaces, handler); } catch (IllegalArgumentException e) { throw new StubNotFoundException("unable to create proxy", e); } diff --git a/src/java.rmi/share/classes/sun/rmi/transport/DGCAckHandler.java b/src/java.rmi/share/classes/sun/rmi/transport/DGCAckHandler.java index d02b500f2a397..4004a23fff787 100644 --- a/src/java.rmi/share/classes/sun/rmi/transport/DGCAckHandler.java +++ b/src/java.rmi/share/classes/sun/rmi/transport/DGCAckHandler.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2024, 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 @@ -26,8 +26,6 @@ package sun.rmi.transport; import java.rmi.server.UID; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -64,16 +62,12 @@ public class DGCAckHandler { /** timeout for holding references without receiving an acknowledgment */ - @SuppressWarnings("removal") private static final long dgcAckTimeout = // default 5 minutes - AccessController.doPrivileged((PrivilegedAction) () -> - Long.getLong("sun.rmi.dgc.ackTimeout", 300000)); + Long.getLong("sun.rmi.dgc.ackTimeout", 300000); /** thread pool for scheduling delayed tasks */ - @SuppressWarnings("removal") private static final ScheduledExecutorService scheduler = - AccessController.doPrivileged( - new RuntimeUtil.GetInstanceAction()).getScheduler(); + RuntimeUtil.getInstance().getScheduler(); /** table mapping ack ID to handler */ private static final Map idTable = diff --git a/src/java.rmi/share/classes/sun/rmi/transport/DGCClient.java b/src/java.rmi/share/classes/sun/rmi/transport/DGCClient.java index 7185f46201f00..6bf0248f529f6 100644 --- a/src/java.rmi/share/classes/sun/rmi/transport/DGCClient.java +++ b/src/java.rmi/share/classes/sun/rmi/transport/DGCClient.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2024, 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 @@ -27,17 +27,13 @@ import java.io.InvalidClassException; import java.lang.ref.PhantomReference; import java.lang.ref.ReferenceQueue; -import java.net.SocketPermission; import java.rmi.UnmarshalException; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; -import java.rmi.ConnectException; import java.rmi.RemoteException; import java.rmi.dgc.DGC; import java.rmi.dgc.Lease; @@ -49,10 +45,6 @@ import sun.rmi.server.UnicastRef; import sun.rmi.server.Util; -import java.security.AccessControlContext; -import java.security.Permissions; -import java.security.ProtectionDomain; - /** * DGCClient implements the client-side of the RMI distributed garbage * collection system. @@ -91,22 +83,16 @@ final class DGCClient { private static VMID vmid = new VMID(); /** lease duration to request (usually ignored by server) */ - @SuppressWarnings("removal") private static final long leaseValue = // default 10 minutes - AccessController.doPrivileged((PrivilegedAction) () -> - Long.getLong("java.rmi.dgc.leaseValue", 600000)); + Long.getLong("java.rmi.dgc.leaseValue", 600000); /** maximum interval between retries of failed clean calls */ - @SuppressWarnings("removal") private static final long cleanInterval = // default 3 minutes - AccessController.doPrivileged((PrivilegedAction) () -> - Long.getLong("sun.rmi.dgc.cleanInterval", 180000)); + Long.getLong("sun.rmi.dgc.cleanInterval", 180000); /** maximum interval between complete garbage collections of local heap */ - @SuppressWarnings("removal") private static final long gcInterval = // default 1 hour - AccessController.doPrivileged((PrivilegedAction) () -> - Long.getLong("sun.rmi.dgc.client.gcInterval", 3600000)); + Long.getLong("sun.rmi.dgc.client.gcInterval", 3600000); /** minimum retry count for dirty calls that fail */ private static final int dirtyFailureRetries = 5; @@ -120,21 +106,6 @@ final class DGCClient { /** ObjID for server-side DGC object */ private static final ObjID dgcID = new ObjID(ObjID.DGC_ID); - /** - * An AccessControlContext with only socket permissions, - * suitable for an RMIClientSocketFactory. - */ - @SuppressWarnings("removal") - private static final AccessControlContext SOCKET_ACC = createSocketAcc(); - - @SuppressWarnings("removal") - private static AccessControlContext createSocketAcc() { - Permissions perms = new Permissions(); - perms.add(new SocketPermission("*", "connect,resolve")); - ProtectionDomain[] pd = { new ProtectionDomain(null, perms) }; - return new AccessControlContext(pd); - } - /* * Disallow anyone from creating one of these. */ @@ -256,7 +227,6 @@ public static EndpointEntry lookup(Endpoint ep) { } } - @SuppressWarnings("removal") private EndpointEntry(final Endpoint endpoint) { this.endpoint = endpoint; try { @@ -266,9 +236,9 @@ private EndpointEntry(final Endpoint endpoint) { } catch (RemoteException e) { throw new Error("internal error creating DGC stub"); } - renewCleanThread = AccessController.doPrivileged( + renewCleanThread = new NewThreadAction(new RenewCleanThread(), - "RenewClean-" + endpoint, true)); + "RenewClean-" + endpoint, true).run(); renewCleanThread.start(); } @@ -496,20 +466,13 @@ private void makeDirtyCall(Set refEntries, long sequenceNum) { * * This method must ONLY be called while synchronized on this entry. */ - @SuppressWarnings("removal") private void setRenewTime(long newRenewTime) { assert Thread.holdsLock(this); if (newRenewTime < renewTime) { renewTime = newRenewTime; if (interruptible) { - AccessController.doPrivileged( - new PrivilegedAction() { - public Void run() { - renewCleanThread.interrupt(); - return null; - } - }); + renewCleanThread.interrupt(); } } else { renewTime = newRenewTime; @@ -522,7 +485,6 @@ public Void run() { */ private class RenewCleanThread implements Runnable { - @SuppressWarnings("removal") public void run() { do { long timeToWait; @@ -601,19 +563,13 @@ public void run() { } } - boolean needRenewal_ = needRenewal; - Set refsToDirty_ = refsToDirty; - long sequenceNum_ = sequenceNum; - AccessController.doPrivileged((PrivilegedAction)() -> { - if (needRenewal_) { - makeDirtyCall(refsToDirty_, sequenceNum_); - } + if (needRenewal) { + makeDirtyCall(refsToDirty, sequenceNum); + } - if (!pendingCleans.isEmpty()) { - makeCleanCalls(); - } - return null; - }, SOCKET_ACC); + if (!pendingCleans.isEmpty()) { + makeCleanCalls(); + } } while (!removed || !pendingCleans.isEmpty()); } } diff --git a/src/java.rmi/share/classes/sun/rmi/transport/DGCImpl.java b/src/java.rmi/share/classes/sun/rmi/transport/DGCImpl.java index ba73610b44141..08c2eda40455d 100644 --- a/src/java.rmi/share/classes/sun/rmi/transport/DGCImpl.java +++ b/src/java.rmi/share/classes/sun/rmi/transport/DGCImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2024, 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 @@ -25,7 +25,6 @@ package sun.rmi.transport; import java.io.ObjectInputFilter; -import java.net.SocketPermission; import java.rmi.Remote; import java.rmi.RemoteException; import java.rmi.dgc.DGC; @@ -36,11 +35,6 @@ import java.rmi.server.RemoteServer; import java.rmi.server.ServerNotActiveException; import java.rmi.server.UID; -import java.security.AccessControlContext; -import java.security.AccessController; -import java.security.Permissions; -import java.security.PrivilegedAction; -import java.security.ProtectionDomain; import java.security.Security; import java.util.ArrayList; import java.util.HashSet; @@ -68,28 +62,20 @@ final class DGCImpl implements DGC { /* dgc system log */ - @SuppressWarnings("removal") static final Log dgcLog = Log.getLog("sun.rmi.dgc", "dgc", - LogStream.parseLevel(AccessController.doPrivileged( - (PrivilegedAction) () -> System.getProperty("sun.rmi.dgc.logLevel")))); + LogStream.parseLevel(System.getProperty("sun.rmi.dgc.logLevel"))); /** lease duration to grant to clients */ - @SuppressWarnings("removal") private static final long leaseValue = // default 10 minutes - AccessController.doPrivileged( - (PrivilegedAction) () -> Long.getLong("java.rmi.dgc.leaseValue", 600000)); + Long.getLong("java.rmi.dgc.leaseValue", 600000); /** lease check interval; default is half of lease grant duration */ - @SuppressWarnings("removal") private static final long leaseCheckInterval = - AccessController.doPrivileged( - (PrivilegedAction) () -> Long.getLong("sun.rmi.dgc.checkInterval", leaseValue / 2)); + Long.getLong("sun.rmi.dgc.checkInterval", leaseValue / 2); /** thread pool for scheduling delayed tasks */ - @SuppressWarnings("removal") private static final ScheduledExecutorService scheduler = - AccessController.doPrivileged( - new RuntimeUtil.GetInstanceAction()).getScheduler(); + RuntimeUtil.getInstance().getScheduler(); /** remote implementation of DGC interface for this VM */ private static DGCImpl dgc; @@ -124,9 +110,7 @@ static DGCImpl getDGCImpl() { * The dgcFilter created from the value of the {@code "sun.rmi.transport.dgcFilter"} * property. */ - @SuppressWarnings("removal") - private static final ObjectInputFilter dgcFilter = - AccessController.doPrivileged((PrivilegedAction)DGCImpl::initDgcFilter); + private static final ObjectInputFilter dgcFilter = initDgcFilter(); /** * Initialize the dgcFilter from the security properties or system property; if any @@ -323,59 +307,35 @@ private void checkLeases() { exportSingleton(); } - @SuppressWarnings("removal") private static void exportSingleton() { /* * "Export" the singleton DGCImpl in a context isolated from * the arbitrary current thread context. */ - AccessController.doPrivileged(new PrivilegedAction() { - public Void run() { - ClassLoader savedCcl = - Thread.currentThread().getContextClassLoader(); - try { - Thread.currentThread().setContextClassLoader( - ClassLoader.getSystemClassLoader()); - - /* - * Put remote collector object in table by hand to prevent - * listen on port. (UnicastServerRef.exportObject would - * cause transport to listen.) - */ - try { - dgc = new DGCImpl(); - ObjID dgcID = new ObjID(ObjID.DGC_ID); - LiveRef ref = new LiveRef(dgcID, 0); - UnicastServerRef disp = new UnicastServerRef(ref, - DGCImpl::checkInput); - Remote stub = - Util.createProxy(DGCImpl.class, - new UnicastRef(ref), true); - disp.setSkeleton(dgc); - - Permissions perms = new Permissions(); - perms.add(new SocketPermission("*", "accept,resolve")); - ProtectionDomain[] pd = { new ProtectionDomain(null, perms) }; - AccessControlContext acceptAcc = new AccessControlContext(pd); - - Target target = AccessController.doPrivileged( - new PrivilegedAction() { - public Target run() { - return new Target(dgc, disp, stub, dgcID, true); - } - }, acceptAcc); - - ObjectTable.putTarget(target); - } catch (RemoteException e) { - throw new Error( - "exception initializing server-side DGC", e); - } - } finally { - Thread.currentThread().setContextClassLoader(savedCcl); - } - return null; + ClassLoader savedCcl = Thread.currentThread().getContextClassLoader(); + try { + Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader()); + + /* + * Put remote collector object in table by hand to prevent + * listen on port. (UnicastServerRef.exportObject would + * cause transport to listen.) + */ + try { + dgc = new DGCImpl(); + ObjID dgcID = new ObjID(ObjID.DGC_ID); + LiveRef ref = new LiveRef(dgcID, 0); + UnicastServerRef disp = new UnicastServerRef(ref, DGCImpl::checkInput); + Remote stub = Util.createProxy(DGCImpl.class, new UnicastRef(ref), true); + disp.setSkeleton(dgc); + Target target = new Target(dgc, disp, stub, dgcID, true); + ObjectTable.putTarget(target); + } catch (RemoteException e) { + throw new Error("exception initializing server-side DGC", e); } - }); + } finally { + Thread.currentThread().setContextClassLoader(savedCcl); + } } /** diff --git a/src/java.rmi/share/classes/sun/rmi/transport/DGCImpl_Stub.java b/src/java.rmi/share/classes/sun/rmi/transport/DGCImpl_Stub.java index 99880f3b3b0c0..c16ee9870b26a 100644 --- a/src/java.rmi/share/classes/sun/rmi/transport/DGCImpl_Stub.java +++ b/src/java.rmi/share/classes/sun/rmi/transport/DGCImpl_Stub.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2024, 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 @@ -33,8 +33,6 @@ import java.rmi.dgc.Lease; import java.rmi.dgc.VMID; import java.rmi.server.UID; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.ArrayList; /** diff --git a/src/java.rmi/share/classes/sun/rmi/transport/GC.java b/src/java.rmi/share/classes/sun/rmi/transport/GC.java index 4bd50511dd45a..9c76a98b9551f 100644 --- a/src/java.rmi/share/classes/sun/rmi/transport/GC.java +++ b/src/java.rmi/share/classes/sun/rmi/transport/GC.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2024, 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 @@ -25,8 +25,6 @@ package sun.rmi.transport; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.SortedSet; import java.util.TreeSet; import jdk.internal.misc.InnocuousThread; @@ -39,7 +37,7 @@ * @since 1.2 */ -@SuppressWarnings({"removal", "restricted"}) +@SuppressWarnings("restricted") class GC { private GC() { } /* To prevent instantiation */ @@ -85,11 +83,7 @@ private static class LatencyLock extends Object { }; public static native long maxObjectInspectionAge(); static { - AccessController.doPrivileged(new PrivilegedAction() { - public Void run() { - System.loadLibrary("rmi"); - return null; - }}); + System.loadLibrary("rmi"); } private static class Daemon implements Runnable { @@ -134,18 +128,12 @@ public void run() { /* Create a new daemon thread */ public static void create() { - PrivilegedAction pa = new PrivilegedAction() { - public Void run() { - Thread t = InnocuousThread.newSystemThread("RMI GC Daemon", - new Daemon()); - assert t.getContextClassLoader() == null; - t.setDaemon(true); - t.setPriority(Thread.MIN_PRIORITY + 1); - t.start(); - GC.daemon = t; - return null; - }}; - AccessController.doPrivileged(pa); + Thread t = InnocuousThread.newSystemThread("RMI GC Daemon", new Daemon()); + assert t.getContextClassLoader() == null; + t.setDaemon(true); + t.setPriority(Thread.MIN_PRIORITY + 1); + t.start(); + GC.daemon = t; } } diff --git a/src/java.rmi/share/classes/sun/rmi/transport/ObjectTable.java b/src/java.rmi/share/classes/sun/rmi/transport/ObjectTable.java index d01256f5533e4..dd1fcaddeab83 100644 --- a/src/java.rmi/share/classes/sun/rmi/transport/ObjectTable.java +++ b/src/java.rmi/share/classes/sun/rmi/transport/ObjectTable.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2024, 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 @@ -30,8 +30,6 @@ import java.rmi.dgc.VMID; import java.rmi.server.ExportException; import java.rmi.server.ObjID; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.HashMap; import java.util.Map; import sun.rmi.runtime.Log; @@ -48,10 +46,8 @@ public final class ObjectTable { /** maximum interval between complete garbage collections of local heap */ - @SuppressWarnings("removal") private static final long gcInterval = // default 1 hour - AccessController.doPrivileged((PrivilegedAction) () -> - Long.getLong("sun.rmi.dgc.server.gcInterval", 3600000)); + Long.getLong("sun.rmi.dgc.server.gcInterval", 3600000); /** * lock guarding objTable and implTable. @@ -270,14 +266,12 @@ static void unreferenced(ObjID id, long sequenceNum, VMID vmid, * thread operates, the reaper thread also serves as the non-daemon * VM keep-alive thread; a new reaper thread is created if necessary. */ - @SuppressWarnings("removal") static void incrementKeepAliveCount() { synchronized (keepAliveLock) { keepAliveCount++; if (reaper == null) { - reaper = AccessController.doPrivileged( - new NewThreadAction(new Reaper(), "Reaper", false)); + reaper = new NewThreadAction(new Reaper(), "Reaper", false).run(); reaper.start(); } @@ -307,19 +301,13 @@ static void incrementKeepAliveCount() { * reaper thread is terminated to cease keeping the VM alive (and * because there are no more non-permanent remote objects to reap). */ - @SuppressWarnings("removal") static void decrementKeepAliveCount() { synchronized (keepAliveLock) { keepAliveCount--; if (keepAliveCount == 0) { if (!(reaper != null)) { throw new AssertionError(); } - AccessController.doPrivileged(new PrivilegedAction() { - public Void run() { - reaper.interrupt(); - return null; - } - }); + reaper.interrupt(); reaper = null; /* diff --git a/src/java.rmi/share/classes/sun/rmi/transport/StreamRemoteCall.java b/src/java.rmi/share/classes/sun/rmi/transport/StreamRemoteCall.java index 8df144d086d60..0cff2c33ce9f7 100644 --- a/src/java.rmi/share/classes/sun/rmi/transport/StreamRemoteCall.java +++ b/src/java.rmi/share/classes/sun/rmi/transport/StreamRemoteCall.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2024, 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 @@ -37,8 +37,6 @@ import java.rmi.UnmarshalException; import java.rmi.server.ObjID; import java.rmi.server.RemoteCall; -import java.security.AccessController; -import java.security.PrivilegedAction; import sun.rmi.runtime.Log; import sun.rmi.server.UnicastRef; @@ -139,17 +137,13 @@ public void setObjectInputFilter(ObjectInputFilter filter) { * Get the InputStream the stub/skeleton should get results/arguments * from. */ - @SuppressWarnings("removal") public ObjectInput getInputStream() throws IOException { if (in == null) { Transport.transportLog.log(Log.VERBOSE, "getting input stream"); in = new ConnectionInputStream(conn.getInputStream()); if (filter != null) { - AccessController.doPrivileged((PrivilegedAction) () -> { - in.setObjectInputFilter(filter); - return null; - }); + in.setObjectInputFilter(filter); } } return in; diff --git a/src/java.rmi/share/classes/sun/rmi/transport/Target.java b/src/java.rmi/share/classes/sun/rmi/transport/Target.java index c0d79bb38e2d2..3ea404698f290 100644 --- a/src/java.rmi/share/classes/sun/rmi/transport/Target.java +++ b/src/java.rmi/share/classes/sun/rmi/transport/Target.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2024, 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 @@ -29,9 +29,6 @@ import java.rmi.dgc.VMID; import java.rmi.server.ObjID; import java.rmi.server.Unreferenced; -import java.security.AccessControlContext; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.*; import sun.rmi.runtime.Log; import sun.rmi.runtime.NewThreadAction; @@ -58,9 +55,6 @@ public final class Target { /** table that maps client endpoints to sequence numbers */ private final Hashtable sequenceTable = new Hashtable<>(5); - /** access control context in which target was created */ - @SuppressWarnings("removal") - private final AccessControlContext acc; /** context class loader in which target was created */ private final ClassLoader ccl; /** number of pending/executing calls */ @@ -86,7 +80,6 @@ public final class Target { * collection. Permanent objects do not keep a server from * exiting. */ - @SuppressWarnings("removal") public Target(Remote impl, Dispatcher disp, Remote stub, ObjID id, boolean permanent) { @@ -94,7 +87,6 @@ public Target(Remote impl, Dispatcher disp, Remote stub, ObjID id, this.disp = disp; this.stub = stub; this.id = id; - this.acc = AccessController.getContext(); /* * Fix for 4149366: so that downloaded parameter types unmarshalled @@ -177,11 +169,6 @@ Dispatcher getDispatcher() { return disp; } - @SuppressWarnings("removal") - AccessControlContext getAccessControlContext() { - return acc; - } - ClassLoader getContextClassLoader() { return ccl; } @@ -307,7 +294,6 @@ synchronized void unreferenced(long sequenceNum, VMID vmid, boolean strong) /** * Remove endpoint from the reference set. */ - @SuppressWarnings("removal") private synchronized void refSetRemove(VMID vmid) { // remove notification request DGCImpl.getDGCImpl().unregisterTarget(vmid, this); @@ -325,17 +311,12 @@ private synchronized void refSetRemove(VMID vmid) { * invoke its unreferenced callback in a separate thread. */ Remote obj = getImpl(); - if (obj instanceof Unreferenced) { - final Unreferenced unrefObj = (Unreferenced) obj; - AccessController.doPrivileged( - new NewThreadAction(() -> { - Thread.currentThread().setContextClassLoader(ccl); - AccessController.doPrivileged((PrivilegedAction) () -> { - unrefObj.unreferenced(); - return null; - }, acc); - }, "Unreferenced-" + nextThreadNum++, false, true)).start(); - // REMIND: access to nextThreadNum not synchronized; you care? + if (obj instanceof Unreferenced unrefObj) { + new NewThreadAction(() -> { + Thread.currentThread().setContextClassLoader(ccl); + unrefObj.unreferenced(); + }, "Unreferenced-" + nextThreadNum++, false, true).run().start(); + // REMIND: access to nextThreadNum not synchronized; you care? } unpinImpl(); diff --git a/src/java.rmi/share/classes/sun/rmi/transport/Transport.java b/src/java.rmi/share/classes/sun/rmi/transport/Transport.java index 4589f913dd345..b617451718062 100644 --- a/src/java.rmi/share/classes/sun/rmi/transport/Transport.java +++ b/src/java.rmi/share/classes/sun/rmi/transport/Transport.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2024, 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 @@ -36,11 +36,6 @@ import java.rmi.server.RemoteCall; import java.rmi.server.RemoteServer; import java.rmi.server.ServerNotActiveException; -import java.security.AccessControlContext; -import java.security.AccessController; -import java.security.Permissions; -import java.security.PrivilegedAction; -import java.security.ProtectionDomain; import sun.rmi.runtime.Log; import sun.rmi.server.Dispatcher; import sun.rmi.server.UnicastServerRef; @@ -51,15 +46,14 @@ * * @author Ann Wollrath */ -@SuppressWarnings({"removal","deprecation"}) +@SuppressWarnings({"deprecation"}) public abstract class Transport { /** "transport" package log level */ static final int logLevel = LogStream.parseLevel(getLogLevel()); private static String getLogLevel() { - return java.security.AccessController.doPrivileged( - (PrivilegedAction) () -> System.getProperty("sun.rmi.transport.logLevel")); + return System.getProperty("sun.rmi.transport.logLevel"); } /* transport package log */ @@ -72,15 +66,6 @@ private static String getLogLevel() { /** ObjID for DGCImpl */ private static final ObjID dgcID = new ObjID(ObjID.DGC_ID); - /** AccessControlContext for setting context ClassLoader */ - private static final AccessControlContext SETCCL_ACC; - static { - Permissions perms = new Permissions(); - perms.add(new RuntimePermission("setContextClassLoader")); - ProtectionDomain[] pd = { new ProtectionDomain(null, perms) }; - SETCCL_ACC = new AccessControlContext(pd); - } - /** * Returns a Channel that generates connections to the * endpoint ep. A Channel is an object that creates and @@ -121,22 +106,11 @@ static Transport currentTransport() { return currentTransport.get(); } - /** - * Verify that the current access control context has permission to accept - * the connection being dispatched by the current thread. The current - * access control context is passed as a parameter to avoid the overhead of - * an additional call to AccessController.getContext. - */ - protected abstract void checkAcceptPermission(AccessControlContext acc); - /** * Sets the context class loader for the current thread. */ private static void setContextClassLoader(ClassLoader ccl) { - AccessController.doPrivileged((PrivilegedAction)() -> { - Thread.currentThread().setContextClassLoader(ccl); - return null; - }, SETCCL_ACC); + Thread.currentThread().setContextClassLoader(ccl); } /** @@ -183,27 +157,13 @@ public boolean serviceCall(final RemoteCall call) { /* call the dispatcher */ transportLog.log(Log.VERBOSE, "call dispatcher"); - final AccessControlContext acc = - target.getAccessControlContext(); ClassLoader ccl = target.getContextClassLoader(); - ClassLoader savedCcl = Thread.currentThread().getContextClassLoader(); try { if (ccl != savedCcl) setContextClassLoader(ccl); currentTransport.set(this); - try { - java.security.AccessController.doPrivileged( - new java.security.PrivilegedExceptionAction() { - public Void run() throws IOException { - checkAcceptPermission(acc); - disp.dispatch(impl, call); - return null; - } - }, acc); - } catch (java.security.PrivilegedActionException pae) { - throw (IOException) pae.getException(); - } + disp.dispatch(impl, call); } finally { if (ccl != savedCcl) setContextClassLoader(savedCcl); currentTransport.set(null); diff --git a/src/java.rmi/share/classes/sun/rmi/transport/tcp/TCPChannel.java b/src/java.rmi/share/classes/sun/rmi/transport/tcp/TCPChannel.java index 013fc1606af2d..91ef41d3e4944 100644 --- a/src/java.rmi/share/classes/sun/rmi/transport/tcp/TCPChannel.java +++ b/src/java.rmi/share/classes/sun/rmi/transport/tcp/TCPChannel.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2024, 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 @@ -27,18 +27,12 @@ import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; -import java.lang.ref.Reference; -import java.lang.ref.SoftReference; import java.net.Socket; import java.rmi.ConnectIOException; import java.rmi.RemoteException; -import java.security.AccessControlContext; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; -import java.util.WeakHashMap; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; @@ -70,42 +64,21 @@ public class TCPChannel implements Channel { /** connection acceptor (should be in TCPTransport) */ private ConnectionAcceptor acceptor; - /** most recently authorized AccessControlContext */ - @SuppressWarnings("removal") - private AccessControlContext okContext; - - /** cache of authorized AccessControlContexts */ - @SuppressWarnings("removal") - private WeakHashMap> authcache; - - /** the SecurityManager which authorized okContext and authcache */ - @SuppressWarnings("removal") - private SecurityManager cacheSecurityManager = null; - /** client-side connection idle usage timeout */ - @SuppressWarnings("removal") private static final long idleTimeout = // default 15 seconds - AccessController.doPrivileged((PrivilegedAction) () -> - Long.getLong("sun.rmi.transport.connectionTimeout", 15000)); + Long.getLong("sun.rmi.transport.connectionTimeout", 15000); /** client-side connection handshake read timeout */ - @SuppressWarnings("removal") private static final int handshakeTimeout = // default 1 minute - AccessController.doPrivileged((PrivilegedAction) () -> - Integer.getInteger("sun.rmi.transport.tcp.handshakeTimeout", 60000)); + Integer.getInteger("sun.rmi.transport.tcp.handshakeTimeout", 60000); /** client-side connection response read timeout (after handshake) */ - @SuppressWarnings("removal") private static final int responseTimeout = // default infinity - AccessController.doPrivileged((PrivilegedAction) () -> - Integer.getInteger("sun.rmi.transport.tcp.responseTimeout", 0)); + Integer.getInteger("sun.rmi.transport.tcp.responseTimeout", 0); /** thread pool for scheduling delayed tasks */ - @SuppressWarnings("removal") private static final ScheduledExecutorService scheduler = - AccessController.doPrivileged( - new RuntimeUtil.GetInstanceAction()).getScheduler(); + RuntimeUtil.getInstance().getScheduler(); /** * Create channel for endpoint. @@ -122,41 +95,6 @@ public Endpoint getEndpoint() { return ep; } - /** - * Checks if the current caller has sufficient privilege to make - * a connection to the remote endpoint. - * @exception SecurityException if caller is not allowed to use this - * Channel. - */ - @SuppressWarnings("removal") - private void checkConnectPermission() throws SecurityException { - SecurityManager security = System.getSecurityManager(); - if (security == null) - return; - - if (security != cacheSecurityManager) { - // The security manager changed: flush the cache - okContext = null; - authcache = new WeakHashMap>(); - cacheSecurityManager = security; - } - - AccessControlContext ctx = AccessController.getContext(); - - // If ctx is the same context as last time, or if it - // appears in the cache, bypass the checkConnect. - if (okContext == null || - !(okContext.equals(ctx) || authcache.containsKey(ctx))) - { - security.checkConnect(ep.getHost(), ep.getPort()); - authcache.put(ctx, new SoftReference(ctx)); - // A WeakHashMap is transformed into a SoftHashSet by making - // each value softly refer to its own key (Peter's idea). - } - okContext = ctx; - } - /** * Supplies a connection to the endpoint of the address space * for which this is a channel. The returned connection may @@ -175,10 +113,6 @@ public Connection newConnection() throws RemoteException { int elementPos = freeList.size()-1; if (elementPos >= 0) { - // If there is a security manager, make sure - // the caller is allowed to connect to the - // requested endpoint. - checkConnectPermission(); conn = freeList.get(elementPos); freeList.remove(elementPos); } @@ -467,11 +401,9 @@ public ConnectionAcceptor(TCPTransport transport) { * Start a new thread to accept connections. */ public void startNewAcceptor() { - @SuppressWarnings("removal") - Thread t = AccessController.doPrivileged( - new NewThreadAction(ConnectionAcceptor.this, - "TCPChannel Accept-" + ++ threadNum, - true)); + Thread t = new NewThreadAction(ConnectionAcceptor.this, + "TCPChannel Accept-" + ++ threadNum, + true).run(); t.start(); } diff --git a/src/java.rmi/share/classes/sun/rmi/transport/tcp/TCPEndpoint.java b/src/java.rmi/share/classes/sun/rmi/transport/tcp/TCPEndpoint.java index b2c0f189845e2..4eb1a35a95ef3 100644 --- a/src/java.rmi/share/classes/sun/rmi/transport/tcp/TCPEndpoint.java +++ b/src/java.rmi/share/classes/sun/rmi/transport/tcp/TCPEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2024, 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 @@ -38,8 +38,6 @@ import java.rmi.server.RMIClientSocketFactory; import java.rmi.server.RMIServerSocketFactory; import java.rmi.server.RMISocketFactory; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; @@ -79,27 +77,19 @@ public class TCPEndpoint implements Endpoint { /** true if real local host name is known yet */ private static boolean localHostKnown; - // this should be a *private* method since it is privileged - @SuppressWarnings("removal") private static int getInt(String name, int def) { - return AccessController.doPrivileged( - (PrivilegedAction) () -> Integer.getInteger(name, def)); + return Integer.getInteger(name, def); } - // this should be a *private* method since it is privileged - @SuppressWarnings("removal") private static boolean getBoolean(String name) { - return AccessController.doPrivileged( - (PrivilegedAction) () -> Boolean.getBoolean(name)); + return Boolean.getBoolean(name); } /** * Returns the value of the java.rmi.server.hostname property. */ - @SuppressWarnings("removal") private static String getHostnameProperty() { - return AccessController.doPrivileged( - (PrivilegedAction) () -> System.getProperty("java.rmi.server.hostname")); + return System.getProperty("java.rmi.server.hostname"); } /** @@ -762,9 +752,7 @@ static String attemptFQDN(InetAddress localAddr) private void getFQDN() { /* FQDN finder will run in RMI threadgroup. */ - @SuppressWarnings("removal") - Thread t = AccessController.doPrivileged( - new NewThreadAction(FQDN.this, "FQDN Finder", true)); + Thread t = new NewThreadAction(FQDN.this, "FQDN Finder", true).run(); t.start(); } diff --git a/src/java.rmi/share/classes/sun/rmi/transport/tcp/TCPTransport.java b/src/java.rmi/share/classes/sun/rmi/transport/tcp/TCPTransport.java index dba0f9f8f60c0..9695fcac2747a 100644 --- a/src/java.rmi/share/classes/sun/rmi/transport/tcp/TCPTransport.java +++ b/src/java.rmi/share/classes/sun/rmi/transport/tcp/TCPTransport.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2024, 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 @@ -25,7 +25,6 @@ package sun.rmi.transport.tcp; import java.lang.ref.Reference; -import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.UndeclaredThrowableException; @@ -47,11 +46,6 @@ import java.rmi.server.RemoteCall; import java.rmi.server.ServerNotActiveException; import java.rmi.server.UID; -import java.security.AccessControlContext; -import java.security.AccessController; -import java.security.Permissions; -import java.security.PrivilegedAction; -import java.security.ProtectionDomain; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; @@ -67,7 +61,6 @@ import java.util.concurrent.atomic.AtomicInteger; import sun.rmi.runtime.Log; import sun.rmi.runtime.NewThreadAction; -import sun.rmi.transport.Channel; import sun.rmi.transport.Connection; import sun.rmi.transport.DGCAckHandler; import sun.rmi.transport.Endpoint; @@ -87,23 +80,16 @@ public class TCPTransport extends Transport { /* tcp package log */ - @SuppressWarnings("removal") static final Log tcpLog = Log.getLog("sun.rmi.transport.tcp", "tcp", - LogStream.parseLevel(AccessController.doPrivileged( - (PrivilegedAction) () -> System.getProperty("sun.rmi.transport.tcp.logLevel")))); + LogStream.parseLevel(System.getProperty("sun.rmi.transport.tcp.logLevel"))); /** maximum number of connection handler threads */ - @SuppressWarnings("removal") private static final int maxConnectionThreads = // default no limit - AccessController.doPrivileged((PrivilegedAction) () -> - Integer.getInteger("sun.rmi.transport.tcp.maxConnectionThreads", - Integer.MAX_VALUE)); + Integer.getInteger("sun.rmi.transport.tcp.maxConnectionThreads", Integer.MAX_VALUE); /** keep alive time for idle connection handler threads */ - @SuppressWarnings("removal") private static final long threadKeepAliveTime = // default 1 minute - AccessController.doPrivileged((PrivilegedAction) () -> - Long.getLong("sun.rmi.transport.tcp.threadKeepAliveTime", 60000)); + Long.getLong("sun.rmi.transport.tcp.threadKeepAliveTime", 60000); /** thread pool for connection handlers */ private static final ExecutorService connectionThreadPool = @@ -111,10 +97,9 @@ public class TCPTransport extends Transport { threadKeepAliveTime, TimeUnit.MILLISECONDS, new SynchronousQueue(), new ThreadFactory() { - @SuppressWarnings("removal") public Thread newThread(Runnable runnable) { - return AccessController.doPrivileged(new NewThreadAction( - runnable, "TCP Connection(idle)", true, true)); + return new NewThreadAction( + runnable, "TCP Connection(idle)", true, true).run(); } }); @@ -125,17 +110,6 @@ public Thread newThread(Runnable runnable) { private static final ThreadLocal threadConnectionHandler = new ThreadLocal<>(); - /** an AccessControlContext with no permissions */ - @SuppressWarnings("removal") - private static final AccessControlContext NOPERMS_ACC = createNopermsAcc(); - - @SuppressWarnings("removal") - private static AccessControlContext createNopermsAcc() { - Permissions perms = new Permissions(); - ProtectionDomain[] pd = { new ProtectionDomain(null, perms) }; - return new AccessControlContext(pd); - } - /** endpoints for this transport */ private final LinkedList epList; /** number of objects exported on this transport */ @@ -149,16 +123,15 @@ private static AccessControlContext createNopermsAcc() { static final RMISocketFactory defaultSocketFactory = RMISocketFactory.getDefaultSocketFactory(); - /** number of milliseconds in accepted-connection timeout. + /** + * Number of milliseconds in accepted-connection timeout. * Warning: this should be greater than 15 seconds (the client-side * timeout), and defaults to 2 hours. * The maximum representable value is slightly more than 24 days * and 20 hours. */ - @SuppressWarnings("removal") private static final int connectionReadTimeout = // default 2 hours - AccessController.doPrivileged((PrivilegedAction) () -> - Integer.getInteger("sun.rmi.transport.tcp.readTimeout", 2 * 3600 * 1000)); + Integer.getInteger("sun.rmi.transport.tcp.readTimeout", 2 * 3600 * 1000); /** * Constructs a TCPTransport. @@ -302,24 +275,6 @@ private void decrementExportCount() { } } - /** - * Verify that the current access control context has permission to - * accept the connection being dispatched by the current thread. - */ - protected void checkAcceptPermission(@SuppressWarnings("removal") AccessControlContext acc) { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm == null) { - return; - } - ConnectionHandler h = threadConnectionHandler.get(); - if (h == null) { - throw new Error( - "checkAcceptPermission not in ConnectionHandler thread"); - } - h.checkAcceptPermission(sm, acc); - } - private TCPEndpoint getEndpoint() { synchronized (epList) { return epList.getLast(); @@ -327,7 +282,8 @@ private TCPEndpoint getEndpoint() { } /** - * Listen on transport's endpoint. + * Listen on transport's endpoint. Do nothing if a server socket + * and listening thread already exist. */ private void listen() throws RemoteException { assert Thread.holdsLock(this); @@ -347,24 +303,14 @@ private void listen() throws RemoteException { * "port in use" will cause export to hang if an * RMIFailureHandler is not installed. */ - @SuppressWarnings("removal") - Thread t = AccessController.doPrivileged( - new NewThreadAction(new AcceptLoop(server), - "TCP Accept-" + port, true)); + Thread t = new NewThreadAction(new AcceptLoop(server), + "TCP Accept-" + port, true).run(); t.start(); } catch (java.net.BindException e) { throw new ExportException("Port already in use: " + port, e); } catch (IOException e) { throw new ExportException("Listen failed on port: " + port, e); } - - } else { - // otherwise verify security access to existing server socket - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkListen(port); - } } } @@ -656,17 +602,6 @@ private class ConnectionHandler implements Runnable { * make this once-reviled tactic again socially acceptable) */ private static final int POST = 0x504f5354; - /** most recently accept-authorized AccessControlContext */ - @SuppressWarnings("removal") - private AccessControlContext okContext; - /** cache of accept-authorized AccessControlContexts */ - @SuppressWarnings("removal") - private Map> authCache; - /** security manager which authorized contexts in authCache */ - @SuppressWarnings("removal") - private SecurityManager cacheSecurityManager = null; - private Socket socket; private String remoteHost; @@ -679,37 +614,6 @@ String getClientHost() { return remoteHost; } - /** - * Verify that the given AccessControlContext has permission to - * accept this connection. - */ - @SuppressWarnings("removal") - void checkAcceptPermission(SecurityManager sm, - AccessControlContext acc) - { - /* - * Note: no need to synchronize on cache-related fields, since this - * method only gets called from the ConnectionHandler's thread. - */ - if (sm != cacheSecurityManager) { - okContext = null; - authCache = new WeakHashMap>(); - cacheSecurityManager = sm; - } - if (acc.equals(okContext) || authCache.containsKey(acc)) { - return; - } - InetAddress addr = socket.getInetAddress(); - String host = (addr != null) ? addr.getHostAddress() : "*"; - - sm.checkAccept(host, socket.getPort()); - - authCache.put(acc, new SoftReference(acc)); - okContext = acc; - } - - @SuppressWarnings("removal") public void run() { Thread t = Thread.currentThread(); String name = t.getName(); @@ -717,10 +621,7 @@ public void run() { t.setName("RMI TCP Connection(" + connectionCount.incrementAndGet() + ")-" + remoteHost); - AccessController.doPrivileged((PrivilegedAction)() -> { - run0(); - return null; - }, NOPERMS_ACC); + run0(); } finally { t.setName(name); } From 3328b4ecf225f95edfce6ab848dcfb62ddc1aaff Mon Sep 17 00:00:00 2001 From: Sonia Zaldana Calles Date: Tue, 19 Nov 2024 19:13:09 +0000 Subject: [PATCH 21/74] 8343700: ceil_log2 should not loop endlessly Reviewed-by: shade, kbarrett, aph, stuefe --- src/hotspot/share/classfile/dictionary.cpp | 2 +- src/hotspot/share/utilities/powerOfTwo.hpp | 9 ++-- .../gtest/utilities/test_powerOfTwo.cpp | 43 ++++++++++++++++++- 3 files changed, 47 insertions(+), 7 deletions(-) diff --git a/src/hotspot/share/classfile/dictionary.cpp b/src/hotspot/share/classfile/dictionary.cpp index 73d58ac368739..92f362860ebce 100644 --- a/src/hotspot/share/classfile/dictionary.cpp +++ b/src/hotspot/share/classfile/dictionary.cpp @@ -44,7 +44,7 @@ const size_t REHASH_LEN = 100; Dictionary::Dictionary(ClassLoaderData* loader_data, size_t table_size) : _number_of_entries(0), _loader_data(loader_data) { - size_t start_size_log_2 = MAX2(ceil_log2(table_size), (size_t)2); // 2 is minimum size even though some dictionaries only have one entry + size_t start_size_log_2 = MAX2(ceil_log2(table_size), 2); // 2 is minimum size even though some dictionaries only have one entry size_t current_size = ((size_t)1) << start_size_log_2; log_info(class, loader, data)("Dictionary start size: " SIZE_FORMAT " (" SIZE_FORMAT ")", current_size, start_size_log_2); diff --git a/src/hotspot/share/utilities/powerOfTwo.hpp b/src/hotspot/share/utilities/powerOfTwo.hpp index 786977a347f74..6c1e413f403fc 100644 --- a/src/hotspot/share/utilities/powerOfTwo.hpp +++ b/src/hotspot/share/utilities/powerOfTwo.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2024, 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 @@ -122,10 +122,9 @@ inline T next_power_of_2(T value) { // Find log2 value greater than this input template ::value)> -inline T ceil_log2(T value) { - T ret; - for (ret = 1; ((T)1 << ret) < value; ++ret); - return ret; +inline int ceil_log2(T value) { + assert(value > 0, "Invalid value"); + return log2i_graceful(value - 1) + 1; } // Return the largest power of two that is a submultiple of the given value. diff --git a/test/hotspot/gtest/utilities/test_powerOfTwo.cpp b/test/hotspot/gtest/utilities/test_powerOfTwo.cpp index 4d16e13ab312e..fc4080bcefd10 100644 --- a/test/hotspot/gtest/utilities/test_powerOfTwo.cpp +++ b/test/hotspot/gtest/utilities/test_powerOfTwo.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2024, 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 @@ -305,3 +305,44 @@ TEST(power_of_2, log2i) { check_log2i_variants_for((uint)0); check_log2i_variants_for((jlong)0); } + +template void test_ceil_log2() { + EXPECT_EQ(ceil_log2(T(1)), 0) << "value = " << T(1); + EXPECT_EQ(ceil_log2(T(2)), 1) << "value = " << T(2); + EXPECT_EQ(ceil_log2(T(3)), 2) << "value = " << T(3); + EXPECT_EQ(ceil_log2(T(4)), 2) << "value = " << T(4); + EXPECT_EQ(ceil_log2(T(5)), 3) << "value = " << T(5); + EXPECT_EQ(ceil_log2(T(6)), 3) << "value = " << T(6); + EXPECT_EQ(ceil_log2(T(7)), 3) << "value = " << T(7); + EXPECT_EQ(ceil_log2(T(8)), 3) << "value = " << T(8); + EXPECT_EQ(ceil_log2(T(9)), 4) << "value = " << T(9); + EXPECT_EQ(ceil_log2(T(10)), 4) << "value = " << T(10); + + // Test max values + if (std::is_unsigned::value) { + EXPECT_EQ(ceil_log2(std::numeric_limits::max()), + (int)(sizeof(T) * 8)) << "value = " << std::numeric_limits::max(); + } else { + EXPECT_EQ(ceil_log2(std::numeric_limits::max()), + (int)(sizeof(T) * 8 - 1)) << "value = " << std::numeric_limits::max(); + } +} + +TEST(power_of_2, ceil_log2) { + test_ceil_log2(); + test_ceil_log2(); + test_ceil_log2(); + test_ceil_log2(); + test_ceil_log2(); + test_ceil_log2(); + test_ceil_log2(); + test_ceil_log2(); +} + +#ifdef ASSERT +TEST_VM_ASSERT_MSG(power_of_2, ceil_log2_invalid, + ".*Invalid value") { + ceil_log2(0); +} + +#endif // ASSERT From 69c9f2566ea36fa3317d762d4498637489c70c45 Mon Sep 17 00:00:00 2001 From: Phil Race Date: Tue, 19 Nov 2024 19:35:28 +0000 Subject: [PATCH 22/74] 8344061: Remove doPrivileged calls from shared implementation code in the java.desktop module : part 2 Reviewed-by: aivanov --- .../classes/sun/awt/AWTAutoShutdown.java | 18 +- .../share/classes/sun/awt/AppContext.java | 192 ++---- .../classes/sun/awt/CausedFocusEvent.java | 19 +- .../share/classes/sun/awt/DebugSettings.java | 13 +- .../classes/sun/awt/FontConfiguration.java | 37 +- .../share/classes/sun/awt/FontDescriptor.java | 5 +- .../classes/sun/awt/NativeLibLoader.java | 10 +- .../sun/awt/datatransfer/DataTransferer.java | 83 +-- .../awt/datatransfer/TransferableProxy.java | 20 +- .../awt/im/ExecutableInputMethodManager.java | 31 +- .../classes/sun/awt/im/InputContext.java | 26 +- .../sun/awt/im/InputMethodContext.java | 5 +- .../classes/sun/font/CreatedFontTracker.java | 30 +- .../share/classes/sun/font/FileFont.java | 99 +-- .../sun/font/FontManagerNativeLibrary.java | 47 +- .../share/classes/sun/font/FontUtilities.java | 104 ++-- .../share/classes/sun/font/StrikeCache.java | 50 +- .../classes/sun/font/SunFontManager.java | 572 ++++++++---------- .../classes/sun/font/SunLayoutEngine.java | 7 +- .../share/classes/sun/font/TrueTypeFont.java | 22 +- .../share/classes/sun/font/Type1Font.java | 47 +- 21 files changed, 521 insertions(+), 916 deletions(-) diff --git a/src/java.desktop/share/classes/sun/awt/AWTAutoShutdown.java b/src/java.desktop/share/classes/sun/awt/AWTAutoShutdown.java index bb7fb64f7f109..e944d19e1c117 100644 --- a/src/java.desktop/share/classes/sun/awt/AWTAutoShutdown.java +++ b/src/java.desktop/share/classes/sun/awt/AWTAutoShutdown.java @@ -26,8 +26,6 @@ package sun.awt; import java.awt.AWTEvent; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.Map; @@ -333,17 +331,13 @@ static AWTEvent getShutdownEvent() { * Creates and starts a new blocker thread. Doesn't return until * the new blocker thread starts. */ - @SuppressWarnings("removal") private void activateBlockerThread() { - AccessController.doPrivileged((PrivilegedAction) () -> { - String name = "AWT-Shutdown"; - Thread thread = new Thread( - ThreadGroupUtils.getRootThreadGroup(), this, name, 0, false); - thread.setContextClassLoader(null); - thread.setDaemon(false); - blockerThread = thread; - return thread; - }).start(); + String name = "AWT-Shutdown"; + Thread thread = new Thread(ThreadGroupUtils.getRootThreadGroup(), this, name, 0, false); + thread.setContextClassLoader(null); + thread.setDaemon(false); + blockerThread = thread; + thread.start(); try { /* Wait for the blocker thread to start. */ mainLock.wait(); diff --git a/src/java.desktop/share/classes/sun/awt/AppContext.java b/src/java.desktop/share/classes/sun/awt/AppContext.java index fa098af556dbc..48482dfc39afc 100644 --- a/src/java.desktop/share/classes/sun/awt/AppContext.java +++ b/src/java.desktop/share/classes/sun/awt/AppContext.java @@ -32,8 +32,6 @@ import java.awt.Toolkit; import java.awt.GraphicsEnvironment; import java.awt.event.InvocationEvent; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.Collections; import java.util.HashMap; import java.util.IdentityHashMap; @@ -229,20 +227,13 @@ public boolean isDisposed() { * @see sun.awt.SunToolkit * @since 1.2 */ - @SuppressWarnings("removal") AppContext(ThreadGroup threadGroup) { numAppContexts.incrementAndGet(); this.threadGroup = threadGroup; threadGroup2appContext.put(threadGroup, this); - this.contextClassLoader = - AccessController.doPrivileged(new PrivilegedAction() { - public ClassLoader run() { - return Thread.currentThread().getContextClassLoader(); - } - }); - + this.contextClassLoader = Thread.currentThread().getContextClassLoader(); // Initialize push/pop lock and its condition to be used by all the // EventQueues within this AppContext Lock eventQueuePushPopLock = new ReentrantLock(); @@ -254,26 +245,19 @@ public ClassLoader run() { private static final ThreadLocal threadAppContext = new ThreadLocal(); - @SuppressWarnings("removal") private static void initMainAppContext() { // On the main Thread, we get the ThreadGroup, make a corresponding // AppContext, and instantiate the Java EventQueue. This way, legacy // code is unaffected by the move to multiple AppContext ability. - AccessController.doPrivileged(new PrivilegedAction() { - public Void run() { - ThreadGroup currentThreadGroup = - Thread.currentThread().getThreadGroup(); - ThreadGroup parentThreadGroup = currentThreadGroup.getParent(); - while (parentThreadGroup != null) { - // Find the root ThreadGroup to construct our main AppContext - currentThreadGroup = parentThreadGroup; - parentThreadGroup = currentThreadGroup.getParent(); - } + ThreadGroup currentThreadGroup = Thread.currentThread().getThreadGroup(); + ThreadGroup parentThreadGroup = currentThreadGroup.getParent(); + while (parentThreadGroup != null) { + // Find the root ThreadGroup to construct our main AppContext + currentThreadGroup = parentThreadGroup; + parentThreadGroup = currentThreadGroup.getParent(); + } - mainAppContext = SunToolkit.createNewAppContext(currentThreadGroup); - return null; - } - }); + mainAppContext = SunToolkit.createNewAppContext(currentThreadGroup); } /** @@ -284,7 +268,6 @@ public Void run() { * @see java.lang.ThreadGroup * @since 1.2 */ - @SuppressWarnings("removal") public static AppContext getAppContext() { // we are standalone app, return the main app context if (numAppContexts.get() == 1 && mainAppContext != null) { @@ -294,69 +277,53 @@ public static AppContext getAppContext() { AppContext appContext = threadAppContext.get(); if (null == appContext) { - appContext = AccessController.doPrivileged(new PrivilegedAction() - { - public AppContext run() { - // Get the current ThreadGroup, and look for it and its - // parents in the hash from ThreadGroup to AppContext -- - // it should be found, because we use createNewContext() - // when new AppContext objects are created. - ThreadGroup currentThreadGroup = Thread.currentThread().getThreadGroup(); - ThreadGroup threadGroup = currentThreadGroup; - - // Special case: we implicitly create the main app context - // if no contexts have been created yet. This covers standalone apps - // and excludes applets because by the time applet starts - // a number of contexts have already been created by the plugin. - synchronized (getAppContextLock) { - if (numAppContexts.get() == 0) { - if (System.getProperty("javaplugin.version") == null && - System.getProperty("javawebstart.version") == null) { - initMainAppContext(); - } else if (System.getProperty("javafx.version") != null && - threadGroup.getParent() != null) { - // Swing inside JavaFX case - SunToolkit.createNewAppContext(); - } - } + // Get the current ThreadGroup, and look for it and its + // parents in the hash from ThreadGroup to AppContext -- + // it should be found, because we use createNewContext() + // when new AppContext objects are created. + ThreadGroup currentThreadGroup = Thread.currentThread().getThreadGroup(); + ThreadGroup threadGroup = currentThreadGroup; + + // Special case: we implicitly create the main app context + // if no contexts have been created yet. This covers standalone apps + // and excludes applets because by the time applet starts + // a number of contexts have already been created by the plugin. + synchronized (getAppContextLock) { + if (numAppContexts.get() == 0) { + if (System.getProperty("javaplugin.version") == null && + System.getProperty("javawebstart.version") == null) { + initMainAppContext(); + } else if (System.getProperty("javafx.version") != null && + threadGroup.getParent() != null) { + // Swing inside JavaFX case + SunToolkit.createNewAppContext(); } + } + } - AppContext context = threadGroup2appContext.get(threadGroup); - while (context == null) { - threadGroup = threadGroup.getParent(); - if (threadGroup == null) { - // We've got up to the root thread group and did not find an AppContext - // Try to get it from the security manager - SecurityManager securityManager = System.getSecurityManager(); - if (securityManager != null) { - ThreadGroup smThreadGroup = securityManager.getThreadGroup(); - if (smThreadGroup != null) { - /* - * If we get this far then it's likely that - * the ThreadGroup does not actually belong - * to the applet, so do not cache it. - */ - return threadGroup2appContext.get(smThreadGroup); - } - } - return null; - } - context = threadGroup2appContext.get(threadGroup); - } + AppContext context = threadGroup2appContext.get(threadGroup); + while (context == null) { + threadGroup = threadGroup.getParent(); + if (threadGroup == null) { + // We've got up to the root thread group and did not find an AppContext + // We have nowhere else to look, and this is not supposed to happen. + // return null from this whole method. + return null; + } + context = threadGroup2appContext.get(threadGroup); + } - // In case we did anything in the above while loop, we add - // all the intermediate ThreadGroups to threadGroup2appContext - // so we won't spin again. - for (ThreadGroup tg = currentThreadGroup; tg != threadGroup; tg = tg.getParent()) { - threadGroup2appContext.put(tg, context); - } + // In case we did anything in the above while loop, we add + // all the intermediate ThreadGroups to threadGroup2appContext + // so we won't spin again. + for (ThreadGroup tg = currentThreadGroup; tg != threadGroup; tg = tg.getParent()) { + threadGroup2appContext.put(tg, context); + } - // Now we're done, so we cache the latest key/value pair. - threadAppContext.set(context); + // Now we're done, so we cache the latest key/value pair. + threadAppContext.set(context); - return context; - } - }); + appContext = context; } return appContext; @@ -395,7 +362,7 @@ public static boolean isMainContext(AppContext ctx) { * contained within this AppContext * @since 1.2 */ - @SuppressWarnings({"deprecation", "removal"}) + @SuppressWarnings("deprecation") public void dispose() throws IllegalThreadStateException { System.err.println( """ @@ -439,19 +406,13 @@ public void run() { log.finer("exception occurred while disposing app context", t); } } - AccessController.doPrivileged(new PrivilegedAction() { - public Void run() { - if (!GraphicsEnvironment.isHeadless() && SystemTray.isSupported()) - { - SystemTray systemTray = SystemTray.getSystemTray(); - TrayIcon[] trayIconsToDispose = systemTray.getTrayIcons(); - for (TrayIcon ti : trayIconsToDispose) { - systemTray.remove(ti); - } - } - return null; - } - }); + if (!GraphicsEnvironment.isHeadless() && SystemTray.isSupported()) { + SystemTray systemTray = SystemTray.getSystemTray(); + TrayIcon[] trayIconsToDispose = systemTray.getTrayIcons(); + for (TrayIcon ti : trayIconsToDispose) { + systemTray.remove(ti); + } + } // Alert PropertyChangeListeners that the GUI has been disposed. if (changeSupport != null) { changeSupport.firePropertyChange(GUI_DISPOSED, false, true); @@ -546,25 +507,6 @@ public void run() { } } - static final class CreateThreadAction implements PrivilegedAction { - private final AppContext appContext; - private final Runnable runnable; - - CreateThreadAction(AppContext ac, Runnable r) { - appContext = ac; - runnable = r; - } - - public Thread run() { - Thread t = new Thread(appContext.getThreadGroup(), - runnable, "AppContext Disposer", 0, false); - t.setContextClassLoader(appContext.getContextClassLoader()); - t.setPriority(Thread.NORM_PRIORITY + 1); - t.setDaemon(true); - return t; - } - } - static void stopEventDispatchThreads() { for (AppContext appContext: getAppContexts()) { if (appContext.isDisposed()) { @@ -576,9 +518,11 @@ static void stopEventDispatchThreads() { if (appContext != AppContext.getAppContext()) { // Create a thread that belongs to the thread group associated // with the AppContext and invokes EventQueue.postEvent. - PrivilegedAction action = new CreateThreadAction(appContext, r); - @SuppressWarnings("removal") - Thread thread = AccessController.doPrivileged(action); + Thread thread = new Thread(appContext.getThreadGroup(), + r, "AppContext Disposer", 0, false); + thread.setContextClassLoader(appContext.getContextClassLoader()); + thread.setPriority(Thread.NORM_PRIORITY + 1); + thread.setDaemon(true); thread.start(); } else { r.run(); @@ -806,14 +750,8 @@ public synchronized PropertyChangeListener[] getPropertyChangeListeners( // Set up JavaAWTAccess in SharedSecrets static { SharedSecrets.setJavaAWTAccess(new JavaAWTAccess() { - @SuppressWarnings("removal") private boolean hasRootThreadGroup(final AppContext ecx) { - return AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Boolean run() { - return ecx.threadGroup.getParent() == null; - } - }); + return ecx.threadGroup.getParent() == null; } /** diff --git a/src/java.desktop/share/classes/sun/awt/CausedFocusEvent.java b/src/java.desktop/share/classes/sun/awt/CausedFocusEvent.java index a19e4f394e191..2527eda11f6b9 100644 --- a/src/java.desktop/share/classes/sun/awt/CausedFocusEvent.java +++ b/src/java.desktop/share/classes/sun/awt/CausedFocusEvent.java @@ -30,8 +30,6 @@ import java.io.ObjectStreamException; import java.io.Serial; import java.lang.reflect.Field; -import java.security.AccessController; -import java.security.PrivilegedAction; /** * This class exists for deserialization compatibility only. @@ -72,7 +70,6 @@ private CausedFocusEvent(Component source, int id, boolean temporary, throw new IllegalStateException(); } - @SuppressWarnings("removal") @Serial Object readResolve() throws ObjectStreamException { FocusEvent.Cause newCause; @@ -119,17 +116,11 @@ Object readResolve() throws ObjectStreamException { focusEvent.setSource(null); try { final Field consumedField = FocusEvent.class.getField("consumed"); - AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Object run() { - consumedField.setAccessible(true); - try { - consumedField.set(focusEvent, consumed); - } catch (IllegalAccessException e) { - } - return null; - } - }); + consumedField.setAccessible(true); + try { + consumedField.set(focusEvent, consumed); + } catch (IllegalAccessException e) { + } } catch (NoSuchFieldException e) { } diff --git a/src/java.desktop/share/classes/sun/awt/DebugSettings.java b/src/java.desktop/share/classes/sun/awt/DebugSettings.java index 9d89b6519b7ed..b95ac44ba545c 100644 --- a/src/java.desktop/share/classes/sun/awt/DebugSettings.java +++ b/src/java.desktop/share/classes/sun/awt/DebugSettings.java @@ -108,18 +108,11 @@ public static DebugSettings getInstance() { * Load debug properties from file, then override * with any command line specified properties */ - @SuppressWarnings("removal") private synchronized void loadProperties() { // setup initial properties - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Void run() { - loadDefaultProperties(); - loadFileProperties(); - loadSystemProperties(); - return null; - } - }); + loadDefaultProperties(); + loadFileProperties(); + loadSystemProperties(); // echo the initial property settings to stdout if (log.isLoggable(PlatformLogger.Level.FINE)) { diff --git a/src/java.desktop/share/classes/sun/awt/FontConfiguration.java b/src/java.desktop/share/classes/sun/awt/FontConfiguration.java index 9fffa09ed6ccc..0054382e8f62b 100644 --- a/src/java.desktop/share/classes/sun/awt/FontConfiguration.java +++ b/src/java.desktop/share/classes/sun/awt/FontConfiguration.java @@ -35,8 +35,6 @@ import java.io.OutputStream; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; @@ -120,7 +118,7 @@ public FontConfiguration(SunFontManager fm, this.preferPropFonts = preferPropFonts; /* fontConfig should be initialised by default constructor, and * its data tables can be shared, since readFontConfigFile doesn't - * update any other state. Also avoid a doPrivileged block. + * update any other state. */ initFontConfig(); } @@ -156,20 +154,8 @@ public boolean fontFilesArePresent() { short fontNameID = compFontNameIDs[0][0][0]; short fileNameID = getComponentFileID(fontNameID); final String fileName = mapFileName(getComponentFileName(fileNameID)); - @SuppressWarnings("removal") - Boolean exists = java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Boolean run() { - try { - File f = new File(fileName); - return Boolean.valueOf(f.exists()); - } - catch (Exception e) { - return Boolean.FALSE; - } - } - }); - return exists.booleanValue(); + File f = new File(fileName); + return f.exists(); } private void findFontConfigFile() { @@ -960,18 +946,11 @@ private CharsetEncoder getFontCharsetEncoder(final String charsetName, !charsetName.startsWith("sun.font.")) { fc = Charset.forName(charsetName); } else { - @SuppressWarnings("removal") - Class fcc = AccessController.doPrivileged(new PrivilegedAction>() { - public Class run() { - try { - return Class.forName(charsetName, true, - ClassLoader.getSystemClassLoader()); - } catch (ClassNotFoundException e) { - } - return null; - } - }); - + Class fcc = null; + try { + fcc = Class.forName(charsetName, true, ClassLoader.getSystemClassLoader()); + } catch (ClassNotFoundException e) { + } if (fcc != null) { try { fc = (Charset) fcc.getDeclaredConstructor().newInstance(); diff --git a/src/java.desktop/share/classes/sun/awt/FontDescriptor.java b/src/java.desktop/share/classes/sun/awt/FontDescriptor.java index 046ecce16daa7..4a16cd8d811ee 100644 --- a/src/java.desktop/share/classes/sun/awt/FontDescriptor.java +++ b/src/java.desktop/share/classes/sun/awt/FontDescriptor.java @@ -120,10 +120,7 @@ public boolean useUnicode() { } static boolean isLE; static { - @SuppressWarnings("removal") - String enc = java.security.AccessController.doPrivileged( - new sun.security.action.GetPropertyAction("sun.io.unicode.encoding", - "UnicodeBig")); + String enc = System.getProperty("sun.io.unicode.encoding", "UnicodeBig"); isLE = !"UnicodeBig".equals(enc); } } diff --git a/src/java.desktop/share/classes/sun/awt/NativeLibLoader.java b/src/java.desktop/share/classes/sun/awt/NativeLibLoader.java index 868ebdf3699bd..4bb49ae0b10eb 100644 --- a/src/java.desktop/share/classes/sun/awt/NativeLibLoader.java +++ b/src/java.desktop/share/classes/sun/awt/NativeLibLoader.java @@ -52,14 +52,8 @@ class NativeLibLoader { * For now, we know it's done by the implementation, and we assume * that the name of the library is "awt". -br. */ - @SuppressWarnings({"removal", "restricted"}) + @SuppressWarnings("restricted") static void loadLibraries() { - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Void run() { - System.loadLibrary("awt"); - return null; - } - }); + System.loadLibrary("awt"); } } diff --git a/src/java.desktop/share/classes/sun/awt/datatransfer/DataTransferer.java b/src/java.desktop/share/classes/sun/awt/datatransfer/DataTransferer.java index 23520de9eea2f..5014bb78ead64 100644 --- a/src/java.desktop/share/classes/sun/awt/datatransfer/DataTransferer.java +++ b/src/java.desktop/share/classes/sun/awt/datatransfer/DataTransferer.java @@ -62,10 +62,6 @@ import java.nio.charset.CharsetEncoder; import java.nio.charset.IllegalCharsetNameException; import java.nio.charset.UnsupportedCharsetException; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; import java.security.ProtectionDomain; import java.util.AbstractMap; import java.util.ArrayList; @@ -985,7 +981,6 @@ private static byte[] convertObjectToBytes(Object object) throws IOException { @SuppressWarnings("removal") private String removeSuspectedData(DataFlavor flavor, final Transferable contents, final String str) - throws IOException { if (null == System.getSecurityManager() || !flavor.isMimeTypeEqual("text/uri-list")) @@ -994,34 +989,25 @@ private String removeSuspectedData(DataFlavor flavor, final Transferable content } final ProtectionDomain userProtectionDomain = getUserProtectionDomain(contents); + StringBuilder allowedFiles = new StringBuilder(str.length()); + String [] uriArray = str.split("(\\s)+"); - try { - return AccessController.doPrivileged((PrivilegedExceptionAction) () -> { - - StringBuilder allowedFiles = new StringBuilder(str.length()); - String [] uriArray = str.split("(\\s)+"); - - for (String fileName : uriArray) + for (String fileName : uriArray) + { + File file = new File(fileName); + if (file.exists() && + !(isFileInWebstartedCache(file) || + isForbiddenToRead(file, userProtectionDomain))) + { + if (0 != allowedFiles.length()) { - File file = new File(fileName); - if (file.exists() && - !(isFileInWebstartedCache(file) || - isForbiddenToRead(file, userProtectionDomain))) - { - if (0 != allowedFiles.length()) - { - allowedFiles.append("\\r\\n"); - } - - allowedFiles.append(fileName); - } + allowedFiles.append("\\r\\n"); } - return allowedFiles.toString(); - }); - } catch (PrivilegedActionException pae) { - throw new IOException(pae.getMessage(), pae); + allowedFiles.append(fileName); + } } + return allowedFiles.toString(); } private static ProtectionDomain getUserProtectionDomain(Transferable contents) { @@ -1047,25 +1033,19 @@ private boolean isForbiddenToRead (File file, ProtectionDomain protectionDomain) @SuppressWarnings("removal") private ArrayList castToFiles(final List files, final ProtectionDomain userProtectionDomain) throws IOException { - try { - return AccessController.doPrivileged((PrivilegedExceptionAction>) () -> { - ArrayList fileList = new ArrayList<>(); - for (Object fileObject : files) - { - File file = castToFile(fileObject); - if (file != null && - (null == System.getSecurityManager() || - !(isFileInWebstartedCache(file) || - isForbiddenToRead(file, userProtectionDomain)))) - { - fileList.add(file.getCanonicalPath()); - } - } - return fileList; - }); - } catch (PrivilegedActionException pae) { - throw new IOException(pae.getMessage()); + ArrayList fileList = new ArrayList<>(); + for (Object fileObject : files) + { + File file = castToFile(fileObject); + if (file != null && + (null == System.getSecurityManager() || + !(isFileInWebstartedCache(file) || + isForbiddenToRead(file, userProtectionDomain)))) + { + fileList.add(file.getCanonicalPath()); + } } + return fileList; } // It is important do not use user's successors @@ -1419,7 +1399,6 @@ public Object translateStream(InputStream str, DataFlavor flavor, * and also arbitrary Objects which have a constructor which takes an * instance of the Class as its sole parameter. */ - @SuppressWarnings("removal") private Object constructFlavoredObject(Object arg, DataFlavor flavor, Class clazz) throws IOException @@ -1429,15 +1408,7 @@ private Object constructFlavoredObject(Object arg, DataFlavor flavor, if (clazz.equals(dfrc)) { return arg; // simple case } else { - Constructor[] constructors; - - try { - constructors = AccessController.doPrivileged( - (PrivilegedAction[]>) dfrc::getConstructors); - } catch (SecurityException se) { - throw new IOException(se.getMessage()); - } - + Constructor[] constructors = dfrc.getConstructors(); Constructor constructor = Stream.of(constructors) .filter(c -> Modifier.isPublic(c.getModifiers())) .filter(c -> { diff --git a/src/java.desktop/share/classes/sun/awt/datatransfer/TransferableProxy.java b/src/java.desktop/share/classes/sun/awt/datatransfer/TransferableProxy.java index cf8660fa8faf2..fffb3f98a3eb6 100644 --- a/src/java.desktop/share/classes/sun/awt/datatransfer/TransferableProxy.java +++ b/src/java.desktop/share/classes/sun/awt/datatransfer/TransferableProxy.java @@ -38,8 +38,6 @@ import java.io.OutputStream; import java.lang.reflect.Modifier; import java.lang.reflect.Proxy; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.HashMap; import java.util.HashSet; import java.util.Map; @@ -111,28 +109,14 @@ final class ClassLoaderObjectOutputStream extends ObjectOutputStream { } protected void annotateClass(final Class cl) throws IOException { - @SuppressWarnings("removal") - ClassLoader classLoader = AccessController.doPrivileged( - new PrivilegedAction() { - public ClassLoader run() { - return cl.getClassLoader(); - } - }); - + ClassLoader classLoader = cl.getClassLoader(); Set s = new HashSet(1); s.add(cl.getName()); map.put(s, classLoader); } protected void annotateProxyClass(final Class cl) throws IOException { - @SuppressWarnings("removal") - ClassLoader classLoader = AccessController.doPrivileged( - new PrivilegedAction() { - public ClassLoader run() { - return cl.getClassLoader(); - } - }); - + ClassLoader classLoader = cl.getClassLoader(); Class[] interfaces = cl.getInterfaces(); Set s = new HashSet(interfaces.length); for (int i = 0; i < interfaces.length; i++) { diff --git a/src/java.desktop/share/classes/sun/awt/im/ExecutableInputMethodManager.java b/src/java.desktop/share/classes/sun/awt/im/ExecutableInputMethodManager.java index 3696d53945bfb..b937fb139a394 100644 --- a/src/java.desktop/share/classes/sun/awt/im/ExecutableInputMethodManager.java +++ b/src/java.desktop/share/classes/sun/awt/im/ExecutableInputMethodManager.java @@ -41,10 +41,6 @@ import java.awt.event.InvocationEvent; import java.awt.im.spi.InputMethodDescriptor; import java.lang.reflect.InvocationTargetException; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; import java.util.Hashtable; import java.util.Iterator; import java.util.Locale; @@ -252,24 +248,14 @@ private synchronized void waitForChangeRequest() { * initializes the input method locator list for all * installed input method descriptors. */ - @SuppressWarnings("removal") private void initializeInputMethodLocatorList() { synchronized (javaInputMethodLocatorList) { javaInputMethodLocatorList.clear(); - try { - AccessController.doPrivileged(new PrivilegedExceptionAction() { - public Object run() { - for (InputMethodDescriptor descriptor : - ServiceLoader.load(InputMethodDescriptor.class, - ClassLoader.getSystemClassLoader())) { - ClassLoader cl = descriptor.getClass().getClassLoader(); - javaInputMethodLocatorList.add(new InputMethodLocator(descriptor, cl, null)); - } - return null; - } - }); - } catch (PrivilegedActionException e) { - e.printStackTrace(); + for (InputMethodDescriptor descriptor : + ServiceLoader.load(InputMethodDescriptor.class, + ClassLoader.getSystemClassLoader())) { + ClassLoader cl = descriptor.getClass().getClassLoader(); + javaInputMethodLocatorList.add(new InputMethodLocator(descriptor, cl, null)); } javaInputMethodCount = javaInputMethodLocatorList.size(); } @@ -594,13 +580,8 @@ private void writePreferredInputMethod(String path, String descriptorName) { } } - @SuppressWarnings("removal") private Preferences getUserRoot() { - return AccessController.doPrivileged(new PrivilegedAction() { - public Preferences run() { - return Preferences.userRoot(); - } - }); + return Preferences.userRoot(); } private Locale getAdvertisedLocale(InputMethodLocator locator, Locale locale) { diff --git a/src/java.desktop/share/classes/sun/awt/im/InputContext.java b/src/java.desktop/share/classes/sun/awt/im/InputContext.java index 6d3dc248abf93..00703eb44c32f 100644 --- a/src/java.desktop/share/classes/sun/awt/im/InputContext.java +++ b/src/java.desktop/share/classes/sun/awt/im/InputContext.java @@ -44,8 +44,6 @@ import java.awt.im.InputMethodRequests; import java.awt.im.spi.InputMethod; import java.lang.Character.Subset; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.text.MessageFormat; import java.util.Collection; import java.util.HashMap; @@ -1036,22 +1034,16 @@ public void windowDeactivated(WindowEvent e) {} /** * Initializes the input method selection key definition in preference trees */ - @SuppressWarnings("removal") private void initializeInputMethodSelectionKey() { - AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { - // Look in user's tree - Preferences root = Preferences.userRoot(); - inputMethodSelectionKey = getInputMethodSelectionKeyStroke(root); - - if (inputMethodSelectionKey == null) { - // Look in system's tree - root = Preferences.systemRoot(); - inputMethodSelectionKey = getInputMethodSelectionKeyStroke(root); - } - return null; - } - }); + // Look in user's tree + Preferences root = Preferences.userRoot(); + inputMethodSelectionKey = getInputMethodSelectionKeyStroke(root); + + if (inputMethodSelectionKey == null) { + // Look in system's tree + root = Preferences.systemRoot(); + inputMethodSelectionKey = getInputMethodSelectionKeyStroke(root); + } } private AWTKeyStroke getInputMethodSelectionKeyStroke(Preferences root) { diff --git a/src/java.desktop/share/classes/sun/awt/im/InputMethodContext.java b/src/java.desktop/share/classes/sun/awt/im/InputMethodContext.java index 96d531787832c..a0f9baa3112cb 100644 --- a/src/java.desktop/share/classes/sun/awt/im/InputMethodContext.java +++ b/src/java.desktop/share/classes/sun/awt/im/InputMethodContext.java @@ -37,7 +37,6 @@ import java.awt.font.TextHitInfo; import java.awt.im.InputMethodRequests; import java.awt.im.spi.InputMethod; -import java.security.AccessController; import java.text.AttributedCharacterIterator; import java.text.AttributedCharacterIterator.Attribute; import java.text.AttributedString; @@ -72,9 +71,7 @@ public class InputMethodContext static { // check whether we should use below-the-spot input // get property from command line - @SuppressWarnings("removal") - String inputStyle = AccessController.doPrivileged - (new GetPropertyAction("java.awt.im.style", null)); + String inputStyle = System.getProperty("java.awt.im.style"); // get property from awt.properties file if (inputStyle == null) { inputStyle = Toolkit.getProperty("java.awt.im.style", null); diff --git a/src/java.desktop/share/classes/sun/font/CreatedFontTracker.java b/src/java.desktop/share/classes/sun/font/CreatedFontTracker.java index 61f48e8d0985e..a144f14f4a9cb 100644 --- a/src/java.desktop/share/classes/sun/font/CreatedFontTracker.java +++ b/src/java.desktop/share/classes/sun/font/CreatedFontTracker.java @@ -27,8 +27,6 @@ import java.io.File; import java.io.OutputStream; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Semaphore; @@ -112,25 +110,21 @@ private static class TempFileDeletionHook { private static HashMap files = new HashMap<>(); private static Thread t = null; - @SuppressWarnings("removal") static void init() { if (t == null) { // Add a shutdown hook to remove the temp file. - AccessController.doPrivileged((PrivilegedAction) () -> { - /* The thread must be a member of a thread group - * which will not get GCed before VM exit. - * Make its parent the top-level thread group. - */ - ThreadGroup rootTG = ThreadGroupUtils.getRootThreadGroup(); - t = new Thread(rootTG, TempFileDeletionHook::runHooks, - "TempFontFileDeleter", 0, false); - /* Set context class loader to null in order to avoid - * keeping a strong reference to an application classloader. - */ - t.setContextClassLoader(null); - Runtime.getRuntime().addShutdownHook(t); - return null; - }); + /* The thread must be a member of a thread group + * which will not get GCed before VM exit. + * Make its parent the top-level thread group. + */ + ThreadGroup rootTG = ThreadGroupUtils.getRootThreadGroup(); + t = new Thread(rootTG, TempFileDeletionHook::runHooks, + "TempFontFileDeleter", 0, false); + /* Set context class loader to null in order to avoid + * keeping a strong reference to an application classloader. + */ + t.setContextClassLoader(null); + Runtime.getRuntime().addShutdownHook(t); } } diff --git a/src/java.desktop/share/classes/sun/font/FileFont.java b/src/java.desktop/share/classes/sun/font/FileFont.java index da5874518fa59..47c6ea181f477 100644 --- a/src/java.desktop/share/classes/sun/font/FileFont.java +++ b/src/java.desktop/share/classes/sun/font/FileFont.java @@ -35,11 +35,7 @@ import sun.java2d.Disposer; import sun.java2d.DisposerRecord; -import java.io.IOException; import java.util.List; -import java.security.AccessController; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; public abstract class FileFont extends PhysicalFont { @@ -252,84 +248,35 @@ private CreatedFontFileDisposerRecord(File file, int cnt, this.tracker = tracker; } - @SuppressWarnings("removal") public void dispose() { - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Object run() { - synchronized (fontFile) { - count--; - if (count > 0) { - return null; - } - } - if (fontFile != null) { - try { - if (tracker != null) { - tracker.subBytes((int)fontFile.length()); - } - /* REMIND: is it possible that the file is - * still open? It will be closed when the - * font2D is disposed but could this code - * execute first? If so the file would not - * be deleted on MS-windows. - */ - fontFile.delete(); - /* remove from delete on exit hook list : */ - // FIXME: still need to be refactored - SunFontManager.getInstance().tmpFontFiles.remove(fontFile); - } catch (Exception e) { - } - } - return null; + synchronized (fontFile) { + count--; + if (count > 0) { + return; + } + } + if (fontFile != null) { + try { + if (tracker != null) { + tracker.subBytes((int)fontFile.length()); } - }); + /* REMIND: is it possible that the file is + * still open? It will be closed when the + * font2D is disposed but could this code + * execute first? If so the file would not + * be deleted on MS-windows. + */ + fontFile.delete(); + /* remove from delete on exit hook list : */ + // FIXME: still need to be refactored + SunFontManager.getInstance().tmpFontFiles.remove(fontFile); + } catch (Exception e) { + } + } } } - @SuppressWarnings("removal") protected String getPublicFileName() { - SecurityManager sm = System.getSecurityManager(); - if (sm == null) { return platName; - } - boolean canReadProperty = true; - - try { - sm.checkPropertyAccess("java.io.tmpdir"); - } catch (SecurityException e) { - canReadProperty = false; - } - - if (canReadProperty) { - return platName; - } - - final File f = new File(platName); - - Boolean isTmpFile = Boolean.FALSE; - try { - isTmpFile = AccessController.doPrivileged( - new PrivilegedExceptionAction() { - public Boolean run() { - File tmp = new File(System.getProperty("java.io.tmpdir")); - try { - String tpath = tmp.getCanonicalPath(); - String fpath = f.getCanonicalPath(); - - return (fpath == null) || fpath.startsWith(tpath); - } catch (IOException e) { - return Boolean.TRUE; - } - } - } - ); - } catch (PrivilegedActionException e) { - // unable to verify whether value of java.io.tempdir will be - // exposed, so return only a name of the font file. - isTmpFile = Boolean.TRUE; - } - - return isTmpFile ? "temp file" : platName; } } diff --git a/src/java.desktop/share/classes/sun/font/FontManagerNativeLibrary.java b/src/java.desktop/share/classes/sun/font/FontManagerNativeLibrary.java index 9439f6ed8574a..51997571e757a 100644 --- a/src/java.desktop/share/classes/sun/font/FontManagerNativeLibrary.java +++ b/src/java.desktop/share/classes/sun/font/FontManagerNativeLibrary.java @@ -27,39 +27,32 @@ import sun.awt.OSInfo; -@SuppressWarnings({"removal", "restricted"}) +@SuppressWarnings("restricted") public class FontManagerNativeLibrary { static { - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Object run() { - /* REMIND do we really have to load awt here? */ - System.loadLibrary("awt"); - if (OSInfo.getOSType() == OSInfo.OSType.WINDOWS) { - /* Ideally fontmanager library should not depend on - particular implementation of the font scaler. - However, freetype scaler is basically small wrapper on - top of freetype library (that is used in binary form). + /* REMIND do we really have to load awt here? */ + System.loadLibrary("awt"); + if (OSInfo.getOSType() == OSInfo.OSType.WINDOWS) { + /* Ideally fontmanager library should not depend on + particular implementation of the font scaler. + However, freetype scaler is basically small wrapper on + top of freetype library (that is used in binary form). - This wrapper is compiled into fontmanager and this make - fontmanger library depending on freetype library. + This wrapper is compiled into fontmanager and this make + fontmanger library depending on freetype library. - On Windows DLL's in the JRE's BIN directory cannot be - found by windows DLL loading as that directory is not - on the Windows PATH. + On Windows DLL's in the JRE's BIN directory cannot be + found by windows DLL loading as that directory is not + on the Windows PATH. - To avoid link error we have to load freetype explicitly - before we load fontmanager. + To avoid link error we have to load freetype explicitly + before we load fontmanager. - NB: consider moving freetype wrapper part to separate - shared library in order to avoid dependency. */ - System.loadLibrary("freetype"); - } - System.loadLibrary("fontmanager"); - - return null; - } - }); + NB: consider moving freetype wrapper part to separate + shared library in order to avoid dependency. */ + System.loadLibrary("freetype"); + } + System.loadLibrary("fontmanager"); } /* diff --git a/src/java.desktop/share/classes/sun/font/FontUtilities.java b/src/java.desktop/share/classes/sun/font/FontUtilities.java index bdccf99d1ed5c..30ec4f3db8136 100644 --- a/src/java.desktop/share/classes/sun/font/FontUtilities.java +++ b/src/java.desktop/share/classes/sun/font/FontUtilities.java @@ -28,9 +28,7 @@ import java.awt.Font; import java.lang.ref.SoftReference; import java.util.concurrent.ConcurrentHashMap; -import java.security.AccessController; -import java.security.PrivilegedAction; import javax.swing.plaf.FontUIResource; import sun.awt.OSInfo; @@ -59,65 +57,57 @@ public final class FontUtilities { initStatic(); } - @SuppressWarnings("removal") + @SuppressWarnings("deprecation") // PlatformLogger.setLevel is deprecated. private static void initStatic() { - AccessController.doPrivileged(new PrivilegedAction() { - @SuppressWarnings("deprecation") // PlatformLogger.setLevel is deprecated. - @Override - public Object run() { - - isLinux = OSInfo.getOSType() == OSInfo.OSType.LINUX; - - isMacOSX = OSInfo.getOSType() == OSInfo.OSType.MACOSX; - if (isMacOSX) { - // os.version has values like 10.13.6, 10.14.6 - // If it is not positively recognised as 10.13 or less, - // assume it means 10.14 or some later version. - isMacOSX14 = true; - String version = System.getProperty("os.version", ""); - if (version.startsWith("10.")) { - version = version.substring(3); - int periodIndex = version.indexOf('.'); - if (periodIndex != -1) { - version = version.substring(0, periodIndex); - } - try { - int v = Integer.parseInt(version); - isMacOSX14 = (v >= 14); - } catch (NumberFormatException e) { - } - } - } - /* If set to "jdk", use the JDK's scaler rather than - * the platform one. This may be a no-op on platforms where - * JDK has been configured so that it always relies on the - * platform scaler. The principal case where it has an - * effect is that on Windows, 2D will never use GDI. - */ - String scalerStr = System.getProperty("sun.java2d.font.scaler"); - if (scalerStr != null) { - useJDKScaler = "jdk".equals(scalerStr); - } else { - useJDKScaler = false; + + isLinux = OSInfo.getOSType() == OSInfo.OSType.LINUX; + + isMacOSX = OSInfo.getOSType() == OSInfo.OSType.MACOSX; + if (isMacOSX) { + // os.version has values like 10.13.6, 10.14.6 + // If it is not positively recognised as 10.13 or less, + // assume it means 10.14 or some later version. + isMacOSX14 = true; + String version = System.getProperty("os.version", ""); + if (version.startsWith("10.")) { + version = version.substring(3); + int periodIndex = version.indexOf('.'); + if (periodIndex != -1) { + version = version.substring(0, periodIndex); } - isWindows = OSInfo.getOSType() == OSInfo.OSType.WINDOWS; - String debugLevel = - System.getProperty("sun.java2d.debugfonts"); - - if (debugLevel != null && !debugLevel.equals("false")) { - debugFonts = true; - logger = PlatformLogger.getLogger("sun.java2d"); - if (debugLevel.equals("warning")) { - logger.setLevel(PlatformLogger.Level.WARNING); - } else if (debugLevel.equals("severe")) { - logger.setLevel(PlatformLogger.Level.SEVERE); - } - logging = logger.isEnabled(); + try { + int v = Integer.parseInt(version); + isMacOSX14 = (v >= 14); + } catch (NumberFormatException e) { } - - return null; + } + } + /* If set to "jdk", use the JDK's scaler rather than + * the platform one. This may be a no-op on platforms where + * JDK has been configured so that it always relies on the + * platform scaler. The principal case where it has an + * effect is that on Windows, 2D will never use GDI. + */ + String scalerStr = System.getProperty("sun.java2d.font.scaler"); + if (scalerStr != null) { + useJDKScaler = "jdk".equals(scalerStr); + } else { + useJDKScaler = false; + } + isWindows = OSInfo.getOSType() == OSInfo.OSType.WINDOWS; + String debugLevel = + System.getProperty("sun.java2d.debugfonts"); + + if (debugLevel != null && !debugLevel.equals("false")) { + debugFonts = true; + logger = PlatformLogger.getLogger("sun.java2d"); + if (debugLevel.equals("warning")) { + logger.setLevel(PlatformLogger.Level.WARNING); + } else if (debugLevel.equals("severe")) { + logger.setLevel(PlatformLogger.Level.SEVERE); } - }); + logging = logger.isEnabled(); + } } /** diff --git a/src/java.desktop/share/classes/sun/font/StrikeCache.java b/src/java.desktop/share/classes/sun/font/StrikeCache.java index ea1369b4383ac..c0859c4c0af58 100644 --- a/src/java.desktop/share/classes/sun/font/StrikeCache.java +++ b/src/java.desktop/share/classes/sun/font/StrikeCache.java @@ -263,7 +263,6 @@ static final byte getPixelByte(MemorySegment pixelData, long index) { initStatic(); } - @SuppressWarnings("removal") private static void initStatic() { if (nativeAddressSize < 4) { @@ -271,37 +270,28 @@ private static void initStatic() { nativeAddressSize); } - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Object run() { - - /* Allow a client to override the reference type used to - * cache strikes. The default is "soft" which hints to keep - * the strikes around. This property allows the client to - * override this to "weak" which hint to the GC to free - * memory more aggressively. - */ - String refType = - System.getProperty("sun.java2d.font.reftype", "soft"); - cacheRefTypeWeak = refType.equals("weak"); - - String minStrikesStr = - System.getProperty("sun.java2d.font.minstrikes"); - if (minStrikesStr != null) { - try { - MINSTRIKES = Integer.parseInt(minStrikesStr); - if (MINSTRIKES <= 0) { - MINSTRIKES = 1; - } - } catch (NumberFormatException e) { - } + /* Allow a client to override the reference type used to + * cache strikes. The default is "soft" which hints to keep + * the strikes around. This property allows the client to + * override this to "weak" which hint to the GC to free + * memory more aggressively. + */ + String refType = System.getProperty("sun.java2d.font.reftype", "soft"); + cacheRefTypeWeak = refType.equals("weak"); + + String minStrikesStr = + System.getProperty("sun.java2d.font.minstrikes"); + if (minStrikesStr != null) { + try { + MINSTRIKES = Integer.parseInt(minStrikesStr); + if (MINSTRIKES <= 0) { + MINSTRIKES = 1; } - - recentStrikes = new FontStrike[MINSTRIKES]; - - return null; + } catch (NumberFormatException e) { } - }); + } + + recentStrikes = new FontStrike[MINSTRIKES]; } diff --git a/src/java.desktop/share/classes/sun/font/SunFontManager.java b/src/java.desktop/share/classes/sun/font/SunFontManager.java index 3aec139b56d73..06dc4a90820c1 100644 --- a/src/java.desktop/share/classes/sun/font/SunFontManager.java +++ b/src/java.desktop/share/classes/sun/font/SunFontManager.java @@ -33,8 +33,6 @@ import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStreamReader; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; @@ -262,30 +260,24 @@ public FilenameFilter getType1Filter() { initStatic(); } - @SuppressWarnings("removal") private static void initStatic() { - AccessController.doPrivileged(new PrivilegedAction() { - public Void run() { - FontManagerNativeLibrary.load(); - - // JNI throws an exception if a class/method/field is not found, - // so there's no need to do anything explicit here. - initIDs(); - - switch (StrikeCache.nativeAddressSize) { - case 8: longAddresses = true; break; - case 4: longAddresses = false; break; - default: throw new RuntimeException("Unexpected address size"); - } + FontManagerNativeLibrary.load(); - noType1Font = "true".equals(System.getProperty("sun.java2d.noType1Font")); - jreLibDirName = System.getProperty("java.home","") + File.separator + "lib"; - jreFontDirName = jreLibDirName + File.separator + "fonts"; + // JNI throws an exception if a class/method/field is not found, + // so there's no need to do anything explicit here. + initIDs(); - maxSoftRefCnt = Integer.getInteger("sun.java2d.font.maxSoftRefs", 10); - return null; - } - }); + switch (StrikeCache.nativeAddressSize) { + case 8: longAddresses = true; break; + case 4: longAddresses = false; break; + default: throw new RuntimeException("Unexpected address size"); + } + + noType1Font = "true".equals(System.getProperty("sun.java2d.noType1Font")); + jreLibDirName = System.getProperty("java.home","") + File.separator + "lib"; + jreFontDirName = jreLibDirName + File.separator + "fonts"; + + maxSoftRefCnt = Integer.getInteger("sun.java2d.font.maxSoftRefs", 10); } /** @@ -304,150 +296,142 @@ public TrueTypeFont getEUDCFont() { /* Initialise ptrs used by JNI methods */ private static native void initIDs(); - @SuppressWarnings("removal") protected SunFontManager() { - AccessController.doPrivileged(new PrivilegedAction() { - public Void run() { - File badFontFile = - new File(jreFontDirName + File.separator + "badfonts.txt"); - if (badFontFile.exists()) { - badFonts = new ArrayList<>(); - try (FileInputStream fis = new FileInputStream(badFontFile); - BufferedReader br = new BufferedReader(new InputStreamReader(fis))) { - while (true) { - String name = br.readLine(); - if (name == null) { - break; - } else { - if (FontUtilities.debugFonts()) { - FontUtilities.logWarning("read bad font: " + name); - } - badFonts.add(name); - } + File badFontFile = + new File(jreFontDirName + File.separator + "badfonts.txt"); + if (badFontFile.exists()) { + badFonts = new ArrayList<>(); + try (FileInputStream fis = new FileInputStream(badFontFile); + BufferedReader br = new BufferedReader(new InputStreamReader(fis))) { + while (true) { + String name = br.readLine(); + if (name == null) { + break; + } else { + if (FontUtilities.debugFonts()) { + FontUtilities.logWarning("read bad font: " + name); } - } catch (IOException e) { + badFonts.add(name); } } + } catch (IOException e) { + } + } - /* Here we get the fonts in jre/lib/fonts and register - * them so they are always available and preferred over - * other fonts. This needs to be registered before the - * composite fonts as otherwise some native font that - * corresponds may be found as we don't have a way to - * handle two fonts of the same name, so the JRE one - * must be the first one registered. Pass "true" to - * registerFonts method as on-screen these JRE fonts - * always go through the JDK rasteriser. - */ - if (FontUtilities.isLinux) { - /* Linux font configuration uses these fonts */ - registerFontDir(jreFontDirName); - } - registerFontsInDir(jreFontDirName, true, Font2D.JRE_RANK, - true, false); - - /* Create the font configuration and get any font path - * that might be specified. - */ - fontConfig = createFontConfiguration(); - - String[] fontInfo = getDefaultPlatformFont(); - defaultFontName = fontInfo[0]; - if (defaultFontName == null && FontUtilities.debugFonts()) { - FontUtilities.logWarning("defaultFontName is null"); - } - defaultFontFileName = fontInfo[1]; - - String extraFontPath = fontConfig.getExtraFontPath(); - - /* In prior releases the debugging font path replaced - * all normally located font directories except for the - * JRE fonts dir. This directory is still always located - * and placed at the head of the path but as an - * augmentation to the previous behaviour the - * changes below allow you to additionally append to - * the font path by starting with append: or prepend by - * starting with a prepend: sign. Eg: to append - * -Dsun.java2d.fontpath=append:/usr/local/myfonts - * and to prepend - * -Dsun.java2d.fontpath=prepend:/usr/local/myfonts Disp - * - * If there is an appendedfontpath it in the font - * configuration it is used instead of searching the - * system for dirs. - * The behaviour of append and prepend is then similar - * to the normal case. ie it goes after what - * you prepend and * before what you append. If the - * sun.java2d.fontpath property is used, but it - * neither the append or prepend syntaxes is used then - * as except for the JRE dir the path is replaced and it - * is up to you to make sure that all the right - * directories are located. This is platform and - * locale-specific so its almost impossible to get - * right, so it should be used with caution. - */ - boolean prependToPath = false; - boolean appendToPath = false; - String dbgFontPath = System.getProperty("sun.java2d.fontpath"); - - if (dbgFontPath != null) { - if (dbgFontPath.startsWith("prepend:")) { - prependToPath = true; - dbgFontPath = - dbgFontPath.substring("prepend:".length()); - } else if (dbgFontPath.startsWith("append:")) { - appendToPath = true; - dbgFontPath = - dbgFontPath.substring("append:".length()); - } - } + /* Here we get the fonts in jre/lib/fonts and register + * them so they are always available and preferred over + * other fonts. This needs to be registered before the + * composite fonts as otherwise some native font that + * corresponds may be found as we don't have a way to + * handle two fonts of the same name, so the JRE one + * must be the first one registered. Pass "true" to + * registerFonts method as on-screen these JRE fonts + * always go through the JDK rasteriser. + */ + if (FontUtilities.isLinux) { + /* Linux font configuration uses these fonts */ + registerFontDir(jreFontDirName); + } + registerFontsInDir(jreFontDirName, true, Font2D.JRE_RANK, + true, false); - if (FontUtilities.debugFonts()) { - FontUtilities.logInfo("JRE font directory: " + jreFontDirName); - FontUtilities.logInfo("Extra font path: " + extraFontPath); - FontUtilities.logInfo("Debug font path: " + dbgFontPath); - } + /* Create the font configuration and get any font path + * that might be specified. + */ + fontConfig = createFontConfiguration(); + + String[] fontInfo = getDefaultPlatformFont(); + defaultFontName = fontInfo[0]; + if (defaultFontName == null && FontUtilities.debugFonts()) { + FontUtilities.logWarning("defaultFontName is null"); + } + defaultFontFileName = fontInfo[1]; + + String extraFontPath = fontConfig.getExtraFontPath(); + + /* In prior releases the debugging font path replaced + * all normally located font directories except for the + * JRE fonts dir. This directory is still always located + * and placed at the head of the path but as an + * augmentation to the previous behaviour the + * changes below allow you to additionally append to + * the font path by starting with append: or prepend by + * starting with a prepend: sign. Eg: to append + * -Dsun.java2d.fontpath=append:/usr/local/myfonts + * and to prepend + * -Dsun.java2d.fontpath=prepend:/usr/local/myfonts Disp + * + * If there is an appendedfontpath it in the font + * configuration it is used instead of searching the + * system for dirs. + * The behaviour of append and prepend is then similar + * to the normal case. ie it goes after what + * you prepend and * before what you append. If the + * sun.java2d.fontpath property is used, but it + * neither the append or prepend syntaxes is used then + * as except for the JRE dir the path is replaced and it + * is up to you to make sure that all the right + * directories are located. This is platform and + * locale-specific so its almost impossible to get + * right, so it should be used with caution. + */ + boolean prependToPath = false; + boolean appendToPath = false; + String dbgFontPath = System.getProperty("sun.java2d.fontpath"); - if (dbgFontPath != null) { - /* In debugging mode we register all the paths - * Caution: this is a very expensive call on Solaris:- - */ - fontPath = getPlatformFontPath(noType1Font); + if (dbgFontPath != null) { + if (dbgFontPath.startsWith("prepend:")) { + prependToPath = true; + dbgFontPath = + dbgFontPath.substring("prepend:".length()); + } else if (dbgFontPath.startsWith("append:")) { + appendToPath = true; + dbgFontPath = + dbgFontPath.substring("append:".length()); + } + } - if (extraFontPath != null) { - fontPath = extraFontPath + File.pathSeparator + fontPath; - } - if (appendToPath) { - fontPath += File.pathSeparator + dbgFontPath; - } else if (prependToPath) { - fontPath = dbgFontPath + File.pathSeparator + fontPath; - } else { - fontPath = dbgFontPath; - } - registerFontDirs(fontPath); - } else if (extraFontPath != null) { - /* If the font configuration contains an - * "appendedfontpath" entry, it is interpreted as a - * set of locations that should always be registered. - * It may be additional to locations normally found - * for that place, or it may be locations that need - * to have all their paths registered to locate all - * the needed platform names. - * This is typically when the same .TTF file is - * referenced from multiple font.dir files and all - * of these must be read to find all the native - * (XLFD) names for the font, so that X11 font APIs - * can be used for as many code points as possible. - */ - registerFontDirs(extraFontPath); - } + if (FontUtilities.debugFonts()) { + FontUtilities.logInfo("JRE font directory: " + jreFontDirName); + FontUtilities.logInfo("Extra font path: " + extraFontPath); + FontUtilities.logInfo("Debug font path: " + dbgFontPath); + } - initCompositeFonts(fontConfig, null); + if (dbgFontPath != null) { + /* In debugging mode we register all the paths + * Caution: this is a very expensive call on Solaris:- + */ + fontPath = getPlatformFontPath(noType1Font); - return null; + if (extraFontPath != null) { + fontPath = extraFontPath + File.pathSeparator + fontPath; } - }); + if (appendToPath) { + fontPath += File.pathSeparator + dbgFontPath; + } else if (prependToPath) { + fontPath = dbgFontPath + File.pathSeparator + fontPath; + } else { + fontPath = dbgFontPath; + } + registerFontDirs(fontPath); + } else if (extraFontPath != null) { + /* If the font configuration contains an + * "appendedfontpath" entry, it is interpreted as a + * set of locations that should always be registered. + * It may be additional to locations normally found + * for that place, or it may be locations that need + * to have all their paths registered to locate all + * the needed platform names. + * This is typically when the same .TTF file is + * referenced from multiple font.dir files and all + * of these must be read to find all the native + * (XLFD) names for the font, so that X11 font APIs + * can be used for as many code points as possible. + */ + registerFontDirs(extraFontPath); + } + initCompositeFonts(fontConfig, null); } public Font2DHandle getNewComposite(String family, int style, @@ -1095,7 +1079,6 @@ private static String dotStyleStr(int num) { private boolean haveCheckedUnreferencedFontFiles; - @SuppressWarnings("removal") private String[] getFontFilesFromPath(boolean noType1) { final FilenameFilter filter; if (noType1) { @@ -1103,34 +1086,30 @@ private String[] getFontFilesFromPath(boolean noType1) { } else { filter = new TTorT1Filter(); } - return AccessController.doPrivileged(new PrivilegedAction() { - public String[] run() { - if (pathDirs.length == 1) { - File dir = new File(pathDirs[0]); - String[] files = dir.list(filter); - if (files == null) { - return new String[0]; - } - for (int f=0; f fileList = new ArrayList<>(); - for (int i = 0; i< pathDirs.length; i++) { - File dir = new File(pathDirs[i]); - String[] files = dir.list(filter); - if (files == null) { - continue; - } - for (int f = 0; f < files.length ; f++) { - fileList.add(files[f].toLowerCase()); - } - } - return fileList.toArray(STR_ARRAY); + if (pathDirs.length == 1) { + File dir = new File(pathDirs[0]); + String[] files = dir.list(filter); + if (files == null) { + return new String[0]; + } + for (int f=0; f fileList = new ArrayList<>(); + for (int i = 0; i< pathDirs.length; i++) { + File dir = new File(pathDirs[i]); + String[] files = dir.list(filter); + if (files == null) { + continue; + } + for (int f = 0; f < files.length ; f++) { + fileList.add(files[f].toLowerCase()); } } - }); + return fileList.toArray(STR_ARRAY); + } } /* This is needed since some windows registry names don't match @@ -1430,7 +1409,6 @@ public HashMap populateHardcodedFileNameMap() { return new HashMap<>(0); } - @SuppressWarnings("removal") Font2D findFontFromPlatformMap(String lcName, int style) { HashMap platformFontMap = SunFontManager.platformFontMap; if (platformFontMap == null) { @@ -1524,20 +1502,16 @@ Font2D findFontFromPlatformMap(String lcName, int style) { final String[] files = { plainFile, boldFile, italicFile, boldItalicFile } ; - failure = AccessController.doPrivileged(new PrivilegedAction() { - public Boolean run() { - for (int i=0; i() { - public String run() { - for (int p = 0; p < pathDirs.length; p++) { - File f = new File(pathDirs[p] +File.separator+ s); - if (f.exists()) { - return f.getAbsolutePath(); - } - } - return null; - } - }); - if (path != null) { - return path; + for (int p = 0; p < pathDirs.length; p++) { + f = new File(pathDirs[p] + File.separator + s); + if (f.exists()) { + return f.getAbsolutePath(); + } } } return s; // shouldn't happen, but harmless @@ -2181,7 +2145,6 @@ private static boolean fontSupportsEncoding(Font font, String encoding) { private int createdFontCount = 0; - @SuppressWarnings("removal") public Font2D[] createFont2D(File fontFile, int fontFormat, boolean all, boolean isCopy, CreatedFontTracker tracker) throws FontFormatException { @@ -2229,15 +2192,10 @@ public Font2D[] createFont2D(File fontFile, int fontFormat, boolean all, } } catch (FontFormatException e) { if (isCopy) { - AccessController.doPrivileged(new PrivilegedAction() { - public Void run() { - if (_tracker != null) { - _tracker.subBytes((int)fFile.length()); - } - fFile.delete(); - return null; - } - }); + if (_tracker != null) { + _tracker.subBytes((int)fFile.length()); + } + fFile.delete(); } throw(e); } @@ -2253,39 +2211,31 @@ public Void run() { if (fileCloser == null) { final Runnable fileCloserRunnable = new Runnable() { public void run() { - AccessController.doPrivileged(new PrivilegedAction() { - public Void run() { - for (int i = 0;i < CHANNELPOOLSIZE; i++) { - if (fontFileCache[i] != null) { - try { - fontFileCache[i].close(); - } catch (Exception e) { - } - } + for (int i = 0;i < CHANNELPOOLSIZE; i++) { + if (fontFileCache[i] != null) { + try { + fontFileCache[i].close(); + } catch (Exception e) { } - if (tmpFontFiles != null) { - File[] files = new File[tmpFontFiles.size()]; - files = tmpFontFiles.toArray(files); - for (int f=0; f) () -> { - ThreadGroup rootTG = ThreadGroupUtils.getRootThreadGroup(); - fileCloser = new Thread(rootTG, fileCloserRunnable, - "FileCloser", 0, false); - fileCloser.setContextClassLoader(null); - Runtime.getRuntime().addShutdownHook(fileCloser); - return null; - }); + ThreadGroup rootTG = ThreadGroupUtils.getRootThreadGroup(); + fileCloser = new Thread(rootTG, fileCloserRunnable, + "FileCloser", 0, false); + fileCloser.setContextClassLoader(null); + Runtime.getRuntime().addShutdownHook(fileCloser); } } } @@ -2930,7 +2880,6 @@ public String getPlatformFontPath(boolean noType1Font) { return fontPath; } - @SuppressWarnings("removal") protected void loadFonts() { if (discoveredAllFonts) { return; @@ -2943,28 +2892,23 @@ protected void loadFonts() { } initialiseDeferredFonts(); - AccessController.doPrivileged(new PrivilegedAction() { - public Void run() { - if (fontPath == null) { - fontPath = getPlatformFontPath(noType1Font); - registerFontDirs(fontPath); - } - if (fontPath != null) { - // this will find all fonts including those already - // registered. But we have checks in place to prevent - // double registration. - if (! gotFontsFromPlatform()) { - registerFontsOnPath(fontPath, false, - Font2D.UNKNOWN_RANK, - false, true); - loadedAllFontFiles = true; - } - } - registerOtherFontFiles(registeredFontFiles); - discoveredAllFonts = true; - return null; + if (fontPath == null) { + fontPath = getPlatformFontPath(noType1Font); + registerFontDirs(fontPath); + } + if (fontPath != null) { + // this will find all fonts including those already + // registered. But we have checks in place to prevent + // double registration. + if (! gotFontsFromPlatform()) { + registerFontsOnPath(fontPath, false, + Font2D.UNKNOWN_RANK, + false, true); + loadedAllFontFiles = true; } - }); + } + registerOtherFontFiles(registeredFontFiles); + discoveredAllFonts = true; } } @@ -3048,7 +2992,6 @@ public synchronized String getDefaultFontFaceName() { return defaultFontName; } - @SuppressWarnings("removal") public void loadFontFiles() { loadFonts(); if (loadedAllFontFiles) { @@ -3060,23 +3003,18 @@ public void loadFontFiles() { Thread.dumpStack(); FontUtilities.logInfo("loadAllFontFiles() called"); } - AccessController.doPrivileged(new PrivilegedAction() { - public Void run() { - if (fontPath == null) { - fontPath = getPlatformFontPath(noType1Font); - } - if (fontPath != null) { - // this will find all fonts including those already - // registered. But we have checks in place to prevent - // double registration. - registerFontsOnPath(fontPath, false, - Font2D.UNKNOWN_RANK, - false, true); - } - loadedAllFontFiles = true; - return null; - } - }); + if (fontPath == null) { + fontPath = getPlatformFontPath(noType1Font); + } + if (fontPath != null) { + // this will find all fonts including those already + // registered. But we have checks in place to prevent + // double registration. + registerFontsOnPath(fontPath, false, + Font2D.UNKNOWN_RANK, + false, true); + } + loadedAllFontFiles = true; } } @@ -3402,16 +3340,9 @@ public String[] getInstalledFontFamilyNames(Locale requestedLocale) { // Provides an aperture to add native font family names to the map protected void addNativeFontFamilyNames(TreeMap familyNames, Locale requestedLocale) { } - @SuppressWarnings("removal") public void register1dot0Fonts() { - AccessController.doPrivileged(new PrivilegedAction() { - public Void run() { - String type1Dir = "/usr/openwin/lib/X11/fonts/Type1"; - registerFontsInDir(type1Dir, true, Font2D.TYPE1_RANK, - false, false); - return null; - } - }); + String type1Dir = "/usr/openwin/lib/X11/fonts/Type1"; + registerFontsInDir(type1Dir, true, Font2D.TYPE1_RANK, false, false); } /* Really we need only the JRE fonts family names, but there's little @@ -3442,33 +3373,28 @@ protected void getJREFontFamilyNames(TreeMap familyNames, * on windows and uses that if set. */ private static Locale systemLocale = null; - @SuppressWarnings("removal") private static Locale getSystemStartupLocale() { if (systemLocale == null) { - systemLocale = AccessController.doPrivileged(new PrivilegedAction() { - public Locale run() { - /* On windows the system locale may be different than the - * user locale. This is an unsupported configuration, but - * in that case we want to return a dummy locale that will - * never cause a match in the usage of this API. This is - * important because Windows documents that the family - * names of fonts are enumerated using the language of - * the system locale. BY returning a dummy locale in that - * case we do not use the platform API which would not - * return us the names we want. - */ - String fileEncoding = System.getProperty("file.encoding", ""); - String sysEncoding = System.getProperty("sun.jnu.encoding"); - if (sysEncoding != null && !sysEncoding.equals(fileEncoding)) { - return Locale.ROOT; - } - - String language = System.getProperty("user.language", "en"); - String country = System.getProperty("user.country",""); - String variant = System.getProperty("user.variant",""); - return Locale.of(language, country, variant); - } - }); + /* On windows the system locale may be different than the + * user locale. This is an unsupported configuration, but + * in that case we want to return a dummy locale that will + * never cause a match in the usage of this API. This is + * important because Windows documents that the family + * names of fonts are enumerated using the language of + * the system locale. BY returning a dummy locale in that + * case we do not use the platform API which would not + * return us the names we want. + */ + String fileEncoding = System.getProperty("file.encoding", ""); + String sysEncoding = System.getProperty("sun.jnu.encoding"); + if (sysEncoding != null && !sysEncoding.equals(fileEncoding)) { + systemLocale = Locale.ROOT; + } else { + String language = System.getProperty("user.language", "en"); + String country = System.getProperty("user.country",""); + String variant = System.getProperty("user.variant",""); + systemLocale = Locale.of(language, country, variant); + } } return systemLocale; } diff --git a/src/java.desktop/share/classes/sun/font/SunLayoutEngine.java b/src/java.desktop/share/classes/sun/font/SunLayoutEngine.java index c291e45b5580c..f1d6de7d4bc55 100644 --- a/src/java.desktop/share/classes/sun/font/SunLayoutEngine.java +++ b/src/java.desktop/share/classes/sun/font/SunLayoutEngine.java @@ -37,8 +37,6 @@ import java.awt.geom.Point2D; import java.lang.foreign.MemorySegment; import java.lang.ref.SoftReference; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.concurrent.ConcurrentHashMap; import java.util.WeakHashMap; @@ -167,10 +165,7 @@ private long getFacePtr(Font2D font2D) { static boolean useFFM = true; static { - @SuppressWarnings("removal") - String prop = AccessController.doPrivileged( - (PrivilegedAction) () -> - System.getProperty("sun.font.layout.ffm", "true")); + String prop = System.getProperty("sun.font.layout.ffm", "true"); useFFM = "true".equals(prop); } diff --git a/src/java.desktop/share/classes/sun/font/TrueTypeFont.java b/src/java.desktop/share/classes/sun/font/TrueTypeFont.java index 3895ec6ca8260..a44a013b7492f 100644 --- a/src/java.desktop/share/classes/sun/font/TrueTypeFont.java +++ b/src/java.desktop/share/classes/sun/font/TrueTypeFont.java @@ -38,9 +38,6 @@ import java.nio.ShortBuffer; import java.nio.channels.ClosedChannelException; import java.nio.channels.FileChannel; -import java.security.AccessController; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; @@ -246,13 +243,7 @@ private synchronized FileChannel open(boolean usePool) FontUtilities.logInfo("open TTF: " + platName); } try { - @SuppressWarnings("removal") - RandomAccessFile raf = AccessController.doPrivileged( - new PrivilegedExceptionAction() { - public RandomAccessFile run() throws FileNotFoundException { - return new RandomAccessFile(platName, "r"); - } - }); + RandomAccessFile raf = new RandomAccessFile(platName, "r"); disposerRecord.channel = raf.getChannel(); fileSize = (int)disposerRecord.channel.size(); if (usePool) { @@ -261,13 +252,6 @@ public RandomAccessFile run() throws FileNotFoundException { ((SunFontManager) fm).addToPool(this); } } - } catch (PrivilegedActionException e) { - close(); - Throwable reason = e.getCause(); - if (reason == null) { - reason = e; - } - throw new FontFormatException(reason.toString()); } catch (ClosedChannelException e) { /* NIO I/O is interruptible, recurse to retry operation. * The call to channel.size() above can throw this exception. @@ -664,7 +648,6 @@ && getDirectoryEntry(hheaTag) == null) { }; private static String defaultCodePage = null; - @SuppressWarnings("removal") static String getCodePage() { if (defaultCodePage != null) { @@ -672,8 +655,7 @@ static String getCodePage() { } if (FontUtilities.isWindows) { - defaultCodePage = - AccessController.doPrivileged(new GetPropertyAction("file.encoding")); + defaultCodePage = System.getProperty("file.encoding"); } else { if (languages.length != codePages.length) { throw new InternalError("wrong code pages array length"); diff --git a/src/java.desktop/share/classes/sun/font/Type1Font.java b/src/java.desktop/share/classes/sun/font/Type1Font.java index cc36c193de030..67f83cce6433c 100644 --- a/src/java.desktop/share/classes/sun/font/Type1Font.java +++ b/src/java.desktop/share/classes/sun/font/Type1Font.java @@ -83,18 +83,10 @@ private static class T1DisposerRecord implements DisposerRecord { fileName = name; } - @SuppressWarnings("removal") public synchronized void dispose() { - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Object run() { - - if (fileName != null) { - (new java.io.File(fileName)).delete(); - } - return null; - } - }); + if (fileName != null) { + (new java.io.File(fileName)).delete(); + } } } @@ -191,18 +183,11 @@ private synchronized ByteBuffer getBuffer() throws FontFormatException { FontUtilities.logInfo("open Type 1 font: " + platName); } try { - @SuppressWarnings("removal") - RandomAccessFile raf = (RandomAccessFile) - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Object run() { - try { - return new RandomAccessFile(platName, "r"); - } catch (FileNotFoundException ffne) { - } - return null; - } - }); + RandomAccessFile raf = null; + try { + raf = new RandomAccessFile(platName, "r"); + } catch (FileNotFoundException ffne) { + } FileChannel fc = raf.getChannel(); fileSize = (int)fc.size(); bbuf = ByteBuffer.allocate(fileSize); @@ -227,7 +212,6 @@ protected void close() { } /* called from native code to read file into a direct byte buffer */ - @SuppressWarnings("removal") void readFile(ByteBuffer buffer) { RandomAccessFile raf = null; FileChannel fc; @@ -235,17 +219,10 @@ void readFile(ByteBuffer buffer) { FontUtilities.logInfo("open Type 1 font: " + platName); } try { - raf = (RandomAccessFile) - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Object run() { - try { - return new RandomAccessFile(platName, "r"); - } catch (FileNotFoundException fnfe) { - } - return null; - } - }); + try { + raf = new RandomAccessFile(platName, "r"); + } catch (FileNotFoundException fnfe) { + } fc = raf.getChannel(); while (buffer.remaining() > 0 && fc.read(buffer) != -1) {} } catch (ClosedChannelException e) { From cd45ba32f026ba3827d18836cab37a73f59346ed Mon Sep 17 00:00:00 2001 From: Xiaolong Peng Date: Tue, 19 Nov 2024 20:18:54 +0000 Subject: [PATCH 23/74] 8342041: Test gc/shenandoah/oom/TestClassLoaderLeak.java slow on Windows after JDK-8340490 Reviewed-by: shade, wkemper --- src/hotspot/share/gc/shenandoah/shenandoahPacer.cpp | 10 +++++----- .../jtreg/gc/shenandoah/oom/TestClassLoaderLeak.java | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/hotspot/share/gc/shenandoah/shenandoahPacer.cpp b/src/hotspot/share/gc/shenandoah/shenandoahPacer.cpp index 8d10b7cbfcfaf..e7d5a2e00c5b2 100644 --- a/src/hotspot/share/gc/shenandoah/shenandoahPacer.cpp +++ b/src/hotspot/share/gc/shenandoah/shenandoahPacer.cpp @@ -253,9 +253,9 @@ void ShenandoahPacer::pace_for_alloc(size_t words) { return; } - jlong const max_delay = ShenandoahPacingMaxDelay * NANOSECS_PER_MILLISEC; - jlong const start_time = os::elapsed_counter(); - while (!claimed && (os::elapsed_counter() - start_time) < max_delay) { + jlong const start_time = os::javaTimeNanos(); + jlong const deadline = start_time + (ShenandoahPacingMaxDelay * NANOSECS_PER_MILLISEC); + while (!claimed && os::javaTimeNanos() < deadline) { // We could instead assist GC, but this would suffice for now. wait(1); claimed = claim_for_alloc(words); @@ -267,7 +267,7 @@ void ShenandoahPacer::pace_for_alloc(size_t words) { claimed = claim_for_alloc(words); assert(claimed, "Should always succeed"); } - ShenandoahThreadLocalData::add_paced_time(current, (double)(os::elapsed_counter() - start_time) / NANOSECS_PER_SEC); + ShenandoahThreadLocalData::add_paced_time(current, (double)(os::javaTimeNanos() - start_time) / NANOSECS_PER_SEC); } void ShenandoahPacer::wait(size_t time_ms) { @@ -276,7 +276,7 @@ void ShenandoahPacer::wait(size_t time_ms) { assert(time_ms > 0, "Should not call this with zero argument, as it would stall until notify"); assert(time_ms <= LONG_MAX, "Sanity"); MonitorLocker locker(_wait_monitor); - _wait_monitor->wait((long)time_ms); + _wait_monitor->wait(time_ms); } void ShenandoahPacer::notify_waiters() { diff --git a/test/hotspot/jtreg/gc/shenandoah/oom/TestClassLoaderLeak.java b/test/hotspot/jtreg/gc/shenandoah/oom/TestClassLoaderLeak.java index 00e32a4136e68..1a3d07bf80d06 100644 --- a/test/hotspot/jtreg/gc/shenandoah/oom/TestClassLoaderLeak.java +++ b/test/hotspot/jtreg/gc/shenandoah/oom/TestClassLoaderLeak.java @@ -27,7 +27,7 @@ * @summary Test OOME in due to classloader leak * @requires vm.gc.Shenandoah * @library /test/lib - * @run driver/timeout=600 TestClassLoaderLeak + * @run driver TestClassLoaderLeak */ import java.util.*; From aac1f9af01b15aac0c6ca923b49f5577ee8ce104 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Laurent=20Bourg=C3=A8s?= Date: Tue, 19 Nov 2024 20:28:58 +0000 Subject: [PATCH 24/74] 8341793: Fix ExceptionOccurred in jdk.accessibility Reviewed-by: prr, avu --- .../AccessBridgeJavaEntryPoints.cpp | 142 ++++-------------- 1 file changed, 30 insertions(+), 112 deletions(-) diff --git a/src/jdk.accessibility/windows/native/libjavaaccessbridge/AccessBridgeJavaEntryPoints.cpp b/src/jdk.accessibility/windows/native/libjavaaccessbridge/AccessBridgeJavaEntryPoints.cpp index 6f4231b70b99e..8610617f7eb55 100644 --- a/src/jdk.accessibility/windows/native/libjavaaccessbridge/AccessBridgeJavaEntryPoints.cpp +++ b/src/jdk.accessibility/windows/native/libjavaaccessbridge/AccessBridgeJavaEntryPoints.cpp @@ -74,36 +74,36 @@ AccessBridgeJavaEntryPoints::~AccessBridgeJavaEntryPoints() { return FALSE; \ } -#define EXCEPTION_CHECK(situationDescription, returnVal) \ - if (exception = jniEnv->ExceptionOccurred()) { \ - PrintDebugString("[ERROR]: *** Exception occured while doing: %s; returning %d", situationDescription, returnVal); \ - jniEnv->ExceptionDescribe(); \ - jniEnv->ExceptionClear(); \ - return (returnVal); \ - } - -#define EXCEPTION_CHECK_WITH_RELEASE(situationDescription, returnVal, js, stringBytes) \ - if (exception = jniEnv->ExceptionOccurred()) { \ - PrintDebugString("[ERROR]: *** Exception occured while doing: %s - call to GetStringLength; returning %d", situationDescription, returnVal); \ - jniEnv->ExceptionDescribe(); \ - jniEnv->ExceptionClear(); \ - jniEnv->ReleaseStringChars(js, stringBytes); \ - return (returnVal); \ - } \ - jniEnv->ReleaseStringChars(js, stringBytes); \ - if (exception = jniEnv->ExceptionOccurred()) { \ - PrintDebugString("[ERROR]: *** Exception occured while doing: %s - call to ReleaseStringChars; returning %d", situationDescription, returnVal); \ - jniEnv->ExceptionDescribe(); \ - jniEnv->ExceptionClear(); \ - return (returnVal); \ - } - -#define EXCEPTION_CHECK_VOID(situationDescription) \ - if (exception = jniEnv->ExceptionOccurred()) { \ +#define EXCEPTION_CHECK(situationDescription, returnVal) \ + if (jniEnv->ExceptionCheck()) { \ + PrintDebugString("[ERROR]: *** Exception occured while doing: %s; returning %d", situationDescription, returnVal); \ + jniEnv->ExceptionDescribe(); \ + jniEnv->ExceptionClear(); \ + return (returnVal); \ + } + +#define EXCEPTION_CHECK_WITH_RELEASE(situationDescription, returnVal, js, stringBytes) \ + if (jniEnv->ExceptionCheck()) { \ + PrintDebugString("[ERROR]: *** Exception occured while doing: %s - call to GetStringLength; returning %d", situationDescription, returnVal); \ + jniEnv->ExceptionDescribe(); \ + jniEnv->ExceptionClear(); \ + jniEnv->ReleaseStringChars(js, stringBytes); \ + return (returnVal); \ + } \ + jniEnv->ReleaseStringChars(js, stringBytes); \ + if (jniEnv->ExceptionCheck()) { \ + PrintDebugString("[ERROR]: *** Exception occured while doing: %s - call to ReleaseStringChars; returning %d", situationDescription, returnVal); \ + jniEnv->ExceptionDescribe(); \ + jniEnv->ExceptionClear(); \ + return (returnVal); \ + } + +#define EXCEPTION_CHECK_VOID(situationDescription) \ + if (jniEnv->ExceptionCheck()) { \ PrintDebugString("[ERROR]: *** Exception occured while doing: %s", situationDescription); \ - jniEnv->ExceptionDescribe(); \ - jniEnv->ExceptionClear(); \ - return; \ + jniEnv->ExceptionDescribe(); \ + jniEnv->ExceptionClear(); \ + return; \ } /** @@ -890,7 +890,6 @@ AccessBridgeJavaEntryPoints::BuildJavaEntryPoints() { */ BOOL AccessBridgeJavaEntryPoints::isJavaWindow(jint window) { - jthrowable exception; BOOL returnVal; PrintDebugString("[INFO]: Calling AccessBridgeJavaEntryPoints::isJavaWindow(%X):", window); @@ -913,7 +912,6 @@ AccessBridgeJavaEntryPoints::isJavaWindow(jint window) { */ BOOL AccessBridgeJavaEntryPoints::isSameObject(jobject obj1, jobject obj2) { - jthrowable exception; BOOL returnVal; PrintDebugString("[INFO]: In AccessBridgeJavaEntryPoints::isSameObject(%p %p):", obj1, obj2); @@ -935,7 +933,6 @@ jobject AccessBridgeJavaEntryPoints::getAccessibleContextFromHWND(jint window) { jobject returnedAccessibleContext; jobject globalRef; - jthrowable exception; PrintDebugString("[INFO]: In AccessBridgeJavaEntryPoints::getAccessibleContextFromHWND(%X):", window); @@ -961,7 +958,6 @@ AccessBridgeJavaEntryPoints::getAccessibleContextFromHWND(jint window) { */ HWND AccessBridgeJavaEntryPoints::getHWNDFromAccessibleContext(jobject accessibleContext) { - jthrowable exception; HWND rHWND; PrintDebugString("[INFO]: In AccessBridgeJavaEntryPoints::getHWNDFromAccessibleContext(%X):", @@ -987,7 +983,6 @@ AccessBridgeJavaEntryPoints::getHWNDFromAccessibleContext(jobject accessibleCont */ BOOL AccessBridgeJavaEntryPoints::setTextContents(const jobject accessibleContext, const wchar_t *text) { - jthrowable exception; BOOL result = FALSE; PrintDebugString("[INFO]: In AccessBridgeJavaEntryPoints::setTextContents(%p, %ls):", @@ -1024,7 +1019,6 @@ AccessBridgeJavaEntryPoints::setTextContents(const jobject accessibleContext, co */ jobject AccessBridgeJavaEntryPoints::getParentWithRole(const jobject accessibleContext, const wchar_t *role) { - jthrowable exception; jobject rAccessibleContext; PrintDebugString("[INFO]: In AccessBridgeJavaEntryPoints::getParentWithRole(%p):", @@ -1062,7 +1056,6 @@ AccessBridgeJavaEntryPoints::getParentWithRole(const jobject accessibleContext, */ jobject AccessBridgeJavaEntryPoints::getTopLevelObject(const jobject accessibleContext) { - jthrowable exception; jobject rAccessibleContext; PrintDebugString("[INFO]: In AccessBridgeJavaEntryPoints::getTopLevelObject(%p):", @@ -1093,7 +1086,6 @@ AccessBridgeJavaEntryPoints::getTopLevelObject(const jobject accessibleContext) */ jobject AccessBridgeJavaEntryPoints::getParentWithRoleElseRoot(const jobject accessibleContext, const wchar_t *role) { - jthrowable exception; jobject rAccessibleContext; PrintDebugString("[INFO]: In AccessBridgeJavaEntryPoints::getParentWithRoleElseRoot(%p):", @@ -1131,7 +1123,6 @@ AccessBridgeJavaEntryPoints::getParentWithRoleElseRoot(const jobject accessibleC */ jint AccessBridgeJavaEntryPoints::getObjectDepth(const jobject accessibleContext) { - jthrowable exception; jint rResult; PrintDebugString("[INFO]: In AccessBridgeJavaEntryPoints::getObjectDepth(%p):", @@ -1158,7 +1149,6 @@ AccessBridgeJavaEntryPoints::getObjectDepth(const jobject accessibleContext) { */ jobject AccessBridgeJavaEntryPoints::getActiveDescendent(const jobject accessibleContext) { - jthrowable exception; jobject rAccessibleContext; PrintDebugString("[INFO]: In AccessBridgeJavaEntryPoints::getActiveDescendent(%p):", @@ -1215,7 +1205,6 @@ AccessBridgeJavaEntryPoints::getVirtualAccessibleName ( jstring js = NULL; const wchar_t * stringBytes = NULL; - jthrowable exception = NULL; jsize length = 0; PrintDebugString("[INFO]: getVirtualAccessibleName called."); if (getVirtualAccessibleNameFromContextMethod != (jmethodID) 0) @@ -1266,7 +1255,6 @@ AccessBridgeJavaEntryPoints::getVirtualAccessibleName ( BOOL AccessBridgeJavaEntryPoints::requestFocus(const jobject accessibleContext) { - jthrowable exception; BOOL result = FALSE; PrintDebugString("[INFO]: In AccessBridgeJavaEntryPoints::requestFocus(%p):", @@ -1294,7 +1282,6 @@ AccessBridgeJavaEntryPoints::requestFocus(const jobject accessibleContext) { BOOL AccessBridgeJavaEntryPoints::selectTextRange(const jobject accessibleContext, int startIndex, int endIndex) { - jthrowable exception; BOOL result = FALSE; PrintDebugString("[INFO]: In AccessBridgeJavaEntryPoints::selectTextRange(%p start = %d end = %d):", @@ -1362,7 +1349,6 @@ AccessBridgeJavaEntryPoints::getTextAttributesInRange(const jobject accessibleCo jstring js; const wchar_t *stringBytes; - jthrowable exception; jsize length; BOOL result = FALSE; @@ -1429,7 +1415,6 @@ AccessBridgeJavaEntryPoints::getTextAttributesInRange(const jobject accessibleCo int AccessBridgeJavaEntryPoints::getVisibleChildrenCount(const jobject accessibleContext) { - jthrowable exception; PrintDebugString("[INFO]: ##### AccessBridgeJavaEntryPoints::getVisibleChildrenCount(%p)", accessibleContext); @@ -1455,8 +1440,6 @@ BOOL AccessBridgeJavaEntryPoints::getVisibleChildren(const jobject accessibleCon const int nStartIndex, /* OUT */ VisibleChildrenInfo *visibleChildrenInfo) { - jthrowable exception; - PrintDebugString("[INFO]: ##### AccessBridgeJavaEntryPoints::getVisibleChildren(%p, startIndex = %d)", accessibleContext, nStartIndex); @@ -1500,7 +1483,6 @@ BOOL AccessBridgeJavaEntryPoints::getVisibleChildren(const jobject accessibleCon BOOL AccessBridgeJavaEntryPoints::setCaretPosition(const jobject accessibleContext, int position) { - jthrowable exception; BOOL result = FALSE; PrintDebugString("[INFO]: In AccessBridgeJavaEntryPoints::setCaretPostion(%p position = %d):", @@ -1531,7 +1513,6 @@ BOOL AccessBridgeJavaEntryPoints::getVersionInfo(AccessBridgeVersionInfo *info) { jstring js; const wchar_t *stringBytes; - jthrowable exception; jsize length; PrintDebugString("[INFO]: Calling AccessBridgeJavaEntryPoints::getVersionInfo():"); @@ -1601,7 +1582,6 @@ AccessBridgeJavaEntryPoints::getVersionInfo(AccessBridgeVersionInfo *info) { BOOL AccessBridgeJavaEntryPoints::verifyAccessibleText(jobject obj) { JavaVM *vm; BOOL retval; - jthrowable exception; PrintDebugString("[INFO]: Calling AccessBridgeJavaEntryPoints::verifyAccessibleText"); @@ -1653,7 +1633,6 @@ jobject AccessBridgeJavaEntryPoints::getAccessibleContextAt(jint x, jint y, jobject accessibleContext) { jobject returnedAccessibleContext; jobject globalRef; - jthrowable exception; PrintDebugString("[INFO]: Calling AccessBridgeJavaEntryPoints::getAccessibleContextAt(%d, %d, %p):", x, y, accessibleContext); @@ -1688,7 +1667,6 @@ jobject AccessBridgeJavaEntryPoints::getAccessibleContextWithFocus() { jobject returnedAccessibleContext; jobject globalRef; - jthrowable exception; PrintDebugString("[INFO]: Calling AccessBridgeJavaEntryPoints::getAccessibleContextWithFocus()"); @@ -1724,7 +1702,6 @@ AccessBridgeJavaEntryPoints::getAccessibleContextInfo(jobject accessibleContext, jstring js; const wchar_t *stringBytes; jobject returnedJobject; - jthrowable exception; jsize length; PrintDebugString("[INFO]: ##### Calling AccessBridgeJavaEntryPoints::getAccessibleContextInfo(%p):", accessibleContext); @@ -2156,7 +2133,6 @@ jobject AccessBridgeJavaEntryPoints::getAccessibleChildFromContext(jobject accessibleContext, jint childIndex) { jobject returnedAccessibleContext; jobject globalRef; - jthrowable exception; PrintDebugString("[INFO]: Calling AccessBridgeJavaEntryPoints::getAccessibleChildContext(%p, %d):", accessibleContext, childIndex); @@ -2188,7 +2164,6 @@ AccessBridgeJavaEntryPoints::getAccessibleParentFromContext(jobject accessibleCo { jobject returnedAccessibleContext; jobject globalRef; - jthrowable exception; PrintDebugString("[INFO]: Calling AccessBridgeJavaEntryPoints::getAccessibleParentFromContext(%p):", accessibleContext); @@ -2217,8 +2192,6 @@ BOOL AccessBridgeJavaEntryPoints::getAccessibleTableInfo(jobject accessibleContext, AccessibleTableInfo *tableInfo) { - jthrowable exception; - PrintDebugString("[INFO]: ##### Calling AccessBridgeJavaEntryPoints::getAccessibleTableInfo(%p):", accessibleContext); @@ -2292,8 +2265,6 @@ BOOL AccessBridgeJavaEntryPoints::getAccessibleTableCellInfo(jobject accessibleTable, jint row, jint column, AccessibleTableCellInfo *tableCellInfo) { - jthrowable exception; - PrintDebugString("[INFO]: ##### Calling AccessBridgeJavaEntryPoints::getAccessibleTableCellInfo(%p): row=%d, column=%d", accessibleTable, row, column); @@ -2373,8 +2344,6 @@ AccessBridgeJavaEntryPoints::getAccessibleTableCellInfo(jobject accessibleTable, BOOL AccessBridgeJavaEntryPoints::getAccessibleTableRowHeader(jobject acParent, AccessibleTableInfo *tableInfo) { - jthrowable exception; - PrintDebugString("[INFO]: ##### Calling AccessBridgeJavaEntryPoints::getAccessibleTableRowHeader(%p):", acParent); @@ -2428,7 +2397,6 @@ AccessBridgeJavaEntryPoints::getAccessibleTableRowHeader(jobject acParent, Acces BOOL AccessBridgeJavaEntryPoints::getAccessibleTableColumnHeader(jobject acParent, AccessibleTableInfo *tableInfo) { - jthrowable exception; PrintDebugString("[INFO]: ##### Calling AccessBridgeJavaEntryPoints::getAccessibleTableColumnHeader(%p):", acParent); @@ -2485,7 +2453,6 @@ AccessBridgeJavaEntryPoints::getAccessibleTableRowDescription(jobject acParent, jobject returnedAccessibleContext; jobject globalRef; - jthrowable exception; PrintDebugString("[INFO]: ##### Calling AccessBridgeJavaEntryPoints::getAccessibleTableRowDescription(%p):", acParent); @@ -2513,7 +2480,6 @@ AccessBridgeJavaEntryPoints::getAccessibleTableColumnDescription(jobject acParen jobject returnedAccessibleContext; jobject globalRef; - jthrowable exception; PrintDebugString("[INFO]: ##### Calling AccessBridgeJavaEntryPoints::getAccessibleTableColumnDescription(%p):", acParent); @@ -2540,7 +2506,6 @@ AccessBridgeJavaEntryPoints::getAccessibleTableColumnDescription(jobject acParen jint AccessBridgeJavaEntryPoints::getAccessibleTableRowSelectionCount(jobject accessibleTable) { - jthrowable exception; jint count; PrintDebugString("[INFO]: ##### AccessBridgeJavaEntryPoints::getAccessibleTableRowSelectionCount(%p)", @@ -2565,7 +2530,6 @@ AccessBridgeJavaEntryPoints::getAccessibleTableRowSelectionCount(jobject accessi BOOL AccessBridgeJavaEntryPoints::isAccessibleTableRowSelected(jobject accessibleTable, jint row) { - jthrowable exception; BOOL result; PrintDebugString("[INFO]: ##### AccessBridgeJavaEntryPoints::isAccessibleTableRowSelected(%p, %d)", @@ -2591,7 +2555,6 @@ BOOL AccessBridgeJavaEntryPoints::getAccessibleTableRowSelections(jobject accessibleTable, jint count, jint *selections) { - jthrowable exception; PrintDebugString("[INFO]: ##### AccessBridgeJavaEntryPoints::getAccessibleTableRowSelections(%p, %d %p)", accessibleTable, count, selections); @@ -2618,7 +2581,6 @@ AccessBridgeJavaEntryPoints::getAccessibleTableRowSelections(jobject accessibleT jint AccessBridgeJavaEntryPoints::getAccessibleTableColumnSelectionCount(jobject accessibleTable) { - jthrowable exception; jint count; PrintDebugString("[INFO]: ##### AccessBridgeJavaEntryPoints::getAccessibleTableColumnSelectionCount(%p)", @@ -2643,7 +2605,6 @@ AccessBridgeJavaEntryPoints::getAccessibleTableColumnSelectionCount(jobject acce BOOL AccessBridgeJavaEntryPoints::isAccessibleTableColumnSelected(jobject accessibleTable, jint column) { - jthrowable exception; BOOL result; PrintDebugString("[INFO]: ##### AccessBridgeJavaEntryPoints::isAccessibleTableColumnSelected(%p, %d)", @@ -2668,7 +2629,6 @@ AccessBridgeJavaEntryPoints::isAccessibleTableColumnSelected(jobject accessibleT BOOL AccessBridgeJavaEntryPoints::getAccessibleTableColumnSelections(jobject accessibleTable, jint count, jint *selections) { - jthrowable exception; PrintDebugString("[INFO]: ##### AccessBridgeJavaEntryPoints::getAccessibleTableColumnSelections(%p, %d, %p)", accessibleTable, count, selections); @@ -2694,7 +2654,6 @@ AccessBridgeJavaEntryPoints::getAccessibleTableColumnSelections(jobject accessib jint AccessBridgeJavaEntryPoints::getAccessibleTableRow(jobject accessibleTable, jint index) { - jthrowable exception; jint result; PrintDebugString("[INFO]: ##### AccessBridgeJavaEntryPoints::getAccessibleTableRow(%p, index=%d)", @@ -2718,7 +2677,6 @@ AccessBridgeJavaEntryPoints::getAccessibleTableRow(jobject accessibleTable, jint jint AccessBridgeJavaEntryPoints::getAccessibleTableColumn(jobject accessibleTable, jint index) { - jthrowable exception; jint result; PrintDebugString("[INFO]: ##### AccessBridgeJavaEntryPoints::getAccessibleTableColumn(%p, index=%d)", @@ -2742,7 +2700,6 @@ AccessBridgeJavaEntryPoints::getAccessibleTableColumn(jobject accessibleTable, j jint AccessBridgeJavaEntryPoints::getAccessibleTableIndex(jobject accessibleTable, jint row, jint column) { - jthrowable exception; jint result; PrintDebugString("[INFO]: ##### AccessBridgeJavaEntryPoints::getAccessibleTableIndex(%p, row=%d, col=%d)", @@ -2773,7 +2730,6 @@ BOOL AccessBridgeJavaEntryPoints::getAccessibleRelationSet(jobject accessibleContext, AccessibleRelationSetInfo *relationSet) { - jthrowable exception; const wchar_t *stringBytes; jsize length; @@ -2853,7 +2809,6 @@ BOOL AccessBridgeJavaEntryPoints::getAccessibleHypertext(jobject accessibleContext, AccessibleHypertextInfo *hypertext) { - jthrowable exception; const wchar_t *stringBytes; jsize length; @@ -2953,7 +2908,6 @@ BOOL AccessBridgeJavaEntryPoints::activateAccessibleHyperlink(jobject accessibleContext, jobject accessibleHyperlink) { - jthrowable exception; BOOL returnVal; PrintDebugString("[INFO]: Calling AccessBridgeJavaEntryPoints::activateAccessibleHyperlink(%p, %p):", @@ -2983,7 +2937,6 @@ AccessBridgeJavaEntryPoints::getAccessibleHypertextExt(const jobject accessibleC const jint nStartIndex, /* OUT */ AccessibleHypertextInfo *hypertext) { - jthrowable exception; const wchar_t *stringBytes; jsize length; PrintDebugString("[INFO]: ##### AccessBridgeJavaEntryPoints::getAccessibleHypertextExt(%p, %p, startIndex = %d)", @@ -3084,8 +3037,6 @@ AccessBridgeJavaEntryPoints::getAccessibleHypertextExt(const jobject accessibleC jint AccessBridgeJavaEntryPoints::getAccessibleHyperlinkCount(const jobject accessibleContext) { - jthrowable exception; - PrintDebugString("[INFO]: ##### AccessBridgeJavaEntryPoints::getAccessibleHyperlinkCount(%X)", accessibleContext); @@ -3106,8 +3057,6 @@ jint AccessBridgeJavaEntryPoints::getAccessibleHyperlinkCount(const jobject acce jint AccessBridgeJavaEntryPoints::getAccessibleHypertextLinkIndex(const jobject hypertext, const jint nIndex) { - jthrowable exception; - PrintDebugString("[INFO]: ##### AccessBridgeJavaEntryPoints::getAccessibleHypertextLinkIndex(%p, index = %d)", hypertext, nIndex); @@ -3129,7 +3078,6 @@ BOOL AccessBridgeJavaEntryPoints::getAccessibleHyperlink(jobject hypertext, const jint index, /* OUT */ AccessibleHyperlinkInfo *info) { - jthrowable exception; const wchar_t *stringBytes; jsize length; @@ -3202,8 +3150,6 @@ BOOL AccessBridgeJavaEntryPoints::getAccessibleHyperlink(jobject hypertext, BOOL AccessBridgeJavaEntryPoints::getAccessibleKeyBindings(jobject accessibleContext, AccessibleKeyBindings *keyBindings) { - jthrowable exception; - PrintDebugString("[INFO]: ##### AccessBridgeJavaEntryPoints::getAccessibleKeyBindings(%p, %p)", accessibleContext, keyBindings); @@ -3249,7 +3195,6 @@ BOOL AccessBridgeJavaEntryPoints::getAccessibleKeyBindings(jobject accessibleCon BOOL AccessBridgeJavaEntryPoints::getAccessibleIcons(jobject accessibleContext, AccessibleIcons *icons) { - jthrowable exception; const wchar_t *stringBytes; jsize length; @@ -3328,7 +3273,6 @@ BOOL AccessBridgeJavaEntryPoints::getAccessibleIcons(jobject accessibleContext, BOOL AccessBridgeJavaEntryPoints::getAccessibleActions(jobject accessibleContext, AccessibleActions *actions) { - jthrowable exception; const wchar_t *stringBytes; jsize length; @@ -3388,7 +3332,6 @@ BOOL AccessBridgeJavaEntryPoints::doAccessibleActions(jobject accessibleContext, AccessibleActionsToDo *actionsToDo, jint *failure) { - jthrowable exception; BOOL returnVal; PrintDebugString("[INFO]: Calling AccessBridgeJavaEntryPoints::doAccessibleActions(%p, #actions %d %s):", @@ -3436,7 +3379,6 @@ BOOL AccessBridgeJavaEntryPoints::getAccessibleTextInfo(jobject accessibleContext, AccessibleTextInfo *textInfo, jint x, jint y) { - jthrowable exception; // Verify the Java VM still exists and AccessibleContext is // an instance of AccessibleText @@ -3495,7 +3437,6 @@ AccessBridgeJavaEntryPoints::getAccessibleTextItems(jobject accessibleContext, AccessibleTextItemsInfo *textItems, jint index) { jstring js; const wchar_t *stringBytes; - jthrowable exception; jsize length; PrintDebugString("[INFO]: Calling AccessBridgeJavaEntryPoints::getAccessibleTextItems(%p):", accessibleContext); @@ -3607,7 +3548,6 @@ AccessBridgeJavaEntryPoints::getAccessibleTextSelectionInfo(jobject accessibleCo AccessibleTextSelectionInfo *selectionInfo) { jstring js; const wchar_t *stringBytes; - jthrowable exception; jsize length; PrintDebugString("[INFO]: Calling AccessBridgeJavaEntryPoints::getAccessibleTextSelectionInfo(%p):", @@ -3680,7 +3620,6 @@ AccessBridgeJavaEntryPoints::getAccessibleTextAttributes(jobject accessibleConte jstring js; const wchar_t *stringBytes; jobject AttributeSet; - jthrowable exception; jsize length; PrintDebugString("[INFO]: Calling AccessBridgeJavaEntryPoints::getAccessibleTextAttributes(%p):", accessibleContext); @@ -4174,8 +4113,6 @@ AccessBridgeJavaEntryPoints::getAccessibleTextAttributes(jobject accessibleConte BOOL AccessBridgeJavaEntryPoints::getAccessibleTextRect(jobject accessibleContext, AccessibleTextRectInfo *rectInfo, jint index) { - jthrowable exception; - PrintDebugString("[INFO]: Calling AccessBridgeJavaEntryPoints::getAccessibleTextRect(%p), index = %d", accessibleContext, index); @@ -4244,8 +4181,6 @@ AccessBridgeJavaEntryPoints::getAccessibleTextRect(jobject accessibleContext, Ac BOOL AccessBridgeJavaEntryPoints::getCaretLocation(jobject accessibleContext, AccessibleTextRectInfo *rectInfo, jint index) { - jthrowable exception; - PrintDebugString("[INFO]: Calling AccessBridgeJavaEntryPoints::getCaretLocation(%p), index = %d", accessibleContext, index); @@ -4311,8 +4246,6 @@ AccessBridgeJavaEntryPoints::getCaretLocation(jobject accessibleContext, Accessi BOOL AccessBridgeJavaEntryPoints::getAccessibleTextLineBounds(jobject accessibleContext, jint index, jint *startIndex, jint *endIndex) { - jthrowable exception; - PrintDebugString("[INFO]: Calling AccessBridgeJavaEntryPoints::getAccessibleTextLineBounds(%p):", accessibleContext); // Verify the Java VM still exists and AccessibleContext is @@ -4353,7 +4286,6 @@ AccessBridgeJavaEntryPoints::getAccessibleTextRange(jobject accessibleContext, jint start, jint end, wchar_t *text, short len) { jstring js; const wchar_t *stringBytes; - jthrowable exception; jsize length; PrintDebugString("[INFO]: Calling AccessBridgeJavaEntryPoints::getAccessibleTextRange(%p, %d, %d, *text, %d):", accessibleContext, start, end, len); @@ -4412,7 +4344,6 @@ BOOL AccessBridgeJavaEntryPoints::getCurrentAccessibleValueFromContext(jobject accessibleContext, wchar_t *value, short len) { jstring js; const wchar_t *stringBytes; - jthrowable exception; jsize length; PrintDebugString("[INFO]: Calling AccessBridgeJavaEntryPoints::getCurrentAccessibleValueFromContext(%p):", accessibleContext); @@ -4453,7 +4384,6 @@ BOOL AccessBridgeJavaEntryPoints::getMaximumAccessibleValueFromContext(jobject accessibleContext, wchar_t *value, short len) { jstring js; const wchar_t *stringBytes; - jthrowable exception; jsize length; PrintDebugString("[INFO]: Calling AccessBridgeJavaEntryPoints::getMaximumAccessibleValueFromContext(%p):", accessibleContext); @@ -4494,7 +4424,6 @@ BOOL AccessBridgeJavaEntryPoints::getMinimumAccessibleValueFromContext(jobject accessibleContext, wchar_t *value, short len) { jstring js; const wchar_t *stringBytes; - jthrowable exception; jsize length; PrintDebugString("[INFO]: Calling AccessBridgeJavaEntryPoints::getMinimumAccessibleValueFromContext(%p):", accessibleContext); @@ -4536,7 +4465,6 @@ AccessBridgeJavaEntryPoints::getMinimumAccessibleValueFromContext(jobject access void AccessBridgeJavaEntryPoints::addAccessibleSelectionFromContext(jobject accessibleContext, int i) { - jthrowable exception; PrintDebugString("[INFO]: Calling AccessBridgeJavaEntryPoints::addAccessibleSelectionFromContext(%p):", accessibleContext); @@ -4554,7 +4482,6 @@ AccessBridgeJavaEntryPoints::addAccessibleSelectionFromContext(jobject accessibl void AccessBridgeJavaEntryPoints::clearAccessibleSelectionFromContext(jobject accessibleContext) { - jthrowable exception; PrintDebugString("[INFO]: Calling AccessBridgeJavaEntryPoints::clearAccessibleSelectionFromContext(%p):", accessibleContext); @@ -4574,7 +4501,6 @@ jobject AccessBridgeJavaEntryPoints::getAccessibleSelectionFromContext(jobject accessibleContext, int i) { jobject returnedAccessibleContext; jobject globalRef; - jthrowable exception; PrintDebugString("[INFO]: Calling AccessBridgeJavaEntryPoints::getAccessibleSelectionFromContext(%p):", accessibleContext); @@ -4600,7 +4526,6 @@ AccessBridgeJavaEntryPoints::getAccessibleSelectionFromContext(jobject accessibl int AccessBridgeJavaEntryPoints::getAccessibleSelectionCountFromContext(jobject accessibleContext) { int count; - jthrowable exception; PrintDebugString("[INFO]: Calling AccessBridgeJavaEntryPoints::getAccessibleSelectionCountFromContext(%p):", accessibleContext); @@ -4621,7 +4546,6 @@ AccessBridgeJavaEntryPoints::getAccessibleSelectionCountFromContext(jobject acce BOOL AccessBridgeJavaEntryPoints::isAccessibleChildSelectedFromContext(jobject accessibleContext, int i) { jboolean result; - jthrowable exception; PrintDebugString("[INFO]: Calling AccessBridgeJavaEntryPoints::isAccessibleChildSelectedFromContext(%p):", accessibleContext); @@ -4644,7 +4568,6 @@ AccessBridgeJavaEntryPoints::isAccessibleChildSelectedFromContext(jobject access void AccessBridgeJavaEntryPoints::removeAccessibleSelectionFromContext(jobject accessibleContext, int i) { - jthrowable exception; PrintDebugString("[INFO]: Calling AccessBridgeJavaEntryPoints::removeAccessibleSelectionFromContext(%p):", accessibleContext); @@ -4662,7 +4585,6 @@ AccessBridgeJavaEntryPoints::removeAccessibleSelectionFromContext(jobject access void AccessBridgeJavaEntryPoints::selectAllAccessibleSelectionFromContext(jobject accessibleContext) { - jthrowable exception; PrintDebugString("[INFO]: Calling AccessBridgeJavaEntryPoints::selectAllAccessibleSelectionFromContext(%p):", accessibleContext); @@ -4683,7 +4605,6 @@ AccessBridgeJavaEntryPoints::selectAllAccessibleSelectionFromContext(jobject acc BOOL AccessBridgeJavaEntryPoints::addJavaEventNotification(jlong type) { - jthrowable exception; PrintDebugString("[INFO]: in AccessBridgeJavaEntryPoints::addJavaEventNotification(%016I64X);", type); @@ -4701,7 +4622,6 @@ AccessBridgeJavaEntryPoints::addJavaEventNotification(jlong type) { BOOL AccessBridgeJavaEntryPoints::removeJavaEventNotification(jlong type) { - jthrowable exception; PrintDebugString("[INFO]: in AccessBridgeJavaEntryPoints::removeJavaEventNotification(%016I64X):", type); @@ -4719,7 +4639,6 @@ AccessBridgeJavaEntryPoints::removeJavaEventNotification(jlong type) { BOOL AccessBridgeJavaEntryPoints::addAccessibilityEventNotification(jlong type) { - jthrowable exception; PrintDebugString("[INFO]: in AccessBridgeJavaEntryPoints::addAccessibilityEventNotification(%016I64X);", type); @@ -4739,7 +4658,6 @@ AccessBridgeJavaEntryPoints::addAccessibilityEventNotification(jlong type) { BOOL AccessBridgeJavaEntryPoints::removeAccessibilityEventNotification(jlong type) { - jthrowable exception; PrintDebugString("[INFO]: in AccessBridgeJavaEntryPoints::removeAccessibilityEventNotification(%016I64X):", type); @@ -4753,4 +4671,4 @@ AccessBridgeJavaEntryPoints::removeAccessibilityEventNotification(jlong type) { return FALSE; } return TRUE; -} +} \ No newline at end of file From f6f73ce70da0bea31b93a397da7f7912d1642c09 Mon Sep 17 00:00:00 2001 From: Brian Burkhalter Date: Tue, 19 Nov 2024 20:30:02 +0000 Subject: [PATCH 25/74] 8344446: Remove security manager dependency from module jdk.sctp Reviewed-by: mullan, alanb --- .../sun/nio/ch/sctp/SctpChannelImpl.java | 24 ++-------- .../sun/nio/ch/sctp/SctpMultiChannelImpl.java | 27 +---------- .../unix/classes/sun/nio/ch/sctp/SctpNet.java | 45 +++---------------- .../nio/ch/sctp/SctpServerChannelImpl.java | 18 +------- 4 files changed, 11 insertions(+), 103 deletions(-) diff --git a/src/jdk.sctp/unix/classes/sun/nio/ch/sctp/SctpChannelImpl.java b/src/jdk.sctp/unix/classes/sun/nio/ch/sctp/SctpChannelImpl.java index 2e12e67c6c72c..2a676e55a9053 100644 --- a/src/jdk.sctp/unix/classes/sun/nio/ch/sctp/SctpChannelImpl.java +++ b/src/jdk.sctp/unix/classes/sun/nio/ch/sctp/SctpChannelImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 2024, 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 @@ -30,8 +30,6 @@ import java.net.InetSocketAddress; import java.io.FileDescriptor; import java.io.IOException; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.Collections; import java.util.Set; import java.util.HashSet; @@ -194,11 +192,6 @@ public SctpChannel bind(SocketAddress local) throws IOException { SctpNet.throwAlreadyBoundException(); InetSocketAddress isa = (local == null) ? new InetSocketAddress(0) : Net.checkAddress(local); - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkListen(isa.getPort()); - } Net.bind(fd, isa.getAddress(), isa.getPort()); InetSocketAddress boundIsa = Net.localAddress(fd); port = boundIsa.getPort(); @@ -364,11 +357,6 @@ public boolean connect(SocketAddress endpoint) throws IOException { synchronized (sendLock) { ensureOpenAndUnconnected(); InetSocketAddress isa = Net.checkAddress(endpoint); - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) - sm.checkConnect(isa.getAddress().getHostAddress(), - isa.getPort()); synchronized (blockingLock()) { int n = 0; try { @@ -1094,16 +1082,10 @@ static native int send0(int fd, long address, int length, loadSctpLibrary(); } - @SuppressWarnings({"removal", "restricted"}) + @SuppressWarnings("restricted") private static void loadSctpLibrary() { IOUtil.load(); /* loads nio & net native libraries */ - AccessController.doPrivileged( - new PrivilegedAction<>() { - public Void run() { - System.loadLibrary("sctp"); - return null; - } - }); + System.loadLibrary("sctp"); initIDs(); } } diff --git a/src/jdk.sctp/unix/classes/sun/nio/ch/sctp/SctpMultiChannelImpl.java b/src/jdk.sctp/unix/classes/sun/nio/ch/sctp/SctpMultiChannelImpl.java index b1b721c99762c..4a3f18e6b083d 100644 --- a/src/jdk.sctp/unix/classes/sun/nio/ch/sctp/SctpMultiChannelImpl.java +++ b/src/jdk.sctp/unix/classes/sun/nio/ch/sctp/SctpMultiChannelImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 2024, 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 @@ -149,10 +149,6 @@ public SctpMultiChannel bind(SocketAddress local, int backlog) InetSocketAddress isa = (local == null) ? new InetSocketAddress(0) : Net.checkAddress(local); - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) - sm.checkListen(isa.getPort()); Net.bind(fd, isa.getAddress(), isa.getPort()); InetSocketAddress boundIsa = Net.localAddress(fd); @@ -508,21 +504,6 @@ public MessageInfo receive(ByteBuffer buffer, resultContainer.getMessageInfo(); info.setAssociation(lookupAssociation(info. associationID())); - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - InetSocketAddress isa = (InetSocketAddress)info.address(); - if (!addressMap.containsKey(isa)) { - /* must be a new association */ - try { - sm.checkAccept(isa.getAddress().getHostAddress(), - isa.getPort()); - } catch (SecurityException se) { - buffer.clear(); - throw se; - } - } - } assert info.association() != null; return info; @@ -805,12 +786,6 @@ public int send(ByteBuffer buffer, MessageInfo messageInfo) checkStreamNumber(association, messageInfo.streamNumber()); assocId = association.associationID(); - } else { /* must be new association */ - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) - sm.checkConnect(addr.getAddress().getHostAddress(), - addr.getPort()); } } else { throw new AssertionError( diff --git a/src/jdk.sctp/unix/classes/sun/nio/ch/sctp/SctpNet.java b/src/jdk.sctp/unix/classes/sun/nio/ch/sctp/SctpNet.java index decf964c6cb72..a12049cbcf05d 100644 --- a/src/jdk.sctp/unix/classes/sun/nio/ch/sctp/SctpNet.java +++ b/src/jdk.sctp/unix/classes/sun/nio/ch/sctp/SctpNet.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 2024, 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 @@ -32,8 +32,6 @@ import java.nio.channels.AlreadyBoundException; import java.util.Set; import java.util.HashSet; -import java.security.AccessController; -import java.security.PrivilegedAction; import sun.net.util.IPAddressUtil; import sun.nio.ch.IOUtil; import sun.nio.ch.Net; @@ -91,41 +89,14 @@ static Set getLocalAddresses(int fd) SocketAddress[] saa = getLocalAddresses0(fd); if (saa != null) { - set = getRevealedLocalAddressSet(saa); + set = new HashSet<>(saa.length); + for (SocketAddress sa : saa) + set.add(sa); } return set; } - private static Set getRevealedLocalAddressSet( - SocketAddress[] saa) - { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - Set set = new HashSet<>(saa.length); - for (SocketAddress sa : saa) { - set.add(getRevealedLocalAddress(sa, sm)); - } - return set; - } - - private static SocketAddress getRevealedLocalAddress(SocketAddress sa, - @SuppressWarnings("removal") SecurityManager sm) - { - if (sm == null || sa == null) - return sa; - InetSocketAddress ia = (InetSocketAddress)sa; - try{ - sm.checkConnect(ia.getAddress().getHostAddress(), -1); - // Security check passed - } catch (SecurityException e) { - // Return loopback address - return new InetSocketAddress(InetAddress.getLoopbackAddress(), - ia.getPort()); - } - return sa; - } - static Set getRemoteAddresses(int fd, int assocId) throws IOException { Set set = null; @@ -336,13 +307,7 @@ static native void setInitMsgOption0(int fd, int arg1, int arg2) @SuppressWarnings({"removal", "restricted"}) private static void loadSctpLibrary() { IOUtil.load(); // loads nio & net native libraries - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Void run() { - System.loadLibrary("sctp"); - return null; - } - }); + System.loadLibrary("sctp"); init(); } } diff --git a/src/jdk.sctp/unix/classes/sun/nio/ch/sctp/SctpServerChannelImpl.java b/src/jdk.sctp/unix/classes/sun/nio/ch/sctp/SctpServerChannelImpl.java index 0f710a4c67048..4b2be742c6d32 100644 --- a/src/jdk.sctp/unix/classes/sun/nio/ch/sctp/SctpServerChannelImpl.java +++ b/src/jdk.sctp/unix/classes/sun/nio/ch/sctp/SctpServerChannelImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 2024, 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 @@ -109,10 +109,6 @@ public SctpServerChannel bind(SocketAddress local, int backlog) InetSocketAddress isa = (local == null) ? new InetSocketAddress(0) : Net.checkAddress(local); - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) - sm.checkListen(isa.getPort()); Net.bind(fd, isa.getAddress(), isa.getPort()); InetSocketAddress boundIsa = Net.localAddress(fd); @@ -217,7 +213,6 @@ public SctpChannel accept() throws IOException { throw new ClosedChannelException(); if (!isBound()) throw new NotYetBoundException(); - SctpChannel sc = null; int n = 0; FileDescriptor newfd = new FileDescriptor(); @@ -244,16 +239,7 @@ public SctpChannel accept() throws IOException { return null; IOUtil.configureBlocking(newfd, true); - InetSocketAddress isa = isaa[0]; - sc = new SctpChannelImpl(provider(), newfd); - - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) - sm.checkAccept(isa.getAddress().getHostAddress(), - isa.getPort()); - - return sc; + return new SctpChannelImpl(provider(), newfd); } } From 81e43114eca5199a0d816c02f50ecb6bc370135b Mon Sep 17 00:00:00 2001 From: Brian Burkhalter Date: Tue, 19 Nov 2024 20:30:22 +0000 Subject: [PATCH 26/74] 8344077: Remove security manager dependency in java.io Reviewed-by: rriggs, alanb, naoto, lancea --- .../share/classes/java/io/Console.java | 29 ++-- src/java.base/share/classes/java/io/File.java | 138 +----------------- .../classes/java/io/FileInputStream.java | 18 +-- .../classes/java/io/FileOutputStream.java | 19 +-- .../share/classes/java/io/FilePermission.java | 38 ++--- .../classes/java/io/RandomAccessFile.java | 8 - .../java/io/SerializablePermission.java | 3 +- .../unix/classes/java/io/UnixFileSystem.java | 19 +-- .../classes/java/io/WinNTFileSystem.java | 42 +----- 9 files changed, 41 insertions(+), 273 deletions(-) diff --git a/src/java.base/share/classes/java/io/Console.java b/src/java.base/share/classes/java/io/Console.java index d8ba0439d4726..3881b2380ad85 100644 --- a/src/java.base/share/classes/java/io/Console.java +++ b/src/java.base/share/classes/java/io/Console.java @@ -25,8 +25,6 @@ package java.io; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.*; import java.nio.charset.Charset; import jdk.internal.access.JavaIOAccess; @@ -659,9 +657,8 @@ public Console console() { }); } - @SuppressWarnings("removal") private static Console instantiateConsole() { - Console c; + Console c = null; try { /* @@ -673,25 +670,19 @@ private static Console instantiateConsole() { * If no providers are available, or instantiation failed, java.base built-in * Console implementation is used. */ - c = AccessController.doPrivileged(new PrivilegedAction() { - public Console run() { - var consModName = System.getProperty("jdk.console", - JdkConsoleProvider.DEFAULT_PROVIDER_MODULE_NAME); + var consModName = System.getProperty("jdk.console", + JdkConsoleProvider.DEFAULT_PROVIDER_MODULE_NAME); - for (var jcp : ServiceLoader.load(ModuleLayer.boot(), JdkConsoleProvider.class)) { - if (consModName.equals(jcp.getClass().getModule().getName())) { - var jc = jcp.console(istty, CHARSET); - if (jc != null) { - return new ProxyingConsole(jc); - } - break; - } + for (var jcp : ServiceLoader.load(ModuleLayer.boot(), JdkConsoleProvider.class)) { + if (consModName.equals(jcp.getClass().getModule().getName())) { + var jc = jcp.console(istty, CHARSET); + if (jc != null) { + c = new ProxyingConsole(jc); } - return null; + break; } - }); + } } catch (ServiceConfigurationError _) { - c = null; } // If not found, default to built-in Console diff --git a/src/java.base/share/classes/java/io/File.java b/src/java.base/share/classes/java/io/File.java index b8eda9dcf8315..3cfeb7ffdeef3 100644 --- a/src/java.base/share/classes/java/io/File.java +++ b/src/java.base/share/classes/java/io/File.java @@ -751,11 +751,6 @@ public URI toURI() { * application; {@code false} otherwise */ public boolean canRead() { - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); - if (security != null) { - security.checkRead(path); - } if (isInvalid()) { return false; } @@ -775,11 +770,6 @@ public boolean canRead() { * {@code false} otherwise. */ public boolean canWrite() { - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); - if (security != null) { - security.checkWrite(path); - } if (isInvalid()) { return false; } @@ -794,11 +784,6 @@ public boolean canWrite() { * by this abstract pathname exists; {@code false} otherwise */ public boolean exists() { - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); - if (security != null) { - security.checkRead(path); - } if (isInvalid()) { return false; } @@ -820,11 +805,6 @@ public boolean exists() { * {@code false} otherwise */ public boolean isDirectory() { - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); - if (security != null) { - security.checkRead(path); - } if (isInvalid()) { return false; } @@ -848,11 +828,6 @@ public boolean isDirectory() { * {@code false} otherwise */ public boolean isFile() { - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); - if (security != null) { - security.checkRead(path); - } if (isInvalid()) { return false; } @@ -881,11 +856,6 @@ public boolean isFile() { * @since 1.2 */ public boolean isHidden() { - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); - if (security != null) { - security.checkRead(path); - } if (isInvalid()) { return false; } @@ -920,11 +890,6 @@ public boolean isHidden() { * epoch */ public long lastModified() { - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); - if (security != null) { - security.checkRead(path); - } if (isInvalid()) { return 0L; } @@ -947,11 +912,6 @@ public long lastModified() { * denoting system-dependent entities such as devices or pipes. */ public long length() { - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); - if (security != null) { - security.checkRead(path); - } if (isInvalid()) { return 0L; } @@ -983,9 +943,6 @@ public long length() { * @since 1.2 */ public boolean createNewFile() throws IOException { - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); - if (security != null) security.checkWrite(path); if (isInvalid()) { throw new IOException("Invalid file path"); } @@ -1007,11 +964,6 @@ public boolean createNewFile() throws IOException { * successfully deleted; {@code false} otherwise */ public boolean delete() { - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); - if (security != null) { - security.checkDelete(path); - } if (isInvalid()) { return false; } @@ -1043,11 +995,6 @@ public boolean delete() { * @since 1.2 */ public void deleteOnExit() { - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); - if (security != null) { - security.checkDelete(path); - } if (isInvalid()) { return; } @@ -1097,11 +1044,6 @@ public String[] list() { * I/O error occurs. */ private final String[] normalizedList() { - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); - if (security != null) { - security.checkRead(path); - } if (isInvalid()) { return null; } @@ -1275,11 +1217,6 @@ public File[] listFiles(FileFilter filter) { * created; {@code false} otherwise */ public boolean mkdir() { - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); - if (security != null) { - security.checkWrite(path); - } if (isInvalid()) { return false; } @@ -1345,12 +1282,6 @@ public boolean renameTo(File dest) { if (dest == null) { throw new NullPointerException(); } - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); - if (security != null) { - security.checkWrite(path); - security.checkWrite(dest.path); - } if (this.isInvalid() || dest.isInvalid()) { return false; } @@ -1380,11 +1311,6 @@ public boolean renameTo(File dest) { */ public boolean setLastModified(long time) { if (time < 0) throw new IllegalArgumentException("Negative time"); - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); - if (security != null) { - security.checkWrite(path); - } if (isInvalid()) { return false; } @@ -1406,11 +1332,6 @@ public boolean setLastModified(long time) { * @since 1.2 */ public boolean setReadOnly() { - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); - if (security != null) { - security.checkWrite(path); - } if (isInvalid()) { return false; } @@ -1445,11 +1366,6 @@ public boolean setReadOnly() { * @since 1.6 */ public boolean setWritable(boolean writable, boolean ownerOnly) { - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); - if (security != null) { - security.checkWrite(path); - } if (isInvalid()) { return false; } @@ -1517,11 +1433,6 @@ public boolean setWritable(boolean writable) { * @since 1.6 */ public boolean setReadable(boolean readable, boolean ownerOnly) { - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); - if (security != null) { - security.checkWrite(path); - } if (isInvalid()) { return false; } @@ -1595,11 +1506,6 @@ public boolean setReadable(boolean readable) { * @since 1.6 */ public boolean setExecutable(boolean executable, boolean ownerOnly) { - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); - if (security != null) { - security.checkWrite(path); - } if (isInvalid()) { return false; } @@ -1652,11 +1558,6 @@ public boolean setExecutable(boolean executable) { * @since 1.6 */ public boolean canExecute() { - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); - if (security != null) { - security.checkExec(path); - } if (isInvalid()) { return false; } @@ -1726,12 +1627,6 @@ public static File[] listRoots() { * @see FileStore#getTotalSpace */ public long getTotalSpace() { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPermission(new RuntimePermission("getFileSystemAttributes")); - sm.checkRead(path); - } if (isInvalid()) { return 0L; } @@ -1764,12 +1659,6 @@ public long getTotalSpace() { * @see FileStore#getUnallocatedSpace */ public long getFreeSpace() { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPermission(new RuntimePermission("getFileSystemAttributes")); - sm.checkRead(path); - } if (isInvalid()) { return 0L; } @@ -1805,12 +1694,6 @@ public long getFreeSpace() { * @see FileStore#getUsableSpace */ public long getUsableSpace() { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPermission(new RuntimePermission("getFileSystemAttributes")); - sm.checkRead(path); - } if (isInvalid()) { return 0L; } @@ -1840,7 +1723,6 @@ private static int shortenSubName(int subNameLength, int excess, } return subNameLength; } - @SuppressWarnings("removal") static File generateFile(String prefix, String suffix, File dir) throws IOException { @@ -1897,11 +1779,8 @@ static File generateFile(String prefix, String suffix, File dir) File f = new File(dir, name); if (!name.equals(f.getName()) || f.isInvalid()) { - if (System.getSecurityManager() != null) - throw new IOException("Unable to create temporary file"); - else - throw new IOException("Unable to create temporary file, " - + name); + throw new IOException("Unable to create temporary file, " + + name); } return f; } @@ -1998,22 +1877,9 @@ public static File createTempFile(String prefix, String suffix, File tmpdir = (directory != null) ? directory : TempDirectory.location(); - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); File f; do { f = TempDirectory.generateFile(prefix, suffix, tmpdir); - - if (sm != null) { - try { - sm.checkWrite(f.getPath()); - } catch (SecurityException se) { - // don't reveal temporary directory location - if (directory == null) - throw new SecurityException("Unable to create temporary file"); - throw se; - } - } } while (FS.hasBooleanAttributes(f, FileSystem.BA_EXISTS)); if (!FS.createFileExclusively(f.getPath())) diff --git a/src/java.base/share/classes/java/io/FileInputStream.java b/src/java.base/share/classes/java/io/FileInputStream.java index e429faec09bd0..ab312fc8c5be0 100644 --- a/src/java.base/share/classes/java/io/FileInputStream.java +++ b/src/java.base/share/classes/java/io/FileInputStream.java @@ -130,22 +130,13 @@ public FileInputStream(String name) throws FileNotFoundException { */ @SuppressWarnings("this-escape") public FileInputStream(File file) throws FileNotFoundException { - String name = (file != null ? file.getPath() : null); - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); - if (security != null) { - security.checkRead(name); - } - if (name == null) { - throw new NullPointerException(); - } if (file.isInvalid()) { throw new FileNotFoundException("Invalid file path"); } + path = file.getPath(); fd = new FileDescriptor(); fd.attach(this); - path = name; - open(name); + open(path); FileCleanable.register(fd); // open set the fd, register the cleanup } @@ -166,14 +157,9 @@ public FileInputStream(File file) throws FileNotFoundException { */ @SuppressWarnings("this-escape") public FileInputStream(FileDescriptor fdObj) { - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); if (fdObj == null) { throw new NullPointerException(); } - if (security != null) { - security.checkRead(fdObj); - } fd = fdObj; path = null; diff --git a/src/java.base/share/classes/java/io/FileOutputStream.java b/src/java.base/share/classes/java/io/FileOutputStream.java index 557bea0c3fc51..6c5a30ea43232 100644 --- a/src/java.base/share/classes/java/io/FileOutputStream.java +++ b/src/java.base/share/classes/java/io/FileOutputStream.java @@ -199,23 +199,15 @@ public FileOutputStream(File file) throws FileNotFoundException { public FileOutputStream(File file, boolean append) throws FileNotFoundException { - String name = (file != null ? file.getPath() : null); - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); - if (security != null) { - security.checkWrite(name); - } - if (name == null) { - throw new NullPointerException(); - } if (file.isInvalid()) { throw new FileNotFoundException("Invalid file path"); } + this.path = file.getPath(); + this.fd = new FileDescriptor(); fd.attach(this); - this.path = name; - open(name, append); + open(this.path, append); FileCleanable.register(fd); // open sets the fd, register the cleanup } @@ -236,14 +228,9 @@ public FileOutputStream(File file, boolean append) */ @SuppressWarnings("this-escape") public FileOutputStream(FileDescriptor fdObj) { - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); if (fdObj == null) { throw new NullPointerException(); } - if (security != null) { - security.checkWrite(fdObj); - } this.fd = fdObj; this.path = null; diff --git a/src/java.base/share/classes/java/io/FilePermission.java b/src/java.base/share/classes/java/io/FilePermission.java index b11e0dd25bebe..30fa3978638c1 100644 --- a/src/java.base/share/classes/java/io/FilePermission.java +++ b/src/java.base/share/classes/java/io/FilePermission.java @@ -26,7 +26,8 @@ package java.io; import java.nio.file.*; -import java.security.*; +import java.security.Permission; +import java.security.PermissionCollection; import java.util.Enumeration; import java.util.Objects; import java.util.StringJoiner; @@ -36,7 +37,6 @@ import jdk.internal.access.JavaIOFilePermissionAccess; import jdk.internal.access.SharedSecrets; import sun.nio.fs.DefaultFileSystemProvider; -import sun.security.action.GetPropertyAction; import sun.security.util.FilePermCompat; import sun.security.util.SecurityConstants; @@ -181,8 +181,7 @@ public final class FilePermission extends Permission implements Serializable { private static final java.nio.file.FileSystem builtInFS = DefaultFileSystemProvider.theFileSystem(); - private static final Path here = builtInFS.getPath( - GetPropertyAction.privilegedGetProperty("user.dir")); + private static final Path here = builtInFS.getPath(jdk.internal.util.StaticProperty.userDir()); private static final Path EMPTY_PATH = builtInFS.getPath(""); private static final Path DASH_PATH = builtInFS.getPath("-"); @@ -361,25 +360,20 @@ private void init(int mask) { } // store only the canonical cpath if possible - cpath = AccessController.doPrivileged(new PrivilegedAction<>() { - public String run() { - try { - String path = cpath; - if (cpath.endsWith("*")) { - // call getCanonicalPath with a path with wildcard character - // replaced to avoid calling it with paths that are - // intended to match all entries in a directory - path = path.substring(0, path.length() - 1) + "-"; - path = new File(path).getCanonicalPath(); - return path.substring(0, path.length() - 1) + "*"; - } else { - return new File(path).getCanonicalPath(); - } - } catch (IOException ioe) { - return cpath; - } + try { + String path = cpath; + if (cpath.endsWith("*")) { + // call getCanonicalPath with a path with wildcard character + // replaced to avoid calling it with paths that are + // intended to match all entries in a directory + path = path.substring(0, path.length() - 1) + "-"; + path = new File(path).getCanonicalPath(); + cpath = path.substring(0, path.length() - 1) + "*"; + } else { + cpath = new File(path).getCanonicalPath(); } - }); + } catch (IOException ignore) { + } int len = cpath.length(); char last = ((len > 0) ? cpath.charAt(len - 1) : 0); diff --git a/src/java.base/share/classes/java/io/RandomAccessFile.java b/src/java.base/share/classes/java/io/RandomAccessFile.java index 1487764ac4475..c09f87afcdc45 100644 --- a/src/java.base/share/classes/java/io/RandomAccessFile.java +++ b/src/java.base/share/classes/java/io/RandomAccessFile.java @@ -245,14 +245,6 @@ else if (mode.startsWith("rw")) { + "\" must be one of " + "\"r\", \"rw\", \"rws\"," + " or \"rwd\""); - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); - if (security != null) { - security.checkRead(name); - if (rw) { - security.checkWrite(name); - } - } if (name == null) { throw new NullPointerException(); } diff --git a/src/java.base/share/classes/java/io/SerializablePermission.java b/src/java.base/share/classes/java/io/SerializablePermission.java index 1e617e173a755..48be2eabf1f71 100644 --- a/src/java.base/share/classes/java/io/SerializablePermission.java +++ b/src/java.base/share/classes/java/io/SerializablePermission.java @@ -25,7 +25,7 @@ package java.io; -import java.security.*; +import java.security.BasicPermission; import java.util.Enumeration; import java.util.Hashtable; import java.util.StringTokenizer; @@ -44,7 +44,6 @@ * @see java.security.Permission * @see java.security.Permissions * @see java.security.PermissionCollection - * @see java.lang.SecurityManager * * @author Joe Fialli * @since 1.2 diff --git a/src/java.base/unix/classes/java/io/UnixFileSystem.java b/src/java.base/unix/classes/java/io/UnixFileSystem.java index 18afb729c019d..ea2ca28fe86aa 100644 --- a/src/java.base/unix/classes/java/io/UnixFileSystem.java +++ b/src/java.base/unix/classes/java/io/UnixFileSystem.java @@ -27,7 +27,6 @@ import java.util.Properties; import jdk.internal.util.StaticProperty; -import sun.security.action.GetPropertyAction; final class UnixFileSystem extends FileSystem { @@ -36,7 +35,7 @@ final class UnixFileSystem extends FileSystem { private final String userDir; UnixFileSystem() { - Properties props = GetPropertyAction.privilegedGetProperties(); + Properties props = System.getProperties(); slash = props.getProperty("file.separator").charAt(0); colon = props.getProperty("path.separator").charAt(0); userDir = StaticProperty.userDir(); @@ -150,11 +149,6 @@ public boolean isInvalid(File f) { @Override public String resolve(File f) { if (isAbsolute(f)) return f.getPath(); - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPropertyAccess("user.dir"); - } return resolve(userDir, f.getPath()); } @@ -259,16 +253,7 @@ public boolean setReadOnly(File f) { @Override public File[] listRoots() { - try { - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); - if (security != null) { - security.checkRead("/"); - } - return new File[] { new File("/") }; - } catch (SecurityException x) { - return new File[0]; - } + return new File[] { new File("/") }; } /* -- Disk usage -- */ diff --git a/src/java.base/windows/classes/java/io/WinNTFileSystem.java b/src/java.base/windows/classes/java/io/WinNTFileSystem.java index 10e02b4ba727a..af6531edd01e7 100644 --- a/src/java.base/windows/classes/java/io/WinNTFileSystem.java +++ b/src/java.base/windows/classes/java/io/WinNTFileSystem.java @@ -30,7 +30,6 @@ import java.util.BitSet; import java.util.Locale; import java.util.Properties; -import sun.security.action.GetPropertyAction; /** * Unicode-aware FileSystem for Windows NT/2000. @@ -53,7 +52,7 @@ final class WinNTFileSystem extends FileSystem { // only if the property is set, ignoring case, to the string "false". private static final boolean ENABLE_ADS; static { - String enableADS = GetPropertyAction.privilegedGetProperty("jdk.io.File.enableADS"); + String enableADS = System.getProperty("jdk.io.File.enableADS"); if (enableADS != null) { ENABLE_ADS = !enableADS.equalsIgnoreCase(Boolean.FALSE.toString()); } else { @@ -81,7 +80,7 @@ private static String stripLongOrUNCPrefix(String path) { } WinNTFileSystem() { - Properties props = GetPropertyAction.privilegedGetProperties(); + Properties props = System.getProperties(); slash = props.getProperty("file.separator").charAt(0); semicolon = props.getProperty("path.separator").charAt(0); altSlash = (this.slash == '\\') ? '/' : '\\'; @@ -394,15 +393,15 @@ public String resolve(File f) { if (pl == 3) return path; /* Absolute local */ if (pl == 0) - return getUserPath() + slashify(path); /* Completely relative */ + return userDir + slashify(path); /* Completely relative */ if (pl == 1) { /* Drive-relative */ - String up = getUserPath(); + String up = userDir; String ud = getDrive(up); if (ud != null) return ud + path; return up + path; /* User dir is a UNC path */ } if (pl == 2) { /* Directory-relative */ - String up = getUserPath(); + String up = userDir; String ud = getDrive(up); if ((ud != null) && path.startsWith(ud)) return up + slashify(path.substring(2)); @@ -413,14 +412,6 @@ public String resolve(File f) { drive other than the current drive, insist that the caller have read permission on the result */ String p = drive + (':' + dir + slashify(path.substring(2))); - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); - try { - if (security != null) security.checkRead(p); - } catch (SecurityException x) { - /* Don't disclose the drive's directory in the exception */ - throw new SecurityException("Cannot resolve path " + path); - } return p; } return drive + ":" + slashify(path.substring(2)); /* fake it */ @@ -428,17 +419,6 @@ public String resolve(File f) { throw new InternalError("Unresolvable path: " + path); } - private String getUserPath() { - /* For both compatibility and security, - we must look this up every time */ - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPropertyAccess("user.dir"); - } - return userDir; - } - private String getDrive(String path) { int pl = prefixLength(path); return (pl == 3) ? path.substring(0, 2) : null; @@ -595,22 +575,10 @@ public File[] listRoots() { .valueOf(new long[] {listRoots0()}) .stream() .mapToObj(i -> new File((char)('A' + i) + ":" + slash)) - .filter(f -> access(f.getPath())) .toArray(File[]::new); } private static native int listRoots0(); - private boolean access(String path) { - try { - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); - if (security != null) security.checkRead(path); - return true; - } catch (SecurityException x) { - return false; - } - } - /* -- Disk usage -- */ @Override From acdbf83325296511e6d27cc696911d81f99b8063 Mon Sep 17 00:00:00 2001 From: Calvin Cheung Date: Tue, 19 Nov 2024 23:37:34 +0000 Subject: [PATCH 27/74] 8341553: Remove UseCompactObjectHeaders extra CDS archives Reviewed-by: erikj, iklam, coleenp --- make/conf/jib-profiles.js | 1 + .../cds/TestDefaultArchiveLoading.java | 31 +++++++++++++++++-- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/make/conf/jib-profiles.js b/make/conf/jib-profiles.js index a28d85c146f16..25cf15c5f3b64 100644 --- a/make/conf/jib-profiles.js +++ b/make/conf/jib-profiles.js @@ -253,6 +253,7 @@ var getJibProfilesCommon = function (input, data) { configure_args: concat( "--with-exclude-translations=es,fr,it,ko,pt_BR,sv,ca,tr,cs,sk,ja_JP_A,ja_JP_HA,ja_JP_HI,ja_JP_I,zh_TW,zh_HK", "--disable-jvm-feature-shenandoahgc", + "--disable-cds-archive-coh", versionArgs(input, common)) }; diff --git a/test/hotspot/jtreg/runtime/cds/TestDefaultArchiveLoading.java b/test/hotspot/jtreg/runtime/cds/TestDefaultArchiveLoading.java index 590f22feed737..192f7ca42a881 100644 --- a/test/hotspot/jtreg/runtime/cds/TestDefaultArchiveLoading.java +++ b/test/hotspot/jtreg/runtime/cds/TestDefaultArchiveLoading.java @@ -66,12 +66,32 @@ * @run driver TestDefaultArchiveLoading coops_coh */ +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import jdk.test.lib.Platform; import jdk.test.lib.process.OutputAnalyzer; import jdk.test.lib.process.ProcessTools; + import jtreg.SkippedException; public class TestDefaultArchiveLoading { + + private static String archiveName(String archiveSuffix) { + return "classes" + archiveSuffix + ".jsa"; + } + + private static Path archivePath(String archiveSuffix) { + return Paths.get(System.getProperty("java.home"), "lib", + "server", archiveName(archiveSuffix)); + } + + private static boolean isCOHArchiveAvailable(char coops, char coh, + String archiveSuffix) throws Exception { + Path archive= archivePath(archiveSuffix); + return Files.exists(archive); + } + public static void main(String[] args) throws Exception { if (args.length != 1) { @@ -90,6 +110,10 @@ public static void main(String[] args) throws Exception { coops = '-'; coh = '+'; archiveSuffix = "_nocoops_coh"; + if (!isCOHArchiveAvailable(coops, coh, archiveSuffix)) { + throw new SkippedException("Skipping test due to " + + archivePath(archiveSuffix).toString() + " not available"); + } break; case "coops_nocoh": coops = '+'; @@ -99,6 +123,10 @@ public static void main(String[] args) throws Exception { case "coops_coh": coh = coops = '+'; archiveSuffix = "_coh"; + if (!isCOHArchiveAvailable(coops, coh, archiveSuffix)) { + throw new SkippedException("Skipping test due to " + + archivePath(archiveSuffix).toString() + " not available"); + } break; default: throw new RuntimeException("Invalid argument " + args[0]); } @@ -114,7 +142,6 @@ public static void main(String[] args) throws Exception { OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); - output.shouldContain("classes" + archiveSuffix + ".jsa"); - + output.shouldContain(archiveName(archiveSuffix)); } } From f525290000bf8583617047aaeb894bf90332d2e9 Mon Sep 17 00:00:00 2001 From: Joe Darcy Date: Wed, 20 Nov 2024 00:06:24 +0000 Subject: [PATCH 28/74] 8341935: javac states that -proc:full is the default but the default as of 23 is -proc:none Reviewed-by: jlahoda --- src/jdk.compiler/share/man/javac.md | 47 ++++++++++++++++++++--------- 1 file changed, 33 insertions(+), 14 deletions(-) diff --git a/src/jdk.compiler/share/man/javac.md b/src/jdk.compiler/share/man/javac.md index b41a395f386db..7761cde2b5802 100644 --- a/src/jdk.compiler/share/man/javac.md +++ b/src/jdk.compiler/share/man/javac.md @@ -1,5 +1,5 @@ --- -# Copyright (c) 1994, 2023, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 1994, 2024, 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 @@ -336,10 +336,18 @@ file system locations may be directories, JAR files or JMOD files. `-proc:`\[`none`, `only`, `full`\] : Controls whether annotation processing and compilation are done. - `-proc:none` means that compilation takes place without annotation - processing. `-proc:only` means that only annotation processing is done, - without any subsequent compilation. If this option is not used, or - `-proc:full` is specified, annotation processing and compilation are done. + + - `-proc:none` means that compilation takes place without annotation + processing + + - `-proc:only` means that only annotation processing is done, + without any subsequent compilation. + + - `-proc:full` means annotation processing and compilation are done. + + If this option is not used, annotation processing and compilation + are done if at least one other option is used to explicitly + configure annotation processing. `-processor` *class1*\[`,`*class2*`,`*class3*...\] : Names of the annotation processors to run. This bypasses the default @@ -1427,15 +1435,26 @@ The API for annotation processors is defined in the ### How Annotation Processing Works -Unless annotation processing is disabled with the [`-proc:none`](#option-proc) option, the -compiler searches for any annotation processors that are available. The search -path can be specified with the [`-processorpath`](#option-processor-path) option. If no path is -specified, then the user class path is used. Processors are located by means of -service provider-configuration files named -`META-INF/services/javax.annotation.processing.Processor` on the search path. -Such files should contain the names of any annotation processors to be used, -listed one per line. Alternatively, processors can be specified explicitly, -using the [`-processor`](#option-processor) option. +Annotation processing is requested by using an option to configure +annotation processing, such as [`-processor`](#option-processor), +[`--processor-path`](#option-processor-path), +[`--processor-module-path`](#option-processor-module-path) or by +explicitly enabling processing with the [`-proc:full`](#option-proc) +or [`-proc:only`](#option-proc) options. Annotation processing is +disabled using the [`-proc:none`](#option-proc) option. + +If annotation processing is requested, the compiler searches for any +annotation processors that are available. + +The search path can be specified with the +[`-processorpath`](#option-processor-path) option. If no path is +specified, then the user class path is used. Processors are located by +means of service provider-configuration files named +`META-INF/services/javax.annotation.processing.Processor` on the +search path. Such files should contain the names of any +annotationation processors to be used, listed one per +line. Alternatively, processors can be specified explicitly, using the +[`-processor`](#option-processor) option. After scanning the source files and classes on the command line to determine what annotations are present, the compiler queries the processors to determine From bc7eabd7e4c499fc1b1f37b958c7384078b69bce Mon Sep 17 00:00:00 2001 From: Guoxiong Li Date: Wed, 20 Nov 2024 01:09:05 +0000 Subject: [PATCH 29/74] 8344350: Add '.gdbinit' and '.lldbinit' to file '.gitignore' Reviewed-by: ihse, erikj --- .gitignore | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.gitignore b/.gitignore index d0736707b804a..b57addfccc9ab 100644 --- a/.gitignore +++ b/.gitignore @@ -20,3 +20,5 @@ NashornProfile.txt /.settings/ /compile_commands.json /.cache +/.gdbinit +/.lldbinit From 4ddd3dec2d0b232d48646ca89b16591b3026aa5c Mon Sep 17 00:00:00 2001 From: SendaoYan Date: Wed, 20 Nov 2024 01:36:56 +0000 Subject: [PATCH 30/74] 8344356: Aarch64: implement -XX:+VerifyActivationFrameSize Reviewed-by: aph --- src/hotspot/cpu/aarch64/interp_masm_aarch64.cpp | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/hotspot/cpu/aarch64/interp_masm_aarch64.cpp b/src/hotspot/cpu/aarch64/interp_masm_aarch64.cpp index b892489af706f..836caa86cb0af 100644 --- a/src/hotspot/cpu/aarch64/interp_masm_aarch64.cpp +++ b/src/hotspot/cpu/aarch64/interp_masm_aarch64.cpp @@ -393,7 +393,13 @@ void InterpreterMacroAssembler::dispatch_base(TosState state, bool verifyoop, bool generate_poll) { if (VerifyActivationFrameSize) { - Unimplemented(); + Label L; + sub(rscratch2, rfp, esp); + int min_frame_size = (frame::link_offset - frame::interpreter_frame_initial_sp_offset) * wordSize; + subs(rscratch2, rscratch2, min_frame_size); + br(Assembler::GE, L); + stop("broken stack frame"); + bind(L); } if (verifyoop) { interp_verify_oop(r0, state); From 8a1f9f0a324e30b5da53d58434ac1b39569fc523 Mon Sep 17 00:00:00 2001 From: Archie Cobbs Date: Wed, 20 Nov 2024 01:57:03 +0000 Subject: [PATCH 31/74] 8343476: Remove unnecessary @SuppressWarnings annotations (client) Reviewed-by: prr --- src/demo/share/jfc/SampleTree/SampleTree.java | 3 +-- src/demo/share/jfc/TableExample/TableExample3.java | 3 +-- src/demo/share/jfc/TableExample/TableExample4.java | 4 +--- .../classes/com/apple/laf/AquaComboBoxButton.java | 3 +-- .../classes/com/apple/laf/AquaComboBoxPopup.java | 3 +-- .../classes/com/apple/laf/AquaComboBoxUI.java | 14 +------------- .../classes/com/apple/laf/AquaFileChooserUI.java | 5 +---- .../macosx/classes/com/apple/laf/AquaFileView.java | 3 +-- .../classes/com/apple/laf/AquaTabbedPaneUI.java | 3 +-- .../classes/com/apple/laf/AquaTextFieldSearch.java | 4 +--- .../macosx/classes/sun/lwawt/LWListPeer.java | 3 +-- .../macosx/classes/sun/lwawt/LWWindowPeer.java | 3 +-- .../classes/sun/lwawt/macosx/CPlatformWindow.java | 1 - .../plugins/tiff/TIFFOldJPEGDecompressor.java | 3 +-- .../java/swing/plaf/motif/MotifFileChooserUI.java | 10 +--------- .../swing/plaf/motif/MotifInternalFrameUI.java | 4 +--- .../java/swing/plaf/motif/MotifOptionPaneUI.java | 3 +-- .../com/sun/media/sound/JavaSoundAudioClip.java | 4 ++-- .../classes/java/awt/AWTEventMulticaster.java | 4 +--- .../share/classes/java/awt/Component.java | 4 +--- .../share/classes/java/awt/Container.java | 7 +------ .../java/awt/DefaultKeyboardFocusManager.java | 3 +-- .../share/classes/java/awt/EventQueue.java | 4 ++-- .../share/classes/java/awt/MediaTracker.java | 3 +-- .../share/classes/java/awt/SequencedEvent.java | 1 - .../share/classes/java/awt/SplashScreen.java | 2 +- .../classes/java/awt/WaitDispatchSupport.java | 1 - .../share/classes/java/awt/Window.java | 2 -- .../share/classes/java/awt/dnd/DragSource.java | 1 - .../share/classes/java/awt/event/FocusEvent.java | 3 +-- .../share/classes/java/beans/Beans.java | 2 +- .../BeanContextChildComponentProxy.java | 1 - .../beancontext/BeanContextContainerProxy.java | 1 - .../BeanContextServiceProviderBeanInfo.java | 1 - .../classes/javax/swing/DefaultFocusManager.java | 3 +-- .../share/classes/javax/swing/JColorChooser.java | 3 +-- .../share/classes/javax/swing/JComponent.java | 2 +- .../share/classes/javax/swing/JLayer.java | 3 +-- .../share/classes/javax/swing/KeyStroke.java | 3 +-- .../share/classes/javax/swing/Spring.java | 3 +-- .../share/classes/javax/swing/SpringLayout.java | 3 +-- .../share/classes/javax/swing/Timer.java | 1 - .../share/classes/javax/swing/UIManager.java | 1 - .../colorchooser/ColorChooserComponentFactory.java | 3 +-- .../javax/swing/filechooser/FileSystemView.java | 1 - .../share/classes/javax/swing/plaf/LayerUI.java | 7 +------ .../javax/swing/plaf/basic/BasicCheckBoxUI.java | 3 +-- .../swing/plaf/basic/BasicComboBoxEditor.java | 3 +-- .../javax/swing/plaf/basic/BasicComboBoxUI.java | 6 +----- .../javax/swing/plaf/basic/BasicFileChooserUI.java | 3 +-- .../javax/swing/plaf/basic/BasicListUI.java | 8 +------- .../javax/swing/plaf/basic/BasicOptionPaneUI.java | 1 - .../swing/plaf/basic/BasicSplitPaneDivider.java | 1 - .../javax/swing/plaf/basic/BasicSplitPaneUI.java | 3 +-- .../javax/swing/plaf/basic/BasicTextAreaUI.java | 3 +-- .../javax/swing/plaf/basic/BasicTextFieldUI.java | 3 +-- .../javax/swing/plaf/basic/BasicTextPaneUI.java | 3 +-- .../javax/swing/plaf/basic/BasicToolBarUI.java | 5 +---- .../classes/javax/swing/plaf/basic/ComboPopup.java | 3 +-- .../javax/swing/plaf/metal/DefaultMetalTheme.java | 3 +-- .../javax/swing/plaf/metal/MetalButtonUI.java | 3 +-- .../javax/swing/plaf/metal/MetalCheckBoxUI.java | 3 +-- .../swing/plaf/metal/MetalComboBoxEditor.java | 3 +-- .../javax/swing/plaf/metal/MetalFileChooserUI.java | 4 +--- .../javax/swing/plaf/metal/MetalProgressBarUI.java | 3 +-- .../javax/swing/plaf/metal/MetalRadioButtonUI.java | 3 +-- .../javax/swing/plaf/metal/MetalRootPaneUI.java | 3 +-- .../javax/swing/plaf/metal/MetalScrollPaneUI.java | 3 +-- .../javax/swing/plaf/metal/MetalSeparatorUI.java | 3 +-- .../javax/swing/plaf/metal/MetalSliderUI.java | 3 +-- .../javax/swing/plaf/metal/MetalSplitPaneUI.java | 3 +-- .../javax/swing/plaf/metal/MetalTabbedPaneUI.java | 3 +-- .../javax/swing/plaf/metal/MetalTextFieldUI.java | 3 +-- .../swing/plaf/metal/MetalToggleButtonUI.java | 3 +-- .../javax/swing/plaf/metal/MetalToolTipUI.java | 3 +-- .../classes/javax/swing/plaf/metal/MetalUtils.java | 4 +--- .../javax/swing/plaf/multi/MultiLookAndFeel.java | 3 +-- .../javax/swing/plaf/synth/SynthDesktopIconUI.java | 3 +-- .../javax/swing/plaf/synth/SynthScrollBarUI.java | 4 +--- .../javax/swing/plaf/synth/SynthSplitPaneUI.java | 3 +-- .../javax/swing/plaf/synth/SynthTextAreaUI.java | 3 +-- .../javax/swing/plaf/synth/SynthTextFieldUI.java | 3 +-- .../javax/swing/plaf/synth/SynthTextPaneUI.java | 3 +-- .../javax/swing/plaf/synth/SynthTreeUI.java | 3 +-- .../javax/swing/text/DefaultStyledDocument.java | 3 +-- .../classes/javax/swing/text/JTextComponent.java | 2 -- .../javax/swing/text/SimpleAttributeSet.java | 3 +-- .../classes/javax/swing/text/StyledEditorKit.java | 3 +-- .../classes/javax/swing/text/WrappedPlainView.java | 4 +--- .../classes/javax/swing/text/html/FormView.java | 6 +----- .../javax/swing/tree/AbstractLayoutCache.java | 3 +-- .../javax/swing/tree/DefaultTreeCellEditor.java | 3 +-- .../share/classes/sun/awt/AWTAutoShutdown.java | 3 +-- .../share/classes/sun/awt/AppContext.java | 3 +-- .../share/classes/sun/awt/CausedFocusEvent.java | 3 +-- .../sun/awt/KeyboardFocusManagerPeerImpl.java | 3 +-- .../share/classes/sun/awt/LightweightFrame.java | 3 +-- .../share/classes/sun/awt/SunToolkit.java | 4 +--- .../share/classes/sun/java2d/Disposer.java | 3 +-- .../sun/java2d/marlin/DMarlinRenderingEngine.java | 3 +-- .../share/classes/sun/print/ServiceDialog.java | 3 +-- .../share/classes/sun/swing/FilePane.java | 5 +---- .../share/classes/sun/swing/JLightweightFrame.java | 4 ++-- .../classes/sun/swing/LightweightContent.java | 4 +--- .../share/classes/sun/swing/PrintingStatus.java | 3 +-- .../swing/plaf/synth/SynthFileChooserUIImpl.java | 3 +-- .../sun/swing/text/TextComponentPrintable.java | 1 - 107 files changed, 95 insertions(+), 252 deletions(-) diff --git a/src/demo/share/jfc/SampleTree/SampleTree.java b/src/demo/share/jfc/SampleTree/SampleTree.java index 90588e6ec3a73..8ff338287918b 100644 --- a/src/demo/share/jfc/SampleTree/SampleTree.java +++ b/src/demo/share/jfc/SampleTree/SampleTree.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2024, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -142,7 +142,6 @@ public SampleTree() { /** Constructs a JPanel containing check boxes for the different * options that tree supports. */ - @SuppressWarnings("serial") private JPanel constructOptionsPanel() { JCheckBox aCheckbox; JPanel retPanel = new JPanel(false); diff --git a/src/demo/share/jfc/TableExample/TableExample3.java b/src/demo/share/jfc/TableExample/TableExample3.java index 9f3c11f44484c..a5344f8802a65 100644 --- a/src/demo/share/jfc/TableExample/TableExample3.java +++ b/src/demo/share/jfc/TableExample/TableExample3.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2024, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -97,7 +97,6 @@ public void windowClosing(WindowEvent e) { }; // Create a model of the data. - @SuppressWarnings("serial") TableModel dataModel = new AbstractTableModel() { // These methods always need to be implemented. diff --git a/src/demo/share/jfc/TableExample/TableExample4.java b/src/demo/share/jfc/TableExample/TableExample4.java index 4d81a3d8cf38e..b429c9ec9de02 100644 --- a/src/demo/share/jfc/TableExample/TableExample4.java +++ b/src/demo/share/jfc/TableExample/TableExample4.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2024, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -99,7 +99,6 @@ public void windowClosing(WindowEvent e) { }; // Create a model of the data. - @SuppressWarnings("serial") TableModel dataModel = new AbstractTableModel() { // These methods always need to be implemented. @@ -180,7 +179,6 @@ public void setValueAt(Object aValue, int row, int column) { // Show the values in the "Favorite Number" column in different colors. TableColumn numbersColumn = tableView.getColumn("Favorite Number"); - @SuppressWarnings("serial") DefaultTableCellRenderer numberColumnRenderer = new DefaultTableCellRenderer() { diff --git a/src/java.desktop/macosx/classes/com/apple/laf/AquaComboBoxButton.java b/src/java.desktop/macosx/classes/com/apple/laf/AquaComboBoxButton.java index b79cc98be9d55..a9eab801b0d54 100644 --- a/src/java.desktop/macosx/classes/com/apple/laf/AquaComboBoxButton.java +++ b/src/java.desktop/macosx/classes/com/apple/laf/AquaComboBoxButton.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2024, 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 @@ -63,7 +63,6 @@ class AquaComboBoxButton extends JButton { boolean isPopDown; boolean isSquare; - @SuppressWarnings("serial") // anonymous class protected AquaComboBoxButton(final AquaComboBoxUI ui, final JComboBox comboBox, final CellRendererPane rendererPane, diff --git a/src/java.desktop/macosx/classes/com/apple/laf/AquaComboBoxPopup.java b/src/java.desktop/macosx/classes/com/apple/laf/AquaComboBoxPopup.java index 981a00d55883f..dc29d0b5ae801 100644 --- a/src/java.desktop/macosx/classes/com/apple/laf/AquaComboBoxPopup.java +++ b/src/java.desktop/macosx/classes/com/apple/laf/AquaComboBoxPopup.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2024, 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 @@ -161,7 +161,6 @@ public void show() { } @Override - @SuppressWarnings("serial") // anonymous class protected JList createList() { return new JList(comboBox.getModel()) { @Override diff --git a/src/java.desktop/macosx/classes/com/apple/laf/AquaComboBoxUI.java b/src/java.desktop/macosx/classes/com/apple/laf/AquaComboBoxUI.java index b9b60994085b4..130c30aa9e153 100644 --- a/src/java.desktop/macosx/classes/com/apple/laf/AquaComboBoxUI.java +++ b/src/java.desktop/macosx/classes/com/apple/laf/AquaComboBoxUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2024, 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 @@ -230,7 +230,6 @@ private void editorTextChanged() { @SuppressWarnings("serial") // Superclass is not serializable across versions class AquaCustomComboTextField extends JTextField { - @SuppressWarnings("serial") // anonymous class public AquaCustomComboTextField() { final InputMap inputMap = getInputMap(); inputMap.put(KeyStroke.getKeyStroke("DOWN"), highlightNextAction); @@ -350,7 +349,6 @@ public void actionPerformed(final ActionEvent e) { /** * Highlight _but do not select_ the next item in the list. */ - @SuppressWarnings("serial") // anonymous class private Action highlightNextAction = new ComboBoxAction() { @Override public void performComboBoxAction(AquaComboBoxUI ui) { @@ -367,7 +365,6 @@ public void performComboBoxAction(AquaComboBoxUI ui) { /** * Highlight _but do not select_ the previous item in the list. */ - @SuppressWarnings("serial") // anonymous class private Action highlightPreviousAction = new ComboBoxAction() { @Override void performComboBoxAction(final AquaComboBoxUI ui) { @@ -380,7 +377,6 @@ void performComboBoxAction(final AquaComboBoxUI ui) { } }; - @SuppressWarnings("serial") // anonymous class private Action highlightFirstAction = new ComboBoxAction() { @Override void performComboBoxAction(final AquaComboBoxUI ui) { @@ -389,7 +385,6 @@ void performComboBoxAction(final AquaComboBoxUI ui) { } }; - @SuppressWarnings("serial") // anonymous class private Action highlightLastAction = new ComboBoxAction() { @Override void performComboBoxAction(final AquaComboBoxUI ui) { @@ -399,7 +394,6 @@ void performComboBoxAction(final AquaComboBoxUI ui) { } }; - @SuppressWarnings("serial") // anonymous class private Action highlightPageUpAction = new ComboBoxAction() { @Override void performComboBoxAction(final AquaComboBoxUI ui) { @@ -420,7 +414,6 @@ void performComboBoxAction(final AquaComboBoxUI ui) { } }; - @SuppressWarnings("serial") // anonymous class private Action highlightPageDownAction = new ComboBoxAction() { @Override void performComboBoxAction(final AquaComboBoxUI ui) { @@ -560,7 +553,6 @@ protected static void triggerSelectionEvent(final JComboBox comboBox, final A // This is somewhat messy. The difference here from BasicComboBoxUI.EnterAction is that // arrow up or down does not automatically select the - @SuppressWarnings("serial") // anonymous class private final Action triggerSelectionAction = new AbstractAction() { public void actionPerformed(final ActionEvent e) { triggerSelectionEvent((JComboBox)e.getSource(), e); @@ -572,7 +564,6 @@ public boolean isEnabled() { } }; - @SuppressWarnings("serial") // anonymous class private static final Action toggleSelectionAction = new AbstractAction() { public void actionPerformed(final ActionEvent e) { final JComboBox comboBox = (JComboBox) e.getSource(); @@ -591,7 +582,6 @@ public void actionPerformed(final ActionEvent e) { } }; - @SuppressWarnings("serial") // anonymous class private final Action hideAction = new AbstractAction() { @Override public void actionPerformed(final ActionEvent e) { @@ -606,7 +596,6 @@ public boolean isEnabled() { } }; - @SuppressWarnings("serial") // anonymous class private final Action openPopupOrHighlightLast = new ComboBoxAction() { @Override void performComboBoxAction(final AquaComboBoxUI ui) { @@ -617,7 +606,6 @@ void performComboBoxAction(final AquaComboBoxUI ui) { } }; - @SuppressWarnings("serial") // anonymous class private final Action openPopupOrHighlightFirst = new ComboBoxAction() { @Override void performComboBoxAction(final AquaComboBoxUI ui) { diff --git a/src/java.desktop/macosx/classes/com/apple/laf/AquaFileChooserUI.java b/src/java.desktop/macosx/classes/com/apple/laf/AquaFileChooserUI.java index e4b112cc2978f..bdb440bf4d2e6 100644 --- a/src/java.desktop/macosx/classes/com/apple/laf/AquaFileChooserUI.java +++ b/src/java.desktop/macosx/classes/com/apple/laf/AquaFileChooserUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2024, 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 @@ -1240,7 +1240,6 @@ public Dimension getMaximumSize(final JComponent c) { return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE); } - @SuppressWarnings("serial") // anonymous class protected ListCellRenderer createDirectoryComboBoxRenderer(final JFileChooser fc) { return new AquaComboBoxRendererInternal(directoryComboBox) { public Component getListCellRendererComponent(final JList list, @@ -1356,7 +1355,6 @@ public File getElementAt(final int index) { // // Renderer for Types ComboBox // - @SuppressWarnings("serial") // anonymous class protected ListCellRenderer createFilterComboBoxRenderer() { return new AquaComboBoxRendererInternal(filterComboBox) { public Component getListCellRendererComponent(final JList list, @@ -1611,7 +1609,6 @@ public void installComponents(final JFileChooser fc) { tPanel.add(labelArea); // separator line - @SuppressWarnings("serial") // anonymous class final JSeparator sep = new JSeparator(){ public Dimension getPreferredSize() { return new Dimension(((JComponent)getParent()).getWidth(), 3); diff --git a/src/java.desktop/macosx/classes/com/apple/laf/AquaFileView.java b/src/java.desktop/macosx/classes/com/apple/laf/AquaFileView.java index 32b43dba29543..653cf49cb550e 100644 --- a/src/java.desktop/macosx/classes/com/apple/laf/AquaFileView.java +++ b/src/java.desktop/macosx/classes/com/apple/laf/AquaFileView.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2024, 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 @@ -39,7 +39,6 @@ import static java.nio.charset.StandardCharsets.UTF_8; -@SuppressWarnings("serial") // JDK implementation class class AquaFileView extends FileView { private static final boolean DEBUG = false; diff --git a/src/java.desktop/macosx/classes/com/apple/laf/AquaTabbedPaneUI.java b/src/java.desktop/macosx/classes/com/apple/laf/AquaTabbedPaneUI.java index e00722bc2936e..1a10e30a6c60a 100644 --- a/src/java.desktop/macosx/classes/com/apple/laf/AquaTabbedPaneUI.java +++ b/src/java.desktop/macosx/classes/com/apple/laf/AquaTabbedPaneUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2024, 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 @@ -1020,7 +1020,6 @@ JMenuItem createMenuItem(final int i) { if (component == null) { menuItem = new JMenuItem(tabPane.getTitleAt(i), tabPane.getIconAt(i)); } else { - @SuppressWarnings("serial") // anonymous class JMenuItem tmp = new JMenuItem() { public void paintComponent(final Graphics g) { super.paintComponent(g); diff --git a/src/java.desktop/macosx/classes/com/apple/laf/AquaTextFieldSearch.java b/src/java.desktop/macosx/classes/com/apple/laf/AquaTextFieldSearch.java index 99349b6c6b3d7..a6be82d9ac34b 100644 --- a/src/java.desktop/macosx/classes/com/apple/laf/AquaTextFieldSearch.java +++ b/src/java.desktop/macosx/classes/com/apple/laf/AquaTextFieldSearch.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2024, 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 @@ -249,7 +249,6 @@ static void updatePromptLabelOnEDT(final JLabel label, final JTextComponent text label.setText(promptText); } - @SuppressWarnings("serial") // anonymous class inside protected static JButton getCancelButton(final JTextComponent c) { final JButton b = createButton(c, getCancelIcon()); b.setName("cancel"); @@ -326,7 +325,6 @@ public Insets getBorderInsets(final Component c) { } protected boolean doingLayout; - @SuppressWarnings("serial") // anonymous class inside protected LayoutManager getCustomLayout() { // unfortunately, the default behavior of BorderLayout, which accommodates for margins // is not what we want, so we "turn off margins" for layout for layout out our buttons diff --git a/src/java.desktop/macosx/classes/sun/lwawt/LWListPeer.java b/src/java.desktop/macosx/classes/sun/lwawt/LWListPeer.java index a9081ae3c363b..905a66b321273 100644 --- a/src/java.desktop/macosx/classes/sun/lwawt/LWListPeer.java +++ b/src/java.desktop/macosx/classes/sun/lwawt/LWListPeer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2024, 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 @@ -254,7 +254,6 @@ public void setSkipStateChangedEvent(boolean skipStateChangedEvent) { } @Override - @SuppressWarnings("unchecked") public void valueChanged(final ListSelectionEvent e) { if (!e.getValueIsAdjusting() && !isSkipStateChangedEvent()) { final JList source = (JList) e.getSource(); diff --git a/src/java.desktop/macosx/classes/sun/lwawt/LWWindowPeer.java b/src/java.desktop/macosx/classes/sun/lwawt/LWWindowPeer.java index 4ec8d87fee3f7..13b6372a3c8e7 100644 --- a/src/java.desktop/macosx/classes/sun/lwawt/LWWindowPeer.java +++ b/src/java.desktop/macosx/classes/sun/lwawt/LWWindowPeer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2024, 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 @@ -1353,7 +1353,6 @@ public void emulateActivation(boolean activate) { changeFocusedWindow(activate, null); } - @SuppressWarnings("deprecation") private boolean isOneOfOwnersOf(LWWindowPeer peer) { Window owner = (peer != null ? peer.getTarget().getOwner() : null); while (owner != null) { diff --git a/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java b/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java index 3af1b4bcddaf1..0596ad2379eb3 100644 --- a/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java +++ b/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java @@ -268,7 +268,6 @@ public void applyProperty(final CPlatformWindow c, final Object value) { } } }) { - @SuppressWarnings("deprecation") public CPlatformWindow convertJComponentToTarget(final JRootPane p) { Component root = SwingUtilities.getRoot(p); final ComponentAccessor acc = AWTAccessor.getComponentAccessor(); diff --git a/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFOldJPEGDecompressor.java b/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFOldJPEGDecompressor.java index 5ad3db345e2e5..bc787f9127cc7 100644 --- a/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFOldJPEGDecompressor.java +++ b/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFOldJPEGDecompressor.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2024, 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 @@ -610,7 +610,6 @@ public void decodeRaw(byte[] b, JPEGReader.read(0, JPEGParam); } - @SuppressWarnings("removal") protected void finalize() throws Throwable { super.finalize(); JPEGReader.dispose(); diff --git a/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/MotifFileChooserUI.java b/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/MotifFileChooserUI.java index a6d2f5bbb0e5d..0f1ecd0dc1ef5 100644 --- a/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/MotifFileChooserUI.java +++ b/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/MotifFileChooserUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2024, 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 @@ -281,7 +281,6 @@ public void installComponents(JFileChooser fc) { fc.setLayout(new BorderLayout(10, 10)); fc.setAlignmentX(JComponent.CENTER_ALIGNMENT); - @SuppressWarnings("serial") // anonymous class JPanel interior = new JPanel() { public Insets getInsets() { return insets; @@ -305,7 +304,6 @@ public Insets getInsets() { curDirName = currentDirectory.getPath(); } - @SuppressWarnings("serial") // anonymous class JTextField tmp1 = new JTextField(curDirName, 35) { public Dimension getMaximumSize() { Dimension d = super.getMaximumSize(); @@ -341,7 +339,6 @@ public Dimension getMaximumSize() { align(l); leftPanel.add(l); - @SuppressWarnings("serial") // anonymous class JComboBox tmp2 = new JComboBox() { public Dimension getMaximumSize() { Dimension d = super.getMaximumSize(); @@ -419,7 +416,6 @@ public Dimension getMaximumSize() { align(fileNameLabel); interior.add(fileNameLabel); - @SuppressWarnings("serial") // anonymous class JTextField tmp3 = new JTextField(35) { public Dimension getMaximumSize() { Dimension d = super.getMaximumSize(); @@ -444,7 +440,6 @@ public Dimension getMaximumSize() { buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS)); buttonPanel.add(Box.createGlue()); - @SuppressWarnings("serial") // anonymous class JButton tmp4 = new JButton(getApproveButtonText(fc)) { public Dimension getMaximumSize() { return new Dimension(MAX_SIZE.width, this.getPreferredSize().height); @@ -460,7 +455,6 @@ public Dimension getMaximumSize() { buttonPanel.add(approveButton); buttonPanel.add(Box.createGlue()); - @SuppressWarnings("serial") // anonymous class JButton updateButton = new JButton(updateButtonText) { public Dimension getMaximumSize() { return new Dimension(MAX_SIZE.width, this.getPreferredSize().height); @@ -475,7 +469,6 @@ public Dimension getMaximumSize() { buttonPanel.add(updateButton); buttonPanel.add(Box.createGlue()); - @SuppressWarnings("serial") // anonymous class JButton cancelButton = new JButton(cancelButtonText) { public Dimension getMaximumSize() { return new Dimension(MAX_SIZE.width, this.getPreferredSize().height); @@ -490,7 +483,6 @@ public Dimension getMaximumSize() { buttonPanel.add(cancelButton); buttonPanel.add(Box.createGlue()); - @SuppressWarnings("serial") // anonymous class JButton helpButton = new JButton(helpButtonText) { public Dimension getMaximumSize() { return new Dimension(MAX_SIZE.width, this.getPreferredSize().height); diff --git a/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/MotifInternalFrameUI.java b/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/MotifInternalFrameUI.java index cba71847fa43c..1179df181ab16 100644 --- a/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/MotifInternalFrameUI.java +++ b/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/MotifInternalFrameUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2024, 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 @@ -132,7 +132,6 @@ protected void uninstallKeyboardActions(){ } } - @SuppressWarnings("serial") // anonymous class protected void setupMenuOpenKey(){ super.setupMenuOpenKey(); ActionMap map = SwingUtilities.getUIActionMap(frame); @@ -152,7 +151,6 @@ public boolean isEnabled(){ } } - @SuppressWarnings("serial") // anonymous class protected void setupMenuCloseKey(){ ActionMap map = SwingUtilities.getUIActionMap(frame); if (map != null) { diff --git a/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/MotifOptionPaneUI.java b/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/MotifOptionPaneUI.java index a9c40aa71af22..e68d7e2d8bf3f 100644 --- a/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/MotifOptionPaneUI.java +++ b/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/MotifOptionPaneUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2024, 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 @@ -72,7 +72,6 @@ public Dimension getMinimumOptionPaneSize() { return null; } - @SuppressWarnings("serial") // anonymous class protected Container createSeparator() { return new JPanel() { diff --git a/src/java.desktop/share/classes/com/sun/media/sound/JavaSoundAudioClip.java b/src/java.desktop/share/classes/com/sun/media/sound/JavaSoundAudioClip.java index affec1aace1cf..00862ea9022ad 100644 --- a/src/java.desktop/share/classes/com/sun/media/sound/JavaSoundAudioClip.java +++ b/src/java.desktop/share/classes/com/sun/media/sound/JavaSoundAudioClip.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2024, 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 @@ -57,7 +57,7 @@ * @author Arthur van Hoff, Kara Kytle, Jan Borgersen * @author Florian Bomers */ -@SuppressWarnings({"deprecation", "removal"}) +@SuppressWarnings("removal") public final class JavaSoundAudioClip implements AudioClip, MetaEventListener, LineListener { private long lastPlayCall = 0; diff --git a/src/java.desktop/share/classes/java/awt/AWTEventMulticaster.java b/src/java.desktop/share/classes/java/awt/AWTEventMulticaster.java index 56084ec8f9022..592482823dbe3 100644 --- a/src/java.desktop/share/classes/java/awt/AWTEventMulticaster.java +++ b/src/java.desktop/share/classes/java/awt/AWTEventMulticaster.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2024, 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 @@ -625,7 +625,6 @@ public static WindowListener add(WindowListener a, WindowListener b) { * @return the resulting listener * @since 1.4 */ - @SuppressWarnings("overloads") public static WindowStateListener add(WindowStateListener a, WindowStateListener b) { return (WindowStateListener)addInternal(a, b); @@ -828,7 +827,6 @@ public static WindowListener remove(WindowListener l, WindowListener oldl) { * @return the resulting listener * @since 1.4 */ - @SuppressWarnings("overloads") public static WindowStateListener remove(WindowStateListener l, WindowStateListener oldl) { return (WindowStateListener) removeInternal(l, oldl); diff --git a/src/java.desktop/share/classes/java/awt/Component.java b/src/java.desktop/share/classes/java/awt/Component.java index a1f8461c802c5..71618eea95b88 100644 --- a/src/java.desktop/share/classes/java/awt/Component.java +++ b/src/java.desktop/share/classes/java/awt/Component.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2024, 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 @@ -7415,7 +7415,6 @@ final void setFocusTraversalKeys_NoIDCheck(int id, Set k } final Set getFocusTraversalKeys_NoIDCheck(int id) { // Okay to return Set directly because it is an unmodifiable view - @SuppressWarnings("unchecked") Set keystrokes = (focusTraversalKeys != null) ? focusTraversalKeys[id] : null; @@ -8362,7 +8361,6 @@ public void add(PopupMenu popup) { * @see #add(PopupMenu) * @since 1.1 */ - @SuppressWarnings("unchecked") public void remove(MenuComponent popup) { synchronized (getTreeLock()) { if (popups == null) { diff --git a/src/java.desktop/share/classes/java/awt/Container.java b/src/java.desktop/share/classes/java/awt/Container.java index 2eb2c923de0e1..63bd7467d91f2 100644 --- a/src/java.desktop/share/classes/java/awt/Container.java +++ b/src/java.desktop/share/classes/java/awt/Container.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2024, 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 @@ -814,7 +814,6 @@ public void setComponentZOrder(Component comp, int index) { * to new heavyweight parent. * @since 1.5 */ - @SuppressWarnings("deprecation") private void reparentTraverse(ContainerPeer parentPeer, Container child) { checkTreeLock(); @@ -838,7 +837,6 @@ private void reparentTraverse(ContainerPeer parentPeer, Container child) { * Container must be heavyweight. * @since 1.5 */ - @SuppressWarnings("deprecation") private void reparentChild(Component comp) { checkTreeLock(); if (comp == null) { @@ -4203,7 +4201,6 @@ final void recursiveApplyCurrentShape(int fromZorder, int toZorder) { } } - @SuppressWarnings("deprecation") private void recursiveShowHeavyweightChildren() { if (!hasHeavyweightDescendants() || !isVisible()) { return; @@ -4225,7 +4222,6 @@ private void recursiveShowHeavyweightChildren() { } } - @SuppressWarnings("deprecation") private void recursiveHideHeavyweightChildren() { if (!hasHeavyweightDescendants()) { return; @@ -4247,7 +4243,6 @@ private void recursiveHideHeavyweightChildren() { } } - @SuppressWarnings("deprecation") private void recursiveRelocateHeavyweightChildren(Point origin) { for (int index = 0; index < getComponentCount(); index++) { Component comp = getComponent(index); diff --git a/src/java.desktop/share/classes/java/awt/DefaultKeyboardFocusManager.java b/src/java.desktop/share/classes/java/awt/DefaultKeyboardFocusManager.java index 3c57ec3a8d905..8ee336548d277 100644 --- a/src/java.desktop/share/classes/java/awt/DefaultKeyboardFocusManager.java +++ b/src/java.desktop/share/classes/java/awt/DefaultKeyboardFocusManager.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2024, 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 @@ -1087,7 +1087,6 @@ void clearMarkers() { } } - @SuppressWarnings("deprecation") private boolean preDispatchKeyEvent(KeyEvent ke) { if (((AWTEvent) ke).isPosted) { Component focusOwner = getFocusOwner(); diff --git a/src/java.desktop/share/classes/java/awt/EventQueue.java b/src/java.desktop/share/classes/java/awt/EventQueue.java index 57a9a6cf567e1..f79ff285a79d3 100644 --- a/src/java.desktop/share/classes/java/awt/EventQueue.java +++ b/src/java.desktop/share/classes/java/awt/EventQueue.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2024, 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 @@ -1058,7 +1058,7 @@ final boolean isDispatchThreadImpl() { } } - @SuppressWarnings({"deprecation", "removal"}) + @SuppressWarnings("removal") final void initDispatchThread() { pushPopLock.lock(); try { diff --git a/src/java.desktop/share/classes/java/awt/MediaTracker.java b/src/java.desktop/share/classes/java/awt/MediaTracker.java index 2435dd0ba3393..408d68ffe142c 100644 --- a/src/java.desktop/share/classes/java/awt/MediaTracker.java +++ b/src/java.desktop/share/classes/java/awt/MediaTracker.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2024, 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 @@ -927,7 +927,6 @@ void setStatus(int flag) { * The entry of the list of {@code Images} that is being tracked by the * {@code MediaTracker}. */ -@SuppressWarnings("serial") // MediaEntry does not have a no-arg ctor class ImageMediaEntry extends MediaEntry implements ImageObserver, java.io.Serializable { @SuppressWarnings("serial") // Not statically typed as Serializable diff --git a/src/java.desktop/share/classes/java/awt/SequencedEvent.java b/src/java.desktop/share/classes/java/awt/SequencedEvent.java index a671814a57b71..e04757e195fda 100644 --- a/src/java.desktop/share/classes/java/awt/SequencedEvent.java +++ b/src/java.desktop/share/classes/java/awt/SequencedEvent.java @@ -43,7 +43,6 @@ * * @author David Mendenhall */ -@SuppressWarnings("removal") class SequencedEvent extends AWTEvent implements ActiveEvent { /** diff --git a/src/java.desktop/share/classes/java/awt/SplashScreen.java b/src/java.desktop/share/classes/java/awt/SplashScreen.java index 7f522026b8a5d..737c1a5c080ef 100644 --- a/src/java.desktop/share/classes/java/awt/SplashScreen.java +++ b/src/java.desktop/share/classes/java/awt/SplashScreen.java @@ -121,7 +121,7 @@ public final class SplashScreen { * @return the {@link SplashScreen} instance, or {@code null} if there is * none or it has already been closed */ - @SuppressWarnings({"removal", "restricted"}) + @SuppressWarnings("restricted") public static SplashScreen getSplashScreen() { synchronized (SplashScreen.class) { if (GraphicsEnvironment.isHeadless()) { diff --git a/src/java.desktop/share/classes/java/awt/WaitDispatchSupport.java b/src/java.desktop/share/classes/java/awt/WaitDispatchSupport.java index 2968c9ad3ef5c..50a66e997f945 100644 --- a/src/java.desktop/share/classes/java/awt/WaitDispatchSupport.java +++ b/src/java.desktop/share/classes/java/awt/WaitDispatchSupport.java @@ -161,7 +161,6 @@ public WaitDispatchSupport(EventDispatchThread dispatchThread, /** * {@inheritDoc} */ - @SuppressWarnings("removal") @Override public boolean enter() { if (log.isLoggable(PlatformLogger.Level.FINE)) { diff --git a/src/java.desktop/share/classes/java/awt/Window.java b/src/java.desktop/share/classes/java/awt/Window.java index 1a5395431ab3e..9b8557394433b 100644 --- a/src/java.desktop/share/classes/java/awt/Window.java +++ b/src/java.desktop/share/classes/java/awt/Window.java @@ -798,7 +798,6 @@ public void removeNotify() { * @see Component#isDisplayable * @see #setMinimumSize */ - @SuppressWarnings("deprecation") public void pack() { Container parent = this.parent; if (parent != null && parent.peer == null) { @@ -3604,7 +3603,6 @@ public float getOpacity() { * * @since 1.7 */ - @SuppressWarnings("deprecation") public void setOpacity(float opacity) { synchronized (getTreeLock()) { if (opacity < 0.0f || opacity > 1.0f) { diff --git a/src/java.desktop/share/classes/java/awt/dnd/DragSource.java b/src/java.desktop/share/classes/java/awt/dnd/DragSource.java index 8477bc6376d82..b5da544c46dc1 100644 --- a/src/java.desktop/share/classes/java/awt/dnd/DragSource.java +++ b/src/java.desktop/share/classes/java/awt/dnd/DragSource.java @@ -905,7 +905,6 @@ private void readObject(ObjectInputStream s) * @since 1.5 */ public static int getDragThreshold() { - @SuppressWarnings("removal") int ts = Integer.getInteger("awt.dnd.drag.threshold", 0); if (ts > 0) { return ts; diff --git a/src/java.desktop/share/classes/java/awt/event/FocusEvent.java b/src/java.desktop/share/classes/java/awt/event/FocusEvent.java index 4fb9043e5b786..27da2e8b4bb12 100644 --- a/src/java.desktop/share/classes/java/awt/event/FocusEvent.java +++ b/src/java.desktop/share/classes/java/awt/event/FocusEvent.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2024, 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 @@ -391,7 +391,6 @@ public final Cause getCause() { * @since 9 */ @Serial - @SuppressWarnings("serial") Object readResolve() throws ObjectStreamException { if (cause != null) { return this; diff --git a/src/java.desktop/share/classes/java/beans/Beans.java b/src/java.desktop/share/classes/java/beans/Beans.java index 247f698247136..e35a751a42ef3 100644 --- a/src/java.desktop/share/classes/java/beans/Beans.java +++ b/src/java.desktop/share/classes/java/beans/Beans.java @@ -105,7 +105,7 @@ public static Object instantiate(ClassLoader cls, String beanName) throws IOExce * @deprecated this method will be removed when java.beans.beancontext is removed */ @Deprecated(since = "23", forRemoval = true) - @SuppressWarnings({"deprecation", "removal"}) + @SuppressWarnings("removal") public static Object instantiate(ClassLoader cls, String beanName, BeanContext beanContext) throws IOException, ClassNotFoundException { diff --git a/src/java.desktop/share/classes/java/beans/beancontext/BeanContextChildComponentProxy.java b/src/java.desktop/share/classes/java/beans/beancontext/BeanContextChildComponentProxy.java index 91d22ecce3ba6..9f79d1c27a93d 100644 --- a/src/java.desktop/share/classes/java/beans/beancontext/BeanContextChildComponentProxy.java +++ b/src/java.desktop/share/classes/java/beans/beancontext/BeanContextChildComponentProxy.java @@ -41,7 +41,6 @@ * @see java.beans.beancontext.BeanContextSupport */ -@SuppressWarnings("removal") @Deprecated(since = "23", forRemoval = true) public interface BeanContextChildComponentProxy { diff --git a/src/java.desktop/share/classes/java/beans/beancontext/BeanContextContainerProxy.java b/src/java.desktop/share/classes/java/beans/beancontext/BeanContextContainerProxy.java index 3c6e0656c50f3..4fe6758b21f2d 100644 --- a/src/java.desktop/share/classes/java/beans/beancontext/BeanContextContainerProxy.java +++ b/src/java.desktop/share/classes/java/beans/beancontext/BeanContextContainerProxy.java @@ -40,7 +40,6 @@ * @see java.beans.beancontext.BeanContextSupport */ -@SuppressWarnings("removal") @Deprecated(since = "23", forRemoval = true) public interface BeanContextContainerProxy { diff --git a/src/java.desktop/share/classes/java/beans/beancontext/BeanContextServiceProviderBeanInfo.java b/src/java.desktop/share/classes/java/beans/beancontext/BeanContextServiceProviderBeanInfo.java index 11fe3fff730f3..60c80edee35fe 100644 --- a/src/java.desktop/share/classes/java/beans/beancontext/BeanContextServiceProviderBeanInfo.java +++ b/src/java.desktop/share/classes/java/beans/beancontext/BeanContextServiceProviderBeanInfo.java @@ -35,7 +35,6 @@ * services. */ -@SuppressWarnings("removal") @Deprecated(since = "23", forRemoval = true) public interface BeanContextServiceProviderBeanInfo extends BeanInfo { diff --git a/src/java.desktop/share/classes/javax/swing/DefaultFocusManager.java b/src/java.desktop/share/classes/javax/swing/DefaultFocusManager.java index 4413721097d10..47cca584452d4 100644 --- a/src/java.desktop/share/classes/javax/swing/DefaultFocusManager.java +++ b/src/java.desktop/share/classes/javax/swing/DefaultFocusManager.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2024, 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 @@ -47,7 +47,6 @@ * @author David Mendenhall * @since 1.2 */ -@SuppressWarnings("serial") // Obsolete class public class DefaultFocusManager extends FocusManager { final FocusTraversalPolicy gluePolicy = diff --git a/src/java.desktop/share/classes/javax/swing/JColorChooser.java b/src/java.desktop/share/classes/javax/swing/JColorChooser.java index 62c4fe8b0838a..89291be5f04e6 100644 --- a/src/java.desktop/share/classes/javax/swing/JColorChooser.java +++ b/src/java.desktop/share/classes/javax/swing/JColorChooser.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2024, 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 @@ -714,7 +714,6 @@ public void actionPerformed(ActionEvent e) { cancelButton.getAccessibleContext().setAccessibleDescription(cancelString); // The following few lines are used to register esc to close the dialog - @SuppressWarnings("serial") // anonymous class Action cancelKeyAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { ((AbstractButton)e.getSource()).fireActionPerformed(e); diff --git a/src/java.desktop/share/classes/javax/swing/JComponent.java b/src/java.desktop/share/classes/javax/swing/JComponent.java index 352fefeaacba6..92f3f01ab3e85 100644 --- a/src/java.desktop/share/classes/javax/swing/JComponent.java +++ b/src/java.desktop/share/classes/javax/swing/JComponent.java @@ -2949,7 +2949,7 @@ protected void processKeyEvent(KeyEvent e) { * * @since 1.3 */ - @SuppressWarnings({"deprecation", "removal"}) + @SuppressWarnings("deprecation") protected boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) { InputMap map = getInputMap(condition, false); diff --git a/src/java.desktop/share/classes/javax/swing/JLayer.java b/src/java.desktop/share/classes/javax/swing/JLayer.java index b08b140933f8a..7ce28b2b72372 100644 --- a/src/java.desktop/share/classes/javax/swing/JLayer.java +++ b/src/java.desktop/share/classes/javax/swing/JLayer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 2024, 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 @@ -735,7 +735,6 @@ public void doLayout() { * * @return the AccessibleContext associated with this {@code JLayer}. */ - @SuppressWarnings("serial") // anonymous class public AccessibleContext getAccessibleContext() { if (accessibleContext == null) { accessibleContext = new AccessibleJComponent() { diff --git a/src/java.desktop/share/classes/javax/swing/KeyStroke.java b/src/java.desktop/share/classes/javax/swing/KeyStroke.java index dcd87c7453556..054d1ad72bb87 100644 --- a/src/java.desktop/share/classes/javax/swing/KeyStroke.java +++ b/src/java.desktop/share/classes/javax/swing/KeyStroke.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2024, 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 @@ -66,7 +66,6 @@ * @author David Mendenhall * @since 1.2 */ -@SuppressWarnings("serial") // Same-version serialization only public class KeyStroke extends AWTKeyStroke { /** diff --git a/src/java.desktop/share/classes/javax/swing/Spring.java b/src/java.desktop/share/classes/javax/swing/Spring.java index 751eef76435f3..cf4504f51f910 100644 --- a/src/java.desktop/share/classes/javax/swing/Spring.java +++ b/src/java.desktop/share/classes/javax/swing/Spring.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2024, 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 @@ -127,7 +127,6 @@ * @author Philip Milne * @since 1.4 */ -@SuppressWarnings("serial") // Same-version serialization only public abstract class Spring { /** diff --git a/src/java.desktop/share/classes/javax/swing/SpringLayout.java b/src/java.desktop/share/classes/javax/swing/SpringLayout.java index 27641690e22fd..76050d31ce309 100644 --- a/src/java.desktop/share/classes/javax/swing/SpringLayout.java +++ b/src/java.desktop/share/classes/javax/swing/SpringLayout.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2024, 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 @@ -184,7 +184,6 @@ * @author Joe Winchester * @since 1.4 */ -@SuppressWarnings("serial") // Same-version serialization only public class SpringLayout implements LayoutManager2 { private Map componentConstraints = new HashMap(); diff --git a/src/java.desktop/share/classes/javax/swing/Timer.java b/src/java.desktop/share/classes/javax/swing/Timer.java index 3801eb0a0728f..46051d92df1c4 100644 --- a/src/java.desktop/share/classes/javax/swing/Timer.java +++ b/src/java.desktop/share/classes/javax/swing/Timer.java @@ -597,7 +597,6 @@ Lock getLock() { return lock; } - @SuppressWarnings("removal") @Serial private void readObject(ObjectInputStream in) throws ClassNotFoundException, IOException diff --git a/src/java.desktop/share/classes/javax/swing/UIManager.java b/src/java.desktop/share/classes/javax/swing/UIManager.java index 4c55e0c514993..752b37a5238f0 100644 --- a/src/java.desktop/share/classes/javax/swing/UIManager.java +++ b/src/java.desktop/share/classes/javax/swing/UIManager.java @@ -1261,7 +1261,6 @@ public static PropertyChangeListener[] getPropertyChangeListeners() { } } - @SuppressWarnings("removal") private static Properties loadSwingProperties() { /* Don't bother checking for Swing properties if untrusted, as diff --git a/src/java.desktop/share/classes/javax/swing/colorchooser/ColorChooserComponentFactory.java b/src/java.desktop/share/classes/javax/swing/colorchooser/ColorChooserComponentFactory.java index eb3920857a684..f1d012ad1780f 100644 --- a/src/java.desktop/share/classes/javax/swing/colorchooser/ColorChooserComponentFactory.java +++ b/src/java.desktop/share/classes/javax/swing/colorchooser/ColorChooserComponentFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2024, 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 @@ -43,7 +43,6 @@ * * @author Steve Wilson */ -@SuppressWarnings("serial") // Same-version serialization only public class ColorChooserComponentFactory { private ColorChooserComponentFactory() { } // can't instantiate diff --git a/src/java.desktop/share/classes/javax/swing/filechooser/FileSystemView.java b/src/java.desktop/share/classes/javax/swing/filechooser/FileSystemView.java index fb89f725cd0ca..6e9f9f26b376a 100644 --- a/src/java.desktop/share/classes/javax/swing/filechooser/FileSystemView.java +++ b/src/java.desktop/share/classes/javax/swing/filechooser/FileSystemView.java @@ -934,7 +934,6 @@ public File createFileObject(String path) { return super.createFileObject(path); } - @SuppressWarnings("serial") // anonymous class protected File createFileSystemRoot(File f) { // Problem: Removable drives on Windows return false on f.exists() // Workaround: Override exists() to always return true. diff --git a/src/java.desktop/share/classes/javax/swing/plaf/LayerUI.java b/src/java.desktop/share/classes/javax/swing/plaf/LayerUI.java index 61fad895c387c..00b7cfc0e5d0e 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/LayerUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/LayerUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 2024, 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 @@ -615,7 +615,6 @@ public void applyPropertyChange(PropertyChangeEvent evt, JLayer l) * baseline */ public int getBaseline(JComponent c, int width, int height) { - @SuppressWarnings("unchecked") JLayer l = (JLayer) c; if (l.getView() != null) { return l.getView().getBaseline(width, height); @@ -633,7 +632,6 @@ public int getBaseline(JComponent c, int width, int height) { * size changes */ public Component.BaselineResizeBehavior getBaselineResizeBehavior(JComponent c) { - @SuppressWarnings("unchecked") JLayer l = (JLayer) c; if (l.getView() != null) { return l.getView().getBaselineResizeBehavior(); @@ -666,7 +664,6 @@ public void doLayout(JLayer l) { * @return preferred size for the passed {@code JLayer} */ public Dimension getPreferredSize(JComponent c) { - @SuppressWarnings("unchecked") JLayer l = (JLayer) c; Component view = l.getView(); if (view != null) { @@ -684,7 +681,6 @@ public Dimension getPreferredSize(JComponent c) { * @return minimal size for the passed {@code JLayer} */ public Dimension getMinimumSize(JComponent c) { - @SuppressWarnings("unchecked") JLayer l = (JLayer) c; Component view = l.getView(); if (view != null) { @@ -702,7 +698,6 @@ public Dimension getMinimumSize(JComponent c) { * @return maximum size for the passed {@code JLayer} */ public Dimension getMaximumSize(JComponent c) { - @SuppressWarnings("unchecked") JLayer l = (JLayer) c; Component view = l.getView(); if (view != null) { diff --git a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicCheckBoxUI.java b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicCheckBoxUI.java index a1bd07282c1ef..24af28c94c099 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicCheckBoxUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicCheckBoxUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2024, 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 @@ -49,7 +49,6 @@ * * @author Jeff Dinkins */ -@SuppressWarnings("serial") // Same-version serialization only public class BasicCheckBoxUI extends BasicRadioButtonUI { private static final Object BASIC_CHECK_BOX_UI_KEY = new Object(); diff --git a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicComboBoxEditor.java b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicComboBoxEditor.java index 0e5eab8285b91..b2a8c58eb2ebb 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicComboBoxEditor.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicComboBoxEditor.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2024, 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 @@ -173,7 +173,6 @@ public void setBorder(Border b) { * has been added to the java.beans package. * Please see {@link java.beans.XMLEncoder}. */ - @SuppressWarnings("serial") // Same-version serialization only public static class UIResource extends BasicComboBoxEditor implements javax.swing.plaf.UIResource { /** diff --git a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicComboBoxUI.java b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicComboBoxUI.java index 6be306d557222..2d1a458e0d7fa 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicComboBoxUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicComboBoxUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2024, 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 @@ -1792,12 +1792,9 @@ public void propertyChange(PropertyChangeEvent e) { comboBox.revalidate(); } } else { - @SuppressWarnings("unchecked") JComboBox comboBox = (JComboBox)e.getSource(); if ( propertyName == "model" ) { - @SuppressWarnings("unchecked") ComboBoxModel newModel = (ComboBoxModel)e.getNewValue(); - @SuppressWarnings("unchecked") ComboBoxModel oldModel = (ComboBoxModel)e.getOldValue(); if ( oldModel != null && listDataListener != null ) { @@ -2012,7 +2009,6 @@ public Dimension minimumLayoutSize(Container parent) { } public void layoutContainer(Container parent) { - @SuppressWarnings("unchecked") JComboBox cb = (JComboBox)parent; int width = cb.getWidth(); int height = cb.getHeight(); diff --git a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicFileChooserUI.java b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicFileChooserUI.java index 57bd6664e1a42..bdce05ae866ba 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicFileChooserUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicFileChooserUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2024, 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 @@ -696,7 +696,6 @@ public void valueChanged(ListSelectionEvent evt) { if(!evt.getValueIsAdjusting()) { JFileChooser chooser = getFileChooser(); FileSystemView fsv = chooser.getFileSystemView(); - @SuppressWarnings("unchecked") JList list = (JList)evt.getSource(); int fsm = chooser.getFileSelectionMode(); diff --git a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicListUI.java b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicListUI.java index 53eb25a76d7ce..0a4aa03dce9d4 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicListUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicListUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2024, 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 @@ -1579,7 +1579,6 @@ private Handler getHandler() { * @see #installKeyboardActions * @see #installUI */ - @SuppressWarnings("serial") // Same-version serialization only public class MouseInputHandler implements MouseInputListener { /** @@ -1703,7 +1702,6 @@ protected FocusListener createFocusListener() { * @see #getCellBounds * @see #installUI */ - @SuppressWarnings("serial") // Same-version serialization only public class ListSelectionHandler implements ListSelectionListener { /** @@ -1769,7 +1767,6 @@ private void redrawList() { * @see #createListDataListener * @see #installUI */ - @SuppressWarnings("serial") // Same-version serialization only public class ListDataHandler implements ListDataListener { /** @@ -1842,7 +1839,6 @@ protected ListDataListener createListDataListener() { * @see #createPropertyChangeListener * @see #installUI */ - @SuppressWarnings("serial") // Same-version serialization only public class PropertyChangeHandler implements PropertyChangeListener { /** @@ -2653,9 +2649,7 @@ public void propertyChange(PropertyChangeEvent e) { * listDataListener from the old model and add it to the new one. */ if (propertyName == "model") { - @SuppressWarnings("unchecked") ListModel oldModel = (ListModel)e.getOldValue(); - @SuppressWarnings("unchecked") ListModel newModel = (ListModel)e.getNewValue(); if (oldModel != null) { oldModel.removeListDataListener(listDataListener); diff --git a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicOptionPaneUI.java b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicOptionPaneUI.java index 82547a4e03681..2e61967031ce6 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicOptionPaneUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicOptionPaneUI.java @@ -482,7 +482,6 @@ protected void addMessageComponents(Container container, if (nl >= 0) { // break up newlines if (nl == 0) { - @SuppressWarnings("serial") // anonymous class JPanel breakPanel = new JPanel() { public Dimension getPreferredSize() { Font f = getFont(); diff --git a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicSplitPaneDivider.java b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicSplitPaneDivider.java index 119e12276c790..cd59bf8433bf1 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicSplitPaneDivider.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicSplitPaneDivider.java @@ -746,7 +746,6 @@ public void mouseExited(MouseEvent e) { * has been added to the java.beans package. * Please see {@link java.beans.XMLEncoder}. */ - @SuppressWarnings("serial") // Same-version serialization only protected class DragController { /** diff --git a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicSplitPaneUI.java b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicSplitPaneUI.java index 31d20ab7b9361..5ff68f78d3829 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicSplitPaneUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicSplitPaneUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2024, 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 @@ -899,7 +899,6 @@ public BasicSplitPaneDivider getDivider() { * * @return the default non continuous layout divider */ - @SuppressWarnings("serial") // anonymous class protected Component createDefaultNonContinuousLayoutDivider() { return new Canvas() { public void paint(Graphics g) { diff --git a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicTextAreaUI.java b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicTextAreaUI.java index 2f5f86f872a8a..1d7128b7ac997 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicTextAreaUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicTextAreaUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2024, 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 @@ -49,7 +49,6 @@ * * @author Timothy Prinzing */ -@SuppressWarnings("serial") // Same-version serialization only public class BasicTextAreaUI extends BasicTextUI { /** diff --git a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicTextFieldUI.java b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicTextFieldUI.java index f379533620753..35c1d0e30b5f4 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicTextFieldUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicTextFieldUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2024, 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 @@ -51,7 +51,6 @@ * * @author Timothy Prinzing */ -@SuppressWarnings("serial") // Same-version serialization only public class BasicTextFieldUI extends BasicTextUI { /** diff --git a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicTextPaneUI.java b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicTextPaneUI.java index a76308dbec6c4..bf1587f826cac 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicTextPaneUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicTextPaneUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2024, 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 @@ -47,7 +47,6 @@ * * @author Timothy Prinzing */ -@SuppressWarnings("serial") // Same-version serialization only public class BasicTextPaneUI extends BasicEditorPaneUI { /** diff --git a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicToolBarUI.java b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicToolBarUI.java index e0e1a2e5ed6b2..41ab6137976f3 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicToolBarUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicToolBarUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2024, 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 @@ -554,13 +554,11 @@ private Border createNonRolloverToggleBorder() { @Deprecated(since = "17", forRemoval = true) protected JFrame createFloatingFrame(JToolBar toolbar) { Window window = SwingUtilities.getWindowAncestor(toolbar); - @SuppressWarnings("serial") // anonymous class JFrame frame = new JFrame(toolbar.getName(), (window != null) ? window.getGraphicsConfiguration() : null) { // Override createRootPane() to automatically resize // the frame when contents change protected JRootPane createRootPane() { - @SuppressWarnings("serial") // anonymous class JRootPane rootPane = new JRootPane() { private boolean packing = false; @@ -606,7 +604,6 @@ public ToolBarDialog(Dialog owner, String title, boolean modal) { // Override createRootPane() to automatically resize // the frame when contents change protected JRootPane createRootPane() { - @SuppressWarnings("serial") // anonymous class JRootPane rootPane = new JRootPane() { private boolean packing = false; diff --git a/src/java.desktop/share/classes/javax/swing/plaf/basic/ComboPopup.java b/src/java.desktop/share/classes/javax/swing/plaf/basic/ComboPopup.java index 122db23533470..71865b4f19f19 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/basic/ComboPopup.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/basic/ComboPopup.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2024, 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 @@ -46,7 +46,6 @@ * * @author Tom Santos */ -@SuppressWarnings("serial") // Same-version serialization only public interface ComboPopup { /** * Shows the popup diff --git a/src/java.desktop/share/classes/javax/swing/plaf/metal/DefaultMetalTheme.java b/src/java.desktop/share/classes/javax/swing/plaf/metal/DefaultMetalTheme.java index 3b9c79a8a9a7b..8ee862fb0b34f 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/metal/DefaultMetalTheme.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/metal/DefaultMetalTheme.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2024, 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 @@ -87,7 +87,6 @@ * * @author Steve Wilson */ -@SuppressWarnings("serial") // Same-version serialization only public class DefaultMetalTheme extends MetalTheme { /** * Whether or not fonts should be plain. This is only used if diff --git a/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalButtonUI.java b/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalButtonUI.java index 2a0b1928fb7a2..0bbbab7b45f8c 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalButtonUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalButtonUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2024, 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 @@ -50,7 +50,6 @@ * * @author Tom Santos */ -@SuppressWarnings("serial") // Same-version serialization only public class MetalButtonUI extends BasicButtonUI { // NOTE: These are not really needed, but at this point we can't pull diff --git a/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalCheckBoxUI.java b/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalCheckBoxUI.java index 0470d15718ad8..558f1987e4d42 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalCheckBoxUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalCheckBoxUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2024, 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 @@ -51,7 +51,6 @@ * @author Michael C. Albers * */ -@SuppressWarnings("serial") // Same-version serialization only public class MetalCheckBoxUI extends MetalRadioButtonUI { // NOTE: MetalCheckBoxUI inherits from MetalRadioButtonUI instead diff --git a/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalComboBoxEditor.java b/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalComboBoxEditor.java index 6765e0344524a..bac9a821a754e 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalComboBoxEditor.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalComboBoxEditor.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2024, 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 @@ -135,7 +135,6 @@ public Insets getBorderInsets(Component c, Insets insets) { * has been added to the java.beans package. * Please see {@link java.beans.XMLEncoder}. */ - @SuppressWarnings("serial") // Same-version serialization only public static class UIResource extends MetalComboBoxEditor implements javax.swing.plaf.UIResource { /** diff --git a/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalFileChooserUI.java b/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalFileChooserUI.java index 23803dafde986..a7b8718ca8daf 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalFileChooserUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalFileChooserUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2024, 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 @@ -238,7 +238,6 @@ public void installComponents(JFileChooser fc) { topPanel.add(lookInLabel, BorderLayout.BEFORE_LINE_BEGINS); // CurrentDir ComboBox - @SuppressWarnings("serial") // anonymous class JComboBox tmp1 = new JComboBox() { public Dimension getPreferredSize() { Dimension d = super.getPreferredSize(); @@ -381,7 +380,6 @@ public void propertyChange(PropertyChangeEvent e) { populateFileNameLabel(); fileNamePanel.add(fileNameLabel); - @SuppressWarnings("serial") // anonymous class JTextField tmp2 = new JTextField(35) { public Dimension getMaximumSize() { return new Dimension(Short.MAX_VALUE, super.getPreferredSize().height); diff --git a/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalProgressBarUI.java b/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalProgressBarUI.java index 5f316cbb20979..b5dddfc127407 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalProgressBarUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalProgressBarUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2024, 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 @@ -44,7 +44,6 @@ * * @author Michael C. Albers */ -@SuppressWarnings("serial") // Same-version serialization only public class MetalProgressBarUI extends BasicProgressBarUI { private Rectangle innards; diff --git a/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalRadioButtonUI.java b/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalRadioButtonUI.java index 8bd1f9acc0a62..712046737eb39 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalRadioButtonUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalRadioButtonUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2024, 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 @@ -53,7 +53,6 @@ * @author Michael C. Albers (Metal modifications) * @author Jeff Dinkins (original BasicRadioButtonCode) */ -@SuppressWarnings("serial") // Same-version serialization only public class MetalRadioButtonUI extends BasicRadioButtonUI { private static final Object METAL_RADIO_BUTTON_UI_KEY = new Object(); diff --git a/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalRootPaneUI.java b/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalRootPaneUI.java index 81ea2fe28eeeb..b243c5ca4723f 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalRootPaneUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalRootPaneUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2024, 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 @@ -77,7 +77,6 @@ * @author Terry Kellerman * @since 1.4 */ -@SuppressWarnings("serial") // Same-version serialization only public class MetalRootPaneUI extends BasicRootPaneUI { /** diff --git a/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalScrollPaneUI.java b/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalScrollPaneUI.java index e90d8657ae5e5..e94edc28b65b7 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalScrollPaneUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalScrollPaneUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2024, 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 @@ -50,7 +50,6 @@ * * @author Steve Wilson */ -@SuppressWarnings("serial") // Same-version serialization only public class MetalScrollPaneUI extends BasicScrollPaneUI { diff --git a/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalSeparatorUI.java b/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalSeparatorUI.java index 9140577b89598..fe8a45aa9791f 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalSeparatorUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalSeparatorUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2024, 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 @@ -50,7 +50,6 @@ * * @author Jeff Shapiro */ -@SuppressWarnings("serial") // Same-version serialization only public class MetalSeparatorUI extends BasicSeparatorUI { /** diff --git a/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalSliderUI.java b/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalSliderUI.java index 0313359682288..c31ee81c729e6 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalSliderUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalSliderUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2024, 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 @@ -50,7 +50,6 @@ * * @author Tom Santos */ -@SuppressWarnings("serial") // Same-version serialization only public class MetalSliderUI extends BasicSliderUI { /** diff --git a/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalSplitPaneUI.java b/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalSplitPaneUI.java index ee888771ff271..aba58db389b62 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalSplitPaneUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalSplitPaneUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2024, 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 @@ -43,7 +43,6 @@ * * @author Steve Wilson */ -@SuppressWarnings("serial") // Same-version serialization only public class MetalSplitPaneUI extends BasicSplitPaneUI { /** diff --git a/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalTabbedPaneUI.java b/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalTabbedPaneUI.java index d73ef0d661311..8f9229d4cbdaf 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalTabbedPaneUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalTabbedPaneUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2024, 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 @@ -47,7 +47,6 @@ * * @author Tom Santos */ -@SuppressWarnings("serial") // Same-version serialization only public class MetalTabbedPaneUI extends BasicTabbedPaneUI { /** diff --git a/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalTextFieldUI.java b/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalTextFieldUI.java index 9a59f99fdceb7..e7bbc0baf696d 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalTextFieldUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalTextFieldUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2024, 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 @@ -47,7 +47,6 @@ * * @author Steve Wilson */ -@SuppressWarnings("serial") // Same-version serialization only public class MetalTextFieldUI extends BasicTextFieldUI { /** diff --git a/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalToggleButtonUI.java b/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalToggleButtonUI.java index 325f30f7e0ad7..088a54ba6b25d 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalToggleButtonUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalToggleButtonUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2024, 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 @@ -55,7 +55,6 @@ * * @author Tom Santos */ -@SuppressWarnings("serial") // Same-version serialization only public class MetalToggleButtonUI extends BasicToggleButtonUI { private static final Object METAL_TOGGLE_BUTTON_UI_KEY = new Object(); diff --git a/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalToolTipUI.java b/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalToolTipUI.java index 6cf5314b4a000..258a37b8dbbd2 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalToolTipUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalToolTipUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2024, 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 @@ -49,7 +49,6 @@ * * @author Steve Wilson */ -@SuppressWarnings("serial") // Same-version serialization only public class MetalToolTipUI extends BasicToolTipUI { static MetalToolTipUI sharedInstance = new MetalToolTipUI(); diff --git a/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalUtils.java b/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalUtils.java index 5ed2cd9b5ced5..7990288684889 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalUtils.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalUtils.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2024, 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 @@ -210,7 +210,6 @@ static int getInt(Object key, int defaultValue) { */ static boolean drawGradient(Component c, Graphics g, String key, int x, int y, int w, int h, boolean vertical) { - @SuppressWarnings("unchecked") java.util.List gradient = (java.util.List)UIManager.get(key); if (gradient == null || !(g instanceof Graphics2D)) { return false; @@ -275,7 +274,6 @@ public void paint(Component c, Graphics2D g, protected void paintToImage(Component c, Image image, Graphics g, int w, int h, Object[] args) { Graphics2D g2 = (Graphics2D)g; - @SuppressWarnings("unchecked") java.util.List gradient = (java.util.List)args[0]; boolean isVertical = ((Boolean)args[1]).booleanValue(); // Render to the VolatileImage diff --git a/src/java.desktop/share/classes/javax/swing/plaf/multi/MultiLookAndFeel.java b/src/java.desktop/share/classes/javax/swing/plaf/multi/MultiLookAndFeel.java index 3862a5ab8711d..a2d3edd659d7c 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/multi/MultiLookAndFeel.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/multi/MultiLookAndFeel.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2024, 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 @@ -56,7 +56,6 @@ * * @author Willie Walker */ -@SuppressWarnings("serial") // Same-version serialization only public class MultiLookAndFeel extends LookAndFeel { /** diff --git a/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthDesktopIconUI.java b/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthDesktopIconUI.java index 0b82788032ee8..23e6e8ec4a340 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthDesktopIconUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthDesktopIconUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2024, 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 @@ -76,7 +76,6 @@ public static ComponentUI createUI(JComponent c) { @Override protected void installComponents() { if (UIManager.getBoolean("InternalFrame.useTaskBar")) { - @SuppressWarnings("serial") // anonymous class JToggleButton tmp = new JToggleButton(frame.getTitle(), frame.getFrameIcon()) { @Override public String getToolTipText() { return getText(); diff --git a/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthScrollBarUI.java b/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthScrollBarUI.java index 52ab14a359fb4..f8bf123ca893c 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthScrollBarUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthScrollBarUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2024, 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 @@ -376,7 +376,6 @@ protected Dimension getMinimumThumbSize() { */ @Override protected JButton createDecreaseButton(int orientation) { - @SuppressWarnings("serial") // anonymous class SynthArrowButton synthArrowButton = new SynthArrowButton(orientation) { @Override public boolean contains(int x, int y) { @@ -406,7 +405,6 @@ public boolean contains(int x, int y) { */ @Override protected JButton createIncreaseButton(int orientation) { - @SuppressWarnings("serial") // anonymous class SynthArrowButton synthArrowButton = new SynthArrowButton(orientation) { @Override public boolean contains(int x, int y) { diff --git a/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthSplitPaneUI.java b/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthSplitPaneUI.java index 49a9689409f9e..4ac76dec28241 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthSplitPaneUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthSplitPaneUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2024, 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 @@ -277,7 +277,6 @@ private void setDividerDraggingColor(Graphics g, int loc) { * {@inheritDoc} */ @Override - @SuppressWarnings("serial") // anonymous class protected Component createDefaultNonContinuousLayoutDivider() { return new Canvas() { public void paint(Graphics g) { diff --git a/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthTextAreaUI.java b/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthTextAreaUI.java index 3d4c41d967788..956a4ee2fcc33 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthTextAreaUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthTextAreaUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2024, 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 @@ -51,7 +51,6 @@ * @author Shannon Hickey * @since 1.7 */ -@SuppressWarnings("serial") // Same-version serialization only public class SynthTextAreaUI extends BasicTextAreaUI implements SynthUI { private Handler handler = new Handler(); private SynthStyle style; diff --git a/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthTextFieldUI.java b/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthTextFieldUI.java index 61fd591d9afec..02ab78d14e8fb 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthTextFieldUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthTextFieldUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2024, 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 @@ -50,7 +50,6 @@ * @author Shannon Hickey * @since 1.7 */ -@SuppressWarnings("serial") // Same-version serialization only public class SynthTextFieldUI extends BasicTextFieldUI implements SynthUI { private Handler handler = new Handler(); private SynthStyle style; diff --git a/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthTextPaneUI.java b/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthTextPaneUI.java index 4aa5567aa26c9..c966b979e32d3 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthTextPaneUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthTextPaneUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2024, 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 @@ -47,7 +47,6 @@ * @author Shannon Hickey * @since 1.7 */ -@SuppressWarnings("serial") // Same-version serialization only public class SynthTextPaneUI extends SynthEditorPaneUI { /** diff --git a/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthTreeUI.java b/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthTreeUI.java index f9d0d6eb1fad1..0e9caf3ebd8c2 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthTreeUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthTreeUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2024, 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 @@ -771,7 +771,6 @@ public SynthTreeCellEditor(JTree tree, @Override protected TreeCellEditor createTreeCellEditor() { - @SuppressWarnings("serial") // anonymous class JTextField tf = new JTextField() { @Override public String getName() { diff --git a/src/java.desktop/share/classes/javax/swing/text/DefaultStyledDocument.java b/src/java.desktop/share/classes/javax/swing/text/DefaultStyledDocument.java index 60ca2d7263428..757eccfcd53c2 100644 --- a/src/java.desktop/share/classes/javax/swing/text/DefaultStyledDocument.java +++ b/src/java.desktop/share/classes/javax/swing/text/DefaultStyledDocument.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2024, 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 @@ -1182,7 +1182,6 @@ public String getName() { * has been added to the java.beans package. * Please see {@link java.beans.XMLEncoder}. */ - @SuppressWarnings("serial") // Same-version serialization only public static class ElementSpec { /** diff --git a/src/java.desktop/share/classes/javax/swing/text/JTextComponent.java b/src/java.desktop/share/classes/javax/swing/text/JTextComponent.java index ce36a5d5a1fe6..03e04d1c1a783 100644 --- a/src/java.desktop/share/classes/javax/swing/text/JTextComponent.java +++ b/src/java.desktop/share/classes/javax/swing/text/JTextComponent.java @@ -1127,7 +1127,6 @@ private static HashMap getKeymapTable() { * has been added to the java.beans package. * Please see {@link java.beans.XMLEncoder}. */ - @SuppressWarnings("serial") // Same-version serialization only public static class KeyBinding { /** @@ -3951,7 +3950,6 @@ public String toString() { * Maps from class name to Boolean indicating if * processInputMethodEvent has been overridden. */ - @SuppressWarnings("removal") private static Cache,Boolean> METHOD_OVERRIDDEN = new Cache,Boolean>(Cache.Kind.WEAK, Cache.Kind.STRONG) { /** diff --git a/src/java.desktop/share/classes/javax/swing/text/SimpleAttributeSet.java b/src/java.desktop/share/classes/javax/swing/text/SimpleAttributeSet.java index 30a47c02a1f37..ad6afb140921a 100644 --- a/src/java.desktop/share/classes/javax/swing/text/SimpleAttributeSet.java +++ b/src/java.desktop/share/classes/javax/swing/text/SimpleAttributeSet.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2024, 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 @@ -48,7 +48,6 @@ * * @author Tim Prinzing */ -@SuppressWarnings("serial") // Same-version serialization only public class SimpleAttributeSet implements MutableAttributeSet, Serializable, Cloneable { /** diff --git a/src/java.desktop/share/classes/javax/swing/text/StyledEditorKit.java b/src/java.desktop/share/classes/javax/swing/text/StyledEditorKit.java index e2630c93623c7..636196de69c39 100644 --- a/src/java.desktop/share/classes/javax/swing/text/StyledEditorKit.java +++ b/src/java.desktop/share/classes/javax/swing/text/StyledEditorKit.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2024, 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 @@ -171,7 +171,6 @@ public Object clone() { /** * Creates the AttributeSet used for the selection. */ - @SuppressWarnings("serial") // anonymous class private void createInputAttributes() { inputAttributes = new SimpleAttributeSet() { public AttributeSet getResolveParent() { diff --git a/src/java.desktop/share/classes/javax/swing/text/WrappedPlainView.java b/src/java.desktop/share/classes/javax/swing/text/WrappedPlainView.java index 8d6980eaaeab8..0bceae3acee12 100644 --- a/src/java.desktop/share/classes/javax/swing/text/WrappedPlainView.java +++ b/src/java.desktop/share/classes/javax/swing/text/WrappedPlainView.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2024, 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 @@ -352,7 +352,6 @@ protected final Segment getLineBuffer() { * @param p1 the ending document location to use * @return the break position */ - @SuppressWarnings("deprecation") protected int calculateBreakPosition(int p0, int p1) { int p; Segment segment = SegmentCache.getSharedSegment(); @@ -798,7 +797,6 @@ public Shape modelToView(int pos, Shape a, Position.Bias b) * given point in the view * @see View#viewToModel */ - @SuppressWarnings("deprecation") public int viewToModel(float fx, float fy, Shape a, Position.Bias[] bias) { // PENDING(prinz) implement bias properly bias[0] = Position.Bias.Forward; diff --git a/src/java.desktop/share/classes/javax/swing/text/html/FormView.java b/src/java.desktop/share/classes/javax/swing/text/html/FormView.java index 8af4f9e2f1e19..47f10e1abb2a7 100644 --- a/src/java.desktop/share/classes/javax/swing/text/html/FormView.java +++ b/src/java.desktop/share/classes/javax/swing/text/html/FormView.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2024, 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 @@ -382,7 +382,6 @@ private void removeStaleListenerForModel(Object model) { // BasicListUI$Handler. // For JComboBox, there are 2 stale ListDataListeners, which are // BasicListUI$Handler and BasicComboBoxUI$Handler. - @SuppressWarnings("unchecked") AbstractListModel listModel = (AbstractListModel) model; String listenerClass1 = "javax.swing.plaf.basic.BasicListUI$Handler"; @@ -850,7 +849,6 @@ private void loadSelectData(AttributeSet attr, StringBuilder buffer) { } } } else if (m instanceof ComboBoxModel) { - @SuppressWarnings("unchecked") ComboBoxModel model = (ComboBoxModel)m; Option option = (Option)model.getSelectedItem(); if (option != null) { @@ -962,7 +960,6 @@ void resetForm() { } catch (BadLocationException e) { } } else if (m instanceof OptionListModel) { - @SuppressWarnings("unchecked") OptionListModel model = (OptionListModel) m; int size = model.getSize(); for (int i = 0; i < size; i++) { @@ -975,7 +972,6 @@ void resetForm() { } } } else if (m instanceof OptionComboBoxModel) { - @SuppressWarnings("unchecked") OptionComboBoxModel model = (OptionComboBoxModel) m; Option option = model.getInitialSelection(); if (option != null) { diff --git a/src/java.desktop/share/classes/javax/swing/tree/AbstractLayoutCache.java b/src/java.desktop/share/classes/javax/swing/tree/AbstractLayoutCache.java index d3435231e7f3c..97383785dca8e 100644 --- a/src/java.desktop/share/classes/javax/swing/tree/AbstractLayoutCache.java +++ b/src/java.desktop/share/classes/javax/swing/tree/AbstractLayoutCache.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2024, 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 @@ -41,7 +41,6 @@ * * @author Scott Violet */ -@SuppressWarnings("serial") // Same-version serialization only public abstract class AbstractLayoutCache implements RowMapper { /** Object responsible for getting the size of a node. */ protected NodeDimensions nodeDimensions; diff --git a/src/java.desktop/share/classes/javax/swing/tree/DefaultTreeCellEditor.java b/src/java.desktop/share/classes/javax/swing/tree/DefaultTreeCellEditor.java index 2397f51f7a62b..4662c95c01fc4 100644 --- a/src/java.desktop/share/classes/javax/swing/tree/DefaultTreeCellEditor.java +++ b/src/java.desktop/share/classes/javax/swing/tree/DefaultTreeCellEditor.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2024, 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 @@ -537,7 +537,6 @@ protected Container createContainer() { */ protected TreeCellEditor createTreeCellEditor() { Border aBorder = UIManager.getBorder("Tree.editorBorder"); - @SuppressWarnings("serial") // Safe: outer class is non-serializable DefaultCellEditor editor = new DefaultCellEditor (new DefaultTextField(aBorder)) { public boolean shouldSelectCell(EventObject event) { diff --git a/src/java.desktop/share/classes/sun/awt/AWTAutoShutdown.java b/src/java.desktop/share/classes/sun/awt/AWTAutoShutdown.java index e944d19e1c117..5a81de507db1f 100644 --- a/src/java.desktop/share/classes/sun/awt/AWTAutoShutdown.java +++ b/src/java.desktop/share/classes/sun/awt/AWTAutoShutdown.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2024, 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 @@ -321,7 +321,6 @@ public void run() { } } - @SuppressWarnings("serial") static AWTEvent getShutdownEvent() { return new AWTEvent(getInstance(), 0) { }; diff --git a/src/java.desktop/share/classes/sun/awt/AppContext.java b/src/java.desktop/share/classes/sun/awt/AppContext.java index 48482dfc39afc..a35d89f6a0ca1 100644 --- a/src/java.desktop/share/classes/sun/awt/AppContext.java +++ b/src/java.desktop/share/classes/sun/awt/AppContext.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2024, 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 @@ -362,7 +362,6 @@ public static boolean isMainContext(AppContext ctx) { * contained within this AppContext * @since 1.2 */ - @SuppressWarnings("deprecation") public void dispose() throws IllegalThreadStateException { System.err.println( """ diff --git a/src/java.desktop/share/classes/sun/awt/CausedFocusEvent.java b/src/java.desktop/share/classes/sun/awt/CausedFocusEvent.java index 2527eda11f6b9..a6293d4efea46 100644 --- a/src/java.desktop/share/classes/sun/awt/CausedFocusEvent.java +++ b/src/java.desktop/share/classes/sun/awt/CausedFocusEvent.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2024, 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 @@ -59,7 +59,6 @@ private enum Cause { RETARGETED } - @SuppressWarnings("serial") private static final Component dummy = new Component(){}; private final Cause cause; diff --git a/src/java.desktop/share/classes/sun/awt/KeyboardFocusManagerPeerImpl.java b/src/java.desktop/share/classes/sun/awt/KeyboardFocusManagerPeerImpl.java index 86b957398f77e..ef50d883ee59e 100644 --- a/src/java.desktop/share/classes/sun/awt/KeyboardFocusManagerPeerImpl.java +++ b/src/java.desktop/share/classes/sun/awt/KeyboardFocusManagerPeerImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2024, 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 @@ -104,7 +104,6 @@ public static boolean shouldFocusOnClick(Component component) { /* * Posts proper lost/gain focus events to the event queue. */ - @SuppressWarnings("deprecation") public static boolean deliverFocus(Component lightweightChild, Component target, boolean temporary, diff --git a/src/java.desktop/share/classes/sun/awt/LightweightFrame.java b/src/java.desktop/share/classes/sun/awt/LightweightFrame.java index cd1cdf3ebd5d6..205b8034b7ec0 100644 --- a/src/java.desktop/share/classes/sun/awt/LightweightFrame.java +++ b/src/java.desktop/share/classes/sun/awt/LightweightFrame.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2024, 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 @@ -88,7 +88,6 @@ public LightweightFrame() { @Override public final void toFront() {} @Override public final void toBack() {} - @SuppressWarnings("deprecation") @Override public void addNotify() { synchronized (getTreeLock()) { if (!isDisplayable()) { diff --git a/src/java.desktop/share/classes/sun/awt/SunToolkit.java b/src/java.desktop/share/classes/sun/awt/SunToolkit.java index 355ee995c8c5a..5c4ebda8715d7 100644 --- a/src/java.desktop/share/classes/sun/awt/SunToolkit.java +++ b/src/java.desktop/share/classes/sun/awt/SunToolkit.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2024, 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 @@ -525,7 +525,6 @@ public static void executeOnEventHandlerThread(Object target, * Fixed 5064013: the InvocationEvent time should be equals * the time of the ActionEvent */ - @SuppressWarnings("serial") public static void executeOnEventHandlerThread(Object target, Runnable runnable, final long when) { @@ -1569,7 +1568,6 @@ private boolean isEQEmpty() { * Should return {@code true} if more processing is * necessary, {@code false} otherwise. */ - @SuppressWarnings("serial") private final boolean waitForIdle(final long end) { if (timeout(end) <= 0) { return false; diff --git a/src/java.desktop/share/classes/sun/java2d/Disposer.java b/src/java.desktop/share/classes/sun/java2d/Disposer.java index 5a80a61604544..5692b490278d2 100644 --- a/src/java.desktop/share/classes/sun/java2d/Disposer.java +++ b/src/java.desktop/share/classes/sun/java2d/Disposer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2024, 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 @@ -241,7 +241,6 @@ public static void pollRemove() { * so will clutter the records hashmap and no one will be cleaning up * the reference queue. */ - @SuppressWarnings("unchecked") public static void addReference(Reference ref, DisposerRecord rec) { records.put(ref, rec); } diff --git a/src/java.desktop/share/classes/sun/java2d/marlin/DMarlinRenderingEngine.java b/src/java.desktop/share/classes/sun/java2d/marlin/DMarlinRenderingEngine.java index a42e474e76492..b29cc84c12778 100644 --- a/src/java.desktop/share/classes/sun/java2d/marlin/DMarlinRenderingEngine.java +++ b/src/java.desktop/share/classes/sun/java2d/marlin/DMarlinRenderingEngine.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2024, 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 @@ -1300,7 +1300,6 @@ private static void logSettings(final String reClass) { * Get the RendererContext instance dedicated to the current thread * @return RendererContext instance */ - @SuppressWarnings({"unchecked"}) static RendererContext getRendererContext() { final RendererContext rdrCtx = RDR_CTX_PROVIDER.acquire(); if (DO_MONITORS) { diff --git a/src/java.desktop/share/classes/sun/print/ServiceDialog.java b/src/java.desktop/share/classes/sun/print/ServiceDialog.java index 6f2bdecb8099a..983be70bdbbb9 100644 --- a/src/java.desktop/share/classes/sun/print/ServiceDialog.java +++ b/src/java.desktop/share/classes/sun/print/ServiceDialog.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2024, 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 @@ -296,7 +296,6 @@ public void windowClosing(WindowEvent event) { * Performs Cancel when Esc key is pressed. */ private void handleEscKey(JButton btnCancel) { - @SuppressWarnings("serial") // anonymous class Action cancelKeyAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { dispose(CANCEL); diff --git a/src/java.desktop/share/classes/sun/swing/FilePane.java b/src/java.desktop/share/classes/sun/swing/FilePane.java index e97dcb3b88185..395cf058b7d6f 100644 --- a/src/java.desktop/share/classes/sun/swing/FilePane.java +++ b/src/java.desktop/share/classes/sun/swing/FilePane.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2024, 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 @@ -659,7 +659,6 @@ public JPanel createList() { JPanel p = new JPanel(new BorderLayout()); final JFileChooser fileChooser = getFileChooser(); - @SuppressWarnings("serial") // anonymous class final JList list = new JList() { public int getNextMatch(String prefix, int startIndex, Position.Bias bias) { ListModel model = getModel(); @@ -1262,7 +1261,6 @@ public JPanel createDetailsView() { JPanel p = new JPanel(new BorderLayout()); - @SuppressWarnings("serial") // anonymous class final JTable detailsTable = new JTable(getDetailsTableModel()) { // Handle Escape key events here protected boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) { @@ -1575,7 +1573,6 @@ private void applyEdit() { protected Action newFolderAction; - @SuppressWarnings("serial") // anonymous class inside public Action getNewFolderAction() { if (!readOnly && newFolderAction == null) { newFolderAction = new AbstractAction(newFolderActionLabelText) { diff --git a/src/java.desktop/share/classes/sun/swing/JLightweightFrame.java b/src/java.desktop/share/classes/sun/swing/JLightweightFrame.java index cfc5ceef6c331..d83b940a0bd6c 100644 --- a/src/java.desktop/share/classes/sun/swing/JLightweightFrame.java +++ b/src/java.desktop/share/classes/sun/swing/JLightweightFrame.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2024, 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 @@ -331,7 +331,7 @@ private void notifyImageUpdated(int x, int y, int width, int height) { content.imageUpdated(x, y, width, height); } - @SuppressWarnings({"removal","serial"}) // anonymous class inside + @SuppressWarnings("removal") private void initInterior() { contentPane = new JPanel() { @Override diff --git a/src/java.desktop/share/classes/sun/swing/LightweightContent.java b/src/java.desktop/share/classes/sun/swing/LightweightContent.java index eb283908e817c..f67e3ad7fcf41 100644 --- a/src/java.desktop/share/classes/sun/swing/LightweightContent.java +++ b/src/java.desktop/share/classes/sun/swing/LightweightContent.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2024, 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 @@ -161,7 +161,6 @@ default public void imageBufferReset(int[] data, * @param scaleY the y coordinate scale factor of the pixel buffer * @since 9 */ - @SuppressWarnings("deprecation") default public void imageBufferReset(int[] data, int x, int y, int width, int height, @@ -178,7 +177,6 @@ default public void imageBufferReset(int[] data, * default implementations in order to allow a client application to run * with any JDK version without breaking backward compatibility. */ - @SuppressWarnings("deprecation") default public void imageBufferReset(int[] data, int x, int y, int width, int height, diff --git a/src/java.desktop/share/classes/sun/swing/PrintingStatus.java b/src/java.desktop/share/classes/sun/swing/PrintingStatus.java index 1f7358a28810a..b2fbed5222ec3 100644 --- a/src/java.desktop/share/classes/sun/swing/PrintingStatus.java +++ b/src/java.desktop/share/classes/sun/swing/PrintingStatus.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2024, 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 @@ -62,7 +62,6 @@ public class PrintingStatus { private final AtomicBoolean isAborted = new AtomicBoolean(false); // the action that will abort printing - @SuppressWarnings("serial") // anonymous class private final Action abortAction = new AbstractAction() { public void actionPerformed(ActionEvent ae) { if (!isAborted.get()) { diff --git a/src/java.desktop/share/classes/sun/swing/plaf/synth/SynthFileChooserUIImpl.java b/src/java.desktop/share/classes/sun/swing/plaf/synth/SynthFileChooserUIImpl.java index 81789bcfdcf7b..c225ddc9ff60b 100644 --- a/src/java.desktop/share/classes/sun/swing/plaf/synth/SynthFileChooserUIImpl.java +++ b/src/java.desktop/share/classes/sun/swing/plaf/synth/SynthFileChooserUIImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2024, 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 @@ -188,7 +188,6 @@ protected void installDefaults(JFileChooser fc) { readOnly = UIManager.getBoolean("FileChooser.readOnly"); } - @SuppressWarnings("serial") // anonymous classes inside public void installComponents(JFileChooser fc) { super.installComponents(fc); diff --git a/src/java.desktop/share/classes/sun/swing/text/TextComponentPrintable.java b/src/java.desktop/share/classes/sun/swing/text/TextComponentPrintable.java index 28d57b02b634b..f93c1673acafd 100644 --- a/src/java.desktop/share/classes/sun/swing/text/TextComponentPrintable.java +++ b/src/java.desktop/share/classes/sun/swing/text/TextComponentPrintable.java @@ -332,7 +332,6 @@ public JTextComponent call() throws Exception { } } - @SuppressWarnings("serial") // anonymous class inside private JTextComponent createPrintShellOnEDT(final JTextComponent textComponent) { assert SwingUtilities.isEventDispatchThread(); From 189fc8ddeffb4dd595ccd8ad3ca53a0ed4cee91f Mon Sep 17 00:00:00 2001 From: Amit Kumar Date: Wed, 20 Nov 2024 08:25:37 +0000 Subject: [PATCH 32/74] 8344381: [s390x] Test failures with error: Register type is not known Reviewed-by: mdoerr, lucy --- .../gc/shared/barrierSetAssembler_s390.cpp | 34 ++++++++++++++----- 1 file changed, 26 insertions(+), 8 deletions(-) diff --git a/src/hotspot/cpu/s390/gc/shared/barrierSetAssembler_s390.cpp b/src/hotspot/cpu/s390/gc/shared/barrierSetAssembler_s390.cpp index d826b4a06f336..8ead8e8ff38b5 100644 --- a/src/hotspot/cpu/s390/gc/shared/barrierSetAssembler_s390.cpp +++ b/src/hotspot/cpu/s390/gc/shared/barrierSetAssembler_s390.cpp @@ -218,10 +218,10 @@ SaveLiveRegisters::SaveLiveRegisters(MacroAssembler *masm, BarrierStubC2 *stub) const int register_save_size = iterate_over_register_mask(ACTION_COUNT_ONLY) * BytesPerWord; - _frame_size = align_up(register_save_size, frame::alignment_in_bytes) + frame::z_abi_160_size; // FIXME: this could be restricted to argument only + _frame_size = align_up(register_save_size, frame::alignment_in_bytes) + frame::z_abi_160_size; __ save_return_pc(); - __ push_frame(_frame_size, Z_R14); // FIXME: check if Z_R1_scaratch can do a job here; + __ push_frame(_frame_size, Z_R14); __ z_lg(Z_R14, _z_common_abi(return_pc) + _frame_size, Z_SP); @@ -240,6 +240,7 @@ int SaveLiveRegisters::iterate_over_register_mask(IterationAction action, int of int reg_save_index = 0; RegMaskIterator live_regs_iterator(_reg_mask); + // Going to preserve the volatile registers which can be used by Register Allocator. while(live_regs_iterator.has_next()) { const OptoReg::Name opto_reg = live_regs_iterator.next(); @@ -251,8 +252,11 @@ int SaveLiveRegisters::iterate_over_register_mask(IterationAction action, int of const VMReg vm_reg = OptoReg::as_VMReg(opto_reg); if (vm_reg->is_Register()) { Register std_reg = vm_reg->as_Register(); - - if (std_reg->encoding() >= Z_R2->encoding() && std_reg->encoding() <= Z_R15->encoding()) { + // Z_R0 and Z_R1 will not be allocated by the register allocator, see s390.ad (Integer Register Classes) + // Z_R6 to Z_R15 are saved registers, except Z_R14 (see Z-Abi) + if (std_reg->encoding() == Z_R14->encoding() || + (std_reg->encoding() >= Z_R2->encoding() && + std_reg->encoding() <= Z_R5->encoding())) { reg_save_index++; if (action == ACTION_SAVE) { @@ -265,8 +269,10 @@ int SaveLiveRegisters::iterate_over_register_mask(IterationAction action, int of } } else if (vm_reg->is_FloatRegister()) { FloatRegister fp_reg = vm_reg->as_FloatRegister(); - if (fp_reg->encoding() >= Z_F0->encoding() && fp_reg->encoding() <= Z_F15->encoding() - && fp_reg->encoding() != Z_F1->encoding()) { + // Z_R1 will not be allocated by the register allocator, see s390.ad (Float Register Classes) + if (fp_reg->encoding() >= Z_F0->encoding() && + fp_reg->encoding() <= Z_F7->encoding() && + fp_reg->encoding() != Z_F1->encoding()) { reg_save_index++; if (action == ACTION_SAVE) { @@ -277,8 +283,20 @@ int SaveLiveRegisters::iterate_over_register_mask(IterationAction action, int of assert(action == ACTION_COUNT_ONLY, "Sanity"); } } - } else if (false /* vm_reg->is_VectorRegister() */){ - fatal("Vector register support is not there yet!"); + } else if (vm_reg->is_VectorRegister()) { + VectorRegister vs_reg = vm_reg->as_VectorRegister(); + // Z_V0 to Z_V15 will not be allocated by the register allocator, see s390.ad (reg class z_v_reg) + if (vs_reg->encoding() >= Z_V16->encoding() && + vs_reg->encoding() <= Z_V31->encoding()) { + reg_save_index += 2; + if (action == ACTION_SAVE) { + __ z_vst(vs_reg, Address(Z_SP, offset - reg_save_index * BytesPerWord)); + } else if (action == ACTION_RESTORE) { + __ z_vl(vs_reg, Address(Z_SP, offset - reg_save_index * BytesPerWord)); + } else { + assert(action == ACTION_COUNT_ONLY, "Sanity"); + } + } } else { fatal("Register type is not known"); } From 587f2b4b4dd73733a6ee247200371f8a8d0299c1 Mon Sep 17 00:00:00 2001 From: Hamlin Li Date: Wed, 20 Nov 2024 08:49:35 +0000 Subject: [PATCH 33/74] 8343827: RISC-V: set AlignVector as false if applicable to enable SLP Reviewed-by: fyang, luhenry --- src/hotspot/cpu/riscv/vm_version_riscv.cpp | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/hotspot/cpu/riscv/vm_version_riscv.cpp b/src/hotspot/cpu/riscv/vm_version_riscv.cpp index dddded795fa99..3b8d8119a8e1c 100644 --- a/src/hotspot/cpu/riscv/vm_version_riscv.cpp +++ b/src/hotspot/cpu/riscv/vm_version_riscv.cpp @@ -150,11 +150,12 @@ void VM_Version::common_initialize() { } if (FLAG_IS_DEFAULT(AvoidUnalignedAccesses)) { - if (unaligned_access.value() != MISALIGNED_FAST) { - FLAG_SET_DEFAULT(AvoidUnalignedAccesses, true); - } else { - FLAG_SET_DEFAULT(AvoidUnalignedAccesses, false); - } + FLAG_SET_DEFAULT(AvoidUnalignedAccesses, + unaligned_access.value() != MISALIGNED_FAST); + } + + if (FLAG_IS_DEFAULT(AlignVector)) { + FLAG_SET_DEFAULT(AlignVector, AvoidUnalignedAccesses); } // See JDK-8026049 From 5b12a87dcb47b5783f179534e2de43d5a920a489 Mon Sep 17 00:00:00 2001 From: Prasanta Sadhukhan Date: Wed, 20 Nov 2024 09:11:12 +0000 Subject: [PATCH 34/74] 8344060: Remove doPrivileged calls from shared implementation code in the java.desktop module : part 1 Reviewed-by: aivanov, prr --- .../share/classes/sun/awt/SunToolkit.java | 47 +++------ .../classes/sun/awt/image/ImageDecoder.java | 9 +- .../classes/sun/awt/image/ImageFetcher.java | 30 +++--- .../classes/sun/awt/image/ImageWatched.java | 36 +------ .../classes/sun/awt/image/ImagingLib.java | 24 ++--- .../sun/awt/image/JPEGImageDecoder.java | 10 +- .../sun/awt/image/NativeLibLoader.java | 10 +- .../sun/awt/image/VSyncedBSManager.java | 5 +- .../sun/awt/util/PerformanceLogger.java | 33 +++---- .../share/classes/sun/java2d/Disposer.java | 32 ++---- .../sun/java2d/SunGraphicsEnvironment.java | 10 +- .../classes/sun/java2d/SurfaceDataProxy.java | 11 +-- .../classes/sun/java2d/cmm/CMSManager.java | 11 +-- .../classes/sun/java2d/cmm/lcms/LCMS.java | 18 ++-- .../sun/java2d/loops/GraphicsPrimitive.java | 40 +++----- .../java2d/marlin/DMarlinRenderingEngine.java | 8 +- .../sun/java2d/marlin/MarlinProperties.java | 18 +--- .../sun/java2d/marlin/RendererStats.java | 30 +++--- .../sun/java2d/opengl/OGLRenderQueue.java | 5 +- .../sun/java2d/opengl/OGLSurfaceData.java | 20 +--- .../sun/java2d/pipe/RenderingEngine.java | 16 +-- .../share/classes/sun/print/PSPrinterJob.java | 97 ++++++------------- .../classes/sun/print/RasterPrinterJob.java | 61 ++---------- .../classes/sun/print/ServiceDialog.java | 39 ++------ .../classes/sun/swing/JLightweightFrame.java | 15 +-- .../classes/sun/swing/SwingUtilities2.java | 8 +- 26 files changed, 166 insertions(+), 477 deletions(-) diff --git a/src/java.desktop/share/classes/sun/awt/SunToolkit.java b/src/java.desktop/share/classes/sun/awt/SunToolkit.java index 5c4ebda8715d7..1dc6c2f392045 100644 --- a/src/java.desktop/share/classes/sun/awt/SunToolkit.java +++ b/src/java.desktop/share/classes/sun/awt/SunToolkit.java @@ -79,7 +79,6 @@ import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.net.URL; -import java.security.AccessController; import java.util.ArrayList; import java.util.Collections; import java.util.Locale; @@ -100,8 +99,6 @@ import sun.awt.image.URLImageSource; import sun.font.FontDesignMetrics; import sun.net.util.URLUtil; -import sun.security.action.GetBooleanAction; -import sun.security.action.GetPropertyAction; import sun.util.logging.PlatformLogger; import static java.awt.RenderingHints.KEY_TEXT_ANTIALIASING; @@ -122,14 +119,12 @@ public abstract class SunToolkit extends Toolkit initStatic(); } - @SuppressWarnings("removal") private static void initStatic() { - if (AccessController.doPrivileged(new GetBooleanAction("sun.awt.nativedebug"))) { + if (Boolean.getBoolean("sun.awt.nativedebug")) { DebugSettings.init(); } touchKeyboardAutoShowIsEnabled = Boolean.parseBoolean( - GetPropertyAction.privilegedGetProperty( - "awt.touchKeyboardAutoShowIsEnabled", "true")); + System.getProperty("awt.touchKeyboardAutoShowIsEnabled", "true")); } /** @@ -231,9 +226,8 @@ public abstract KeyboardFocusManagerPeer getKeyboardFocusManagerPeer() * } */ - @SuppressWarnings("removal") private static final ReentrantLock AWT_LOCK = new ReentrantLock( - AccessController.doPrivileged(new GetBooleanAction("awt.lock.fair"))); + Boolean.getBoolean("awt.lock.fair")); private static final Condition AWT_LOCK_COND = AWT_LOCK.newCondition(); public static final void awtLock() { @@ -672,18 +666,16 @@ private void disableBackgroundEraseImpl(Component component) { * Returns the value of "sun.awt.noerasebackground" property. Default * value is {@code false}. */ - @SuppressWarnings("removal") public static boolean getSunAwtNoerasebackground() { - return AccessController.doPrivileged(new GetBooleanAction("sun.awt.noerasebackground")); + return Boolean.getBoolean("sun.awt.noerasebackground"); } /** * Returns the value of "sun.awt.erasebackgroundonresize" property. Default * value is {@code false}. */ - @SuppressWarnings("removal") public static boolean getSunAwtErasebackgroundonresize() { - return AccessController.doPrivileged(new GetBooleanAction("sun.awt.erasebackgroundonresize")); + return Boolean.getBoolean("sun.awt.erasebackgroundonresize"); } @@ -1157,15 +1149,12 @@ public boolean enableInputMethodsForTextComponent() { /** * Returns the locale in which the runtime was started. */ - @SuppressWarnings("removal") public static Locale getStartupLocale() { if (startupLocale == null) { String language, region, country, variant; - language = AccessController.doPrivileged( - new GetPropertyAction("user.language", "en")); + language = System.getProperty("user.language", "en"); // for compatibility, check for old user.region property - region = AccessController.doPrivileged( - new GetPropertyAction("user.region")); + region = System.getProperty("user.region"); if (region != null) { // region can be of form country, country_variant, or _variant int i = region.indexOf('_'); @@ -1177,10 +1166,8 @@ public static Locale getStartupLocale() { variant = ""; } } else { - country = AccessController.doPrivileged( - new GetPropertyAction("user.country", "")); - variant = AccessController.doPrivileged( - new GetPropertyAction("user.variant", "")); + country = System.getProperty("user.country", ""); + variant = System.getProperty("user.variant", ""); } startupLocale = Locale.of(language, country, variant); } @@ -1201,9 +1188,7 @@ public Locale getDefaultKeyboardLocale() { * @return {@code true}, if XEmbed is needed, {@code false} otherwise */ public static boolean needsXEmbed() { - @SuppressWarnings("removal") - String noxembed = AccessController. - doPrivileged(new GetPropertyAction("sun.awt.noxembed", "false")); + String noxembed = System.getProperty("sun.awt.noxembed", "false"); if ("true".equals(noxembed)) { return false; } @@ -1235,9 +1220,8 @@ protected boolean needsXEmbedImpl() { * developer. If true, Toolkit should return an * XEmbed-server-enabled CanvasPeer instead of the ordinary CanvasPeer. */ - @SuppressWarnings("removal") protected final boolean isXEmbedServerRequested() { - return AccessController.doPrivileged(new GetBooleanAction("sun.awt.xembedserver")); + return Boolean.getBoolean("sun.awt.xembedserver"); } /** @@ -1756,16 +1740,13 @@ private static RenderingHints getDesktopAAHintsByName(String hintname) { * to be inapplicable in that case. In that headless case although * this method will return "true" the toolkit will return a null map. */ - @SuppressWarnings("removal") private static boolean useSystemAAFontSettings() { if (!checkedSystemAAFontSettings) { useSystemAAFontSettings = true; /* initially set this true */ String systemAAFonts = null; Toolkit tk = Toolkit.getDefaultToolkit(); if (tk instanceof SunToolkit) { - systemAAFonts = - AccessController.doPrivileged( - new GetPropertyAction("awt.useSystemAAFontSettings")); + systemAAFonts = System.getProperty("awt.useSystemAAFontSettings"); } if (systemAAFonts != null) { useSystemAAFontSettings = Boolean.parseBoolean(systemAAFonts); @@ -1859,11 +1840,9 @@ public static Window getContainingWindow(Component comp) { * Returns the value of "sun.awt.disableMixing" property. Default * value is {@code false}. */ - @SuppressWarnings("removal") public static synchronized boolean getSunAwtDisableMixing() { if (sunAwtDisableMixing == null) { - sunAwtDisableMixing = AccessController.doPrivileged( - new GetBooleanAction("sun.awt.disableMixing")); + sunAwtDisableMixing = Boolean.getBoolean("sun.awt.disableMixing"); } return sunAwtDisableMixing.booleanValue(); } diff --git a/src/java.desktop/share/classes/sun/awt/image/ImageDecoder.java b/src/java.desktop/share/classes/sun/awt/image/ImageDecoder.java index d09cfd9b2d88d..c3691773f6ea0 100644 --- a/src/java.desktop/share/classes/sun/awt/image/ImageDecoder.java +++ b/src/java.desktop/share/classes/sun/awt/image/ImageDecoder.java @@ -159,18 +159,11 @@ protected int imageComplete(int status, boolean done) { public abstract void produceImage() throws IOException, ImageFormatException; - @SuppressWarnings("removal") public void abort() { aborted = true; source.doneDecoding(this); close(); - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Object run() { - feeder.interrupt(); - return null; - } - }); + feeder.interrupt(); } public synchronized void close() { diff --git a/src/java.desktop/share/classes/sun/awt/image/ImageFetcher.java b/src/java.desktop/share/classes/sun/awt/image/ImageFetcher.java index e527dbfcb3ff8..88e830a2bf554 100644 --- a/src/java.desktop/share/classes/sun/awt/image/ImageFetcher.java +++ b/src/java.desktop/share/classes/sun/awt/image/ImageFetcher.java @@ -276,7 +276,6 @@ private static void stoppingAnimation(Thread me) { /** * Create and start ImageFetcher threads in the appropriate ThreadGroup. */ - @SuppressWarnings("removal") private static void createFetchers(final FetcherInfo info) { // We need to instantiate a new ImageFetcher thread. // First, figure out which ThreadGroup we'll put the @@ -310,25 +309,18 @@ private static void createFetchers(final FetcherInfo info) { } final ThreadGroup fetcherGroup = fetcherThreadGroup; - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Object run() { - for (int i = 0; i < info.fetchers.length; i++) { - if (info.fetchers[i] == null) { - ImageFetcher f = new ImageFetcher(fetcherGroup, i); - try { - f.start(); - info.fetchers[i] = f; - info.numFetchers++; - break; - } catch (Error e) { - } - } - } - return null; + for (int i = 0; i < info.fetchers.length; i++) { + if (info.fetchers[i] == null) { + ImageFetcher f = new ImageFetcher(fetcherGroup, i); + try { + f.start(); + info.fetchers[i] = f; + info.numFetchers++; + break; + } catch (Error e) { } - }); - return; + } + } } } diff --git a/src/java.desktop/share/classes/sun/awt/image/ImageWatched.java b/src/java.desktop/share/classes/sun/awt/image/ImageWatched.java index 0a1dd47fb550d..c3198ac704b70 100644 --- a/src/java.desktop/share/classes/sun/awt/image/ImageWatched.java +++ b/src/java.desktop/share/classes/sun/awt/image/ImageWatched.java @@ -29,10 +29,6 @@ import java.awt.Image; import java.awt.image.ImageObserver; -import java.security.AccessControlContext; -import java.security.AccessController; -import java.security.PrivilegedAction; - public abstract class ImageWatched { public static Link endlink = new Link(); @@ -89,28 +85,16 @@ public boolean newInfo(Image img, int info, } } - static class AccWeakReference extends WeakReference { - - @SuppressWarnings("removal") - private final AccessControlContext acc; - - @SuppressWarnings("removal") - AccWeakReference(T ref) { - super(ref); - acc = AccessController.getContext(); - } - } - /* * Standard Link implementation to manage a Weak Reference * to an ImageObserver. */ public static class WeakLink extends Link { - private final AccWeakReference myref; + private final WeakReference myref; private Link next; public WeakLink(ImageObserver obs, Link next) { - myref = new AccWeakReference(obs); + myref = new WeakReference(obs); this.next = next; } @@ -136,20 +120,6 @@ public Link removeWatcher(ImageObserver iw) { return this; } - @SuppressWarnings("removal") - private static boolean update(ImageObserver iw, AccessControlContext acc, - Image img, int info, - int x, int y, int w, int h) { - - if (acc != null || System.getSecurityManager() != null) { - return AccessController.doPrivileged( - (PrivilegedAction) () -> { - return iw.imageUpdate(img, info, x, y, w, h); - }, acc); - } - return false; - } - public boolean newInfo(Image img, int info, int x, int y, int w, int h) { @@ -159,7 +129,7 @@ public boolean newInfo(Image img, int info, if (myiw == null) { // My referent is null so we must prune in a second pass. ret = true; - } else if (update(myiw, myref.acc, img, info, x, y, w, h) == false) { + } else if (myiw.imageUpdate(img, info, x, y, w, h) == false) { // My referent has lost interest so clear it and ask // for a pruning pass to remove it later. myref.clear(); diff --git a/src/java.desktop/share/classes/sun/awt/image/ImagingLib.java b/src/java.desktop/share/classes/sun/awt/image/ImagingLib.java index a98e6fc81fbad..d37afcb7a8b65 100644 --- a/src/java.desktop/share/classes/sun/awt/image/ImagingLib.java +++ b/src/java.desktop/share/classes/sun/awt/image/ImagingLib.java @@ -37,8 +37,6 @@ import java.awt.image.RasterOp; import java.awt.image.Raster; import java.awt.image.WritableRaster; -import java.security.AccessController; -import java.security.PrivilegedAction; /** * This class provides a hook to access platform-specific @@ -51,7 +49,7 @@ * (in which case our java code will be executed) or may throw * an exception. */ -@SuppressWarnings({"removal", "restricted"}) +@SuppressWarnings("restricted") public class ImagingLib { static boolean useLib = true; @@ -90,20 +88,14 @@ public static native int lookupByteRaster(Raster src, Raster dst, static { - PrivilegedAction doMlibInitialization = - new PrivilegedAction() { - public Boolean run() { - try { - System.loadLibrary("mlib_image"); - } catch (UnsatisfiedLinkError e) { - return Boolean.FALSE; - } - boolean success = init(); - return Boolean.valueOf(success); - } - }; + boolean success = false; + try { + System.loadLibrary("mlib_image"); + success = init(); + } catch (UnsatisfiedLinkError e) { + } - useLib = AccessController.doPrivileged(doMlibInitialization); + useLib = success; // // Cache the class references of the operations we know about diff --git a/src/java.desktop/share/classes/sun/awt/image/JPEGImageDecoder.java b/src/java.desktop/share/classes/sun/awt/image/JPEGImageDecoder.java index b976a716deda8..eb1023bd69434 100644 --- a/src/java.desktop/share/classes/sun/awt/image/JPEGImageDecoder.java +++ b/src/java.desktop/share/classes/sun/awt/image/JPEGImageDecoder.java @@ -42,7 +42,7 @@ * * @author Jim Graham */ -@SuppressWarnings({"removal", "restricted"}) +@SuppressWarnings("restricted") public class JPEGImageDecoder extends ImageDecoder { private static ColorModel RGBcolormodel; private static ColorModel ARGBcolormodel; @@ -54,13 +54,7 @@ public class JPEGImageDecoder extends ImageDecoder { private ColorModel colormodel; static { - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Void run() { - System.loadLibrary("javajpeg"); - return null; - } - }); + System.loadLibrary("javajpeg"); initIDs(InputStreamClass); RGBcolormodel = new DirectColorModel(24, 0xff0000, 0xff00, 0xff); ARGBcolormodel = ColorModel.getRGBdefault(); diff --git a/src/java.desktop/share/classes/sun/awt/image/NativeLibLoader.java b/src/java.desktop/share/classes/sun/awt/image/NativeLibLoader.java index e1fe5658e6377..d971bf6e40d4e 100644 --- a/src/java.desktop/share/classes/sun/awt/image/NativeLibLoader.java +++ b/src/java.desktop/share/classes/sun/awt/image/NativeLibLoader.java @@ -52,14 +52,8 @@ class NativeLibLoader { * For now, we know it's done by the implementation, and we assume * that the name of the library is "awt". -br. */ - @SuppressWarnings({"removal", "restricted"}) + @SuppressWarnings("restricted") static void loadLibraries() { - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Void run() { - System.loadLibrary("awt"); - return null; - } - }); + System.loadLibrary("awt"); } } diff --git a/src/java.desktop/share/classes/sun/awt/image/VSyncedBSManager.java b/src/java.desktop/share/classes/sun/awt/image/VSyncedBSManager.java index 8bb34dd627979..88403ca06a31c 100644 --- a/src/java.desktop/share/classes/sun/awt/image/VSyncedBSManager.java +++ b/src/java.desktop/share/classes/sun/awt/image/VSyncedBSManager.java @@ -35,11 +35,8 @@ public abstract class VSyncedBSManager { private static VSyncedBSManager theInstance; - @SuppressWarnings("removal") private static final boolean vSyncLimit = - Boolean.parseBoolean(java.security.AccessController.doPrivileged( - new sun.security.action.GetPropertyAction( - "sun.java2d.vsynclimit", "true"))); + Boolean.parseBoolean(System.getProperty("sun.java2d.vsynclimit", "true")); private static VSyncedBSManager getInstance(boolean create) { if (theInstance == null && create) { diff --git a/src/java.desktop/share/classes/sun/awt/util/PerformanceLogger.java b/src/java.desktop/share/classes/sun/awt/util/PerformanceLogger.java index fa4a1450bb419..303b57626d6f6 100644 --- a/src/java.desktop/share/classes/sun/awt/util/PerformanceLogger.java +++ b/src/java.desktop/share/classes/sun/awt/util/PerformanceLogger.java @@ -72,7 +72,6 @@ * exist once those APIs are in place. * @author Chet Haase */ -@SuppressWarnings("removal") public class PerformanceLogger { // Timing values of global interest @@ -87,16 +86,12 @@ public class PerformanceLogger { private static long baseTime; static { - String perfLoggingProp = - java.security.AccessController.doPrivileged( - new sun.security.action.GetPropertyAction("sun.perflog")); + String perfLoggingProp = System.getProperty("sun.perflog"); if (perfLoggingProp != null) { perfLoggingOn = true; // Check if we should use nanoTime - String perfNanoProp = - java.security.AccessController.doPrivileged( - new sun.security.action.GetPropertyAction("sun.perflog.nano")); + String perfNanoProp = System.getProperty("sun.perflog.nano"); if (perfNanoProp != null) { useNanoTime = true; } @@ -107,21 +102,15 @@ public class PerformanceLogger { } if (logFileName != null) { if (logWriter == null) { - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Void run() { - try { - File logFile = new File(logFileName); - logFile.createNewFile(); - logWriter = new FileWriter(logFile); - } catch (Exception e) { - System.out.println(e + ": Creating logfile " + - logFileName + - ". Log to console"); - } - return null; - } - }); + try { + File logFile = new File(logFileName); + logFile.createNewFile(); + logWriter = new FileWriter(logFile); + } catch (Exception e) { + System.out.println(e + ": Creating logfile " + + logFileName + + ". Log to console"); + } } } if (logWriter == null) { diff --git a/src/java.desktop/share/classes/sun/java2d/Disposer.java b/src/java.desktop/share/classes/sun/java2d/Disposer.java index 5692b490278d2..9929238c09928 100644 --- a/src/java.desktop/share/classes/sun/java2d/Disposer.java +++ b/src/java.desktop/share/classes/sun/java2d/Disposer.java @@ -31,8 +31,6 @@ import java.lang.ref.ReferenceQueue; import java.lang.ref.PhantomReference; import java.lang.ref.WeakReference; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.Hashtable; import java.util.concurrent.ConcurrentLinkedDeque; @@ -50,7 +48,7 @@ * * @see DisposerRecord */ -@SuppressWarnings({"removal", "restricted"}) +@SuppressWarnings("restricted") public class Disposer implements Runnable { private static final ReferenceQueue queue = new ReferenceQueue<>(); private static final Hashtable, DisposerRecord> records = @@ -62,16 +60,9 @@ public class Disposer implements Runnable { public static int refType = PHANTOM; static { - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Void run() { - System.loadLibrary("awt"); - return null; - } - }); + System.loadLibrary("awt"); initIDs(); - String type = java.security.AccessController.doPrivileged( - new sun.security.action.GetPropertyAction("sun.java2d.reftype")); + String type = System.getProperty("sun.java2d.reftype"); if (type != null) { if (type.equals("weak")) { refType = WEAK; @@ -82,16 +73,13 @@ public Void run() { } } disposerInstance = new Disposer(); - AccessController.doPrivileged((PrivilegedAction) () -> { - String name = "Java2D Disposer"; - ThreadGroup rootTG = ThreadGroupUtils.getRootThreadGroup(); - Thread t = new Thread(rootTG, disposerInstance, name, 0, false); - t.setContextClassLoader(null); - t.setDaemon(true); - t.setPriority(Thread.MAX_PRIORITY); - t.start(); - return null; - }); + String name = "Java2D Disposer"; + ThreadGroup rootTG = ThreadGroupUtils.getRootThreadGroup(); + Thread t = new Thread(rootTG, disposerInstance, name, 0, false); + t.setContextClassLoader(null); + t.setDaemon(true); + t.setPriority(Thread.MAX_PRIORITY); + t.start(); } /** diff --git a/src/java.desktop/share/classes/sun/java2d/SunGraphicsEnvironment.java b/src/java.desktop/share/classes/sun/java2d/SunGraphicsEnvironment.java index 4335b1c9fbff4..5cd8f11ecdb64 100644 --- a/src/java.desktop/share/classes/sun/java2d/SunGraphicsEnvironment.java +++ b/src/java.desktop/share/classes/sun/java2d/SunGraphicsEnvironment.java @@ -40,7 +40,6 @@ import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.awt.peer.ComponentPeer; -import java.security.AccessController; import java.util.Locale; import java.util.TreeMap; @@ -50,7 +49,6 @@ import sun.font.FontManagerFactory; import sun.font.FontManagerForSGE; import sun.java2d.pipe.Region; -import sun.security.action.GetPropertyAction; /** * This is an implementation of a GraphicsEnvironment object for the @@ -65,10 +63,8 @@ public abstract class SunGraphicsEnvironment extends GraphicsEnvironment /** Establish the default font to be used by SG2D. */ private final Font defaultFont = new Font(Font.DIALOG, Font.PLAIN, 12); - @SuppressWarnings("removal") private static final boolean uiScaleEnabled - = "true".equals(AccessController.doPrivileged( - new GetPropertyAction("sun.java2d.uiScale.enabled", "true"))); + = "true".equals(System.getProperty("sun.java2d.uiScale.enabled", "true")); private static final double debugScale = uiScaleEnabled ? getScaleFactor("sun.java2d.uiScale") : -1; @@ -293,9 +289,7 @@ public static double getDebugScale() { public static double getScaleFactor(String propertyName) { - @SuppressWarnings("removal") - String scaleFactor = AccessController.doPrivileged( - new GetPropertyAction(propertyName, "-1")); + String scaleFactor = System.getProperty(propertyName, "-1"); if (scaleFactor == null || scaleFactor.equals("-1")) { return -1; diff --git a/src/java.desktop/share/classes/sun/java2d/SurfaceDataProxy.java b/src/java.desktop/share/classes/sun/java2d/SurfaceDataProxy.java index 4c1e8256552ea..ba4d6caf44c0a 100644 --- a/src/java.desktop/share/classes/sun/java2d/SurfaceDataProxy.java +++ b/src/java.desktop/share/classes/sun/java2d/SurfaceDataProxy.java @@ -38,9 +38,6 @@ import sun.java2d.loops.BlitBg; import sun.awt.image.SurfaceManager; -import java.security.AccessController; -import sun.security.action.GetPropertyAction; - /** * The proxy class encapsulates the logic for managing alternate * SurfaceData representations of a primary SurfaceData. @@ -70,18 +67,14 @@ public abstract class SurfaceDataProxy static { cachingAllowed = true; - @SuppressWarnings("removal") - String manimg = AccessController.doPrivileged( - new GetPropertyAction("sun.java2d.managedimages")); + String manimg = System.getProperty("sun.java2d.managedimages"); if ("false".equals(manimg)) { cachingAllowed = false; System.out.println("Disabling managed images"); } defaultThreshold = 1; - @SuppressWarnings("removal") - String num = AccessController.doPrivileged( - new GetPropertyAction("sun.java2d.accthreshold")); + String num = System.getProperty("sun.java2d.accthreshold"); if (num != null) { try { int parsed = Integer.parseInt(num); diff --git a/src/java.desktop/share/classes/sun/java2d/cmm/CMSManager.java b/src/java.desktop/share/classes/sun/java2d/cmm/CMSManager.java index 99e167ba67250..8aba105661612 100644 --- a/src/java.desktop/share/classes/sun/java2d/cmm/CMSManager.java +++ b/src/java.desktop/share/classes/sun/java2d/cmm/CMSManager.java @@ -27,9 +27,6 @@ import java.awt.color.CMMException; import java.awt.color.ICC_Profile; -import java.security.AccessController; - -import sun.security.action.GetPropertyAction; public final class CMSManager { @@ -45,9 +42,7 @@ private static synchronized PCMM createModule() { return cmmImpl; } - GetPropertyAction gpa = new GetPropertyAction("sun.java2d.cmm"); - @SuppressWarnings("removal") - String cmmProviderClass = AccessController.doPrivileged(gpa); + String cmmProviderClass = System.getProperty("sun.java2d.cmm"); CMMServiceProvider provider = null; if (cmmProviderClass != null) { try { @@ -67,9 +62,7 @@ private static synchronized PCMM createModule() { "No CM module found"); } - gpa = new GetPropertyAction("sun.java2d.cmm.trace"); - @SuppressWarnings("removal") - String cmmTrace = AccessController.doPrivileged(gpa); + String cmmTrace = System.getProperty("sun.java2d.cmm.trace"); if (cmmTrace != null) { cmmImpl = new CMMTracer(cmmImpl); } diff --git a/src/java.desktop/share/classes/sun/java2d/cmm/lcms/LCMS.java b/src/java.desktop/share/classes/sun/java2d/cmm/lcms/LCMS.java index 2fe86b3500cf9..3a7db37329eee 100644 --- a/src/java.desktop/share/classes/sun/java2d/cmm/lcms/LCMS.java +++ b/src/java.desktop/share/classes/sun/java2d/cmm/lcms/LCMS.java @@ -143,23 +143,17 @@ private LCMS() {} private static LCMS theLcms = null; - @SuppressWarnings({"removal", "restricted"}) + @SuppressWarnings("restricted") static synchronized PCMM getModule() { if (theLcms != null) { return theLcms; } - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Object run() { - /* We need to load awt here because of usage trace and - * disposer frameworks - */ - System.loadLibrary("awt"); - System.loadLibrary("lcms"); - return null; - } - }); + /* We need to load awt here because of usage trace and + * disposer frameworks + */ + System.loadLibrary("awt"); + System.loadLibrary("lcms"); theLcms = new LCMS(); diff --git a/src/java.desktop/share/classes/sun/java2d/loops/GraphicsPrimitive.java b/src/java.desktop/share/classes/sun/java2d/loops/GraphicsPrimitive.java index ade97ee007fe7..8fd97626f040a 100644 --- a/src/java.desktop/share/classes/sun/java2d/loops/GraphicsPrimitive.java +++ b/src/java.desktop/share/classes/sun/java2d/loops/GraphicsPrimitive.java @@ -36,8 +36,6 @@ import java.io.FileOutputStream; import java.io.PrintStream; import java.lang.reflect.Field; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; @@ -46,7 +44,6 @@ import sun.awt.util.ThreadGroupUtils; import sun.java2d.SurfaceData; import sun.java2d.pipe.Region; -import sun.security.action.GetPropertyAction; /** * defines interface for primitives which can be placed into @@ -336,9 +333,7 @@ protected GraphicsPrimitive makePrimitive(SurfaceType srctype, public static final int TRACECOUNTS = 4; static { - GetPropertyAction gpa = new GetPropertyAction("sun.java2d.trace"); - @SuppressWarnings("removal") - String trace = AccessController.doPrivileged(gpa); + String trace = System.getProperty("sun.java2d.trace"); if (trace != null) { boolean verbose = false; int traceflags = 0; @@ -401,17 +396,12 @@ public static boolean tracingEnabled() { private static PrintStream getTraceOutputFile() { if (traceout == null) { if (tracefile != null) { - @SuppressWarnings("removal") - FileOutputStream o = AccessController.doPrivileged( - new PrivilegedAction() { - public FileOutputStream run() { - try { - return new FileOutputStream(tracefile); - } catch (FileNotFoundException e) { - return null; - } - } - }); + FileOutputStream o; + try { + o = new FileOutputStream(tracefile); + } catch (FileNotFoundException e) { + o = null; + } if (o != null) { traceout = new PrintStream(o); } else { @@ -425,17 +415,13 @@ public FileOutputStream run() { } public static class TraceReporter implements Runnable { - @SuppressWarnings("removal") public static void setShutdownHook() { - AccessController.doPrivileged((PrivilegedAction) () -> { - TraceReporter t = new TraceReporter(); - Thread thread = new Thread( - ThreadGroupUtils.getRootThreadGroup(), t, - "TraceReporter", 0, false); - thread.setContextClassLoader(null); - Runtime.getRuntime().addShutdownHook(thread); - return null; - }); + TraceReporter t = new TraceReporter(); + Thread thread = new Thread( + ThreadGroupUtils.getRootThreadGroup(), t, + "TraceReporter", 0, false); + thread.setContextClassLoader(null); + Runtime.getRuntime().addShutdownHook(thread); } public void run() { diff --git a/src/java.desktop/share/classes/sun/java2d/marlin/DMarlinRenderingEngine.java b/src/java.desktop/share/classes/sun/java2d/marlin/DMarlinRenderingEngine.java index b29cc84c12778..66eb9334e8630 100644 --- a/src/java.desktop/share/classes/sun/java2d/marlin/DMarlinRenderingEngine.java +++ b/src/java.desktop/share/classes/sun/java2d/marlin/DMarlinRenderingEngine.java @@ -30,7 +30,6 @@ import java.awt.geom.AffineTransform; import java.awt.geom.Path2D; import java.awt.geom.PathIterator; -import java.security.AccessController; import java.util.Arrays; import sun.awt.geom.PathConsumer2D; import static sun.java2d.marlin.MarlinUtils.logInfo; @@ -40,7 +39,6 @@ import sun.java2d.pipe.AATileGenerator; import sun.java2d.pipe.Region; import sun.java2d.pipe.RenderingEngine; -import sun.security.action.GetPropertyAction; /** * Marlin RendererEngine implementation (derived from Pisces) @@ -1119,10 +1117,8 @@ public float getMinimumAAPenSize() { USE_THREAD_LOCAL = MarlinProperties.isUseThreadLocal(); // Soft reference by default: - @SuppressWarnings("removal") - final String refType = AccessController.doPrivileged( - new GetPropertyAction("sun.java2d.renderer.useRef", - "soft")); + final String refType = System.getProperty("sun.java2d.renderer.useRef", + "soft"); switch (refType) { default: case "soft": diff --git a/src/java.desktop/share/classes/sun/java2d/marlin/MarlinProperties.java b/src/java.desktop/share/classes/sun/java2d/marlin/MarlinProperties.java index ef919eba4009f..65122cae2a3d0 100644 --- a/src/java.desktop/share/classes/sun/java2d/marlin/MarlinProperties.java +++ b/src/java.desktop/share/classes/sun/java2d/marlin/MarlinProperties.java @@ -25,9 +25,7 @@ package sun.java2d.marlin; -import java.security.AccessController; import static sun.java2d.marlin.MarlinUtils.logInfo; -import sun.security.action.GetPropertyAction; public final class MarlinProperties { @@ -288,24 +286,18 @@ public static float getQuadDecD2() { } // system property utilities - @SuppressWarnings("removal") static String getString(final String key, final String def) { - return AccessController.doPrivileged( - new GetPropertyAction(key, def)); + return System.getProperty(key, def); } - @SuppressWarnings("removal") static boolean getBoolean(final String key, final String def) { - return Boolean.parseBoolean(AccessController.doPrivileged( - new GetPropertyAction(key, def))); + return Boolean.parseBoolean(System.getProperty(key, def)); } static int getInteger(final String key, final int def, final int min, final int max) { - @SuppressWarnings("removal") - final String property = AccessController.doPrivileged( - new GetPropertyAction(key)); + final String property = System.getProperty(key); int value = def; if (property != null) { @@ -334,9 +326,7 @@ public static double getDouble(final String key, final double def, final double min, final double max) { double value = def; - @SuppressWarnings("removal") - final String property = AccessController.doPrivileged( - new GetPropertyAction(key)); + final String property = System.getProperty(key); if (property != null) { try { diff --git a/src/java.desktop/share/classes/sun/java2d/marlin/RendererStats.java b/src/java.desktop/share/classes/sun/java2d/marlin/RendererStats.java index 5517ce93f9948..131f63afa65b3 100644 --- a/src/java.desktop/share/classes/sun/java2d/marlin/RendererStats.java +++ b/src/java.desktop/share/classes/sun/java2d/marlin/RendererStats.java @@ -25,8 +25,6 @@ package sun.java2d.marlin; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentLinkedQueue; @@ -357,11 +355,8 @@ static void dumpStats() { private final ConcurrentLinkedQueue allStats = new ConcurrentLinkedQueue<>(); - @SuppressWarnings("removal") private RendererStatsHolder() { - AccessController.doPrivileged( - (PrivilegedAction) () -> { - final Thread hook = new Thread( + final Thread hook = new Thread( MarlinUtils.getRootThreadGroup(), new Runnable() { @Override @@ -371,21 +366,18 @@ public void run() { }, "MarlinStatsHook" ); - hook.setContextClassLoader(null); - Runtime.getRuntime().addShutdownHook(hook); + hook.setContextClassLoader(null); + Runtime.getRuntime().addShutdownHook(hook); - if (USE_DUMP_THREAD) { - final Timer statTimer = new Timer("RendererStats"); - statTimer.scheduleAtFixedRate(new TimerTask() { - @Override - public void run() { - dump(); - } - }, DUMP_INTERVAL, DUMP_INTERVAL); + if (USE_DUMP_THREAD) { + final Timer statTimer = new Timer("RendererStats"); + statTimer.scheduleAtFixedRate(new TimerTask() { + @Override + public void run() { + dump(); } - return null; - } - ); + }, DUMP_INTERVAL, DUMP_INTERVAL); + } } void add(final Object parent, final RendererStats stats) { diff --git a/src/java.desktop/share/classes/sun/java2d/opengl/OGLRenderQueue.java b/src/java.desktop/share/classes/sun/java2d/opengl/OGLRenderQueue.java index 4b89aca5c85d6..8427bcd1a4f4f 100644 --- a/src/java.desktop/share/classes/sun/java2d/opengl/OGLRenderQueue.java +++ b/src/java.desktop/share/classes/sun/java2d/opengl/OGLRenderQueue.java @@ -30,8 +30,6 @@ import sun.java2d.pipe.RenderQueue; import static sun.java2d.pipe.BufferedOpCodes.*; -import java.security.AccessController; -import java.security.PrivilegedAction; /** * OGL-specific implementation of RenderQueue. This class provides a @@ -44,13 +42,12 @@ public class OGLRenderQueue extends RenderQueue { private static OGLRenderQueue theInstance; private final QueueFlusher flusher; - @SuppressWarnings("removal") private OGLRenderQueue() { /* * The thread must be a member of a thread group * which will not get GCed before VM exit. */ - flusher = AccessController.doPrivileged((PrivilegedAction) QueueFlusher::new); + flusher = new QueueFlusher(); } /** diff --git a/src/java.desktop/share/classes/sun/java2d/opengl/OGLSurfaceData.java b/src/java.desktop/share/classes/sun/java2d/opengl/OGLSurfaceData.java index 2f27515c20410..501399c35a938 100644 --- a/src/java.desktop/share/classes/sun/java2d/opengl/OGLSurfaceData.java +++ b/src/java.desktop/share/classes/sun/java2d/opengl/OGLSurfaceData.java @@ -178,31 +178,19 @@ protected native boolean initFBObject(long pData, static { if (!GraphicsEnvironment.isHeadless()) { // fbobject currently enabled by default; use "false" to disable - @SuppressWarnings("removal") - String fbo = java.security.AccessController.doPrivileged( - new sun.security.action.GetPropertyAction( - "sun.java2d.opengl.fbobject")); + String fbo = System.getProperty("sun.java2d.opengl.fbobject"); isFBObjectEnabled = !"false".equals(fbo); // lcdshader currently enabled by default; use "false" to disable - @SuppressWarnings("removal") - String lcd = java.security.AccessController.doPrivileged( - new sun.security.action.GetPropertyAction( - "sun.java2d.opengl.lcdshader")); + String lcd = System.getProperty("sun.java2d.opengl.lcdshader"); isLCDShaderEnabled = !"false".equals(lcd); // biopshader currently enabled by default; use "false" to disable - @SuppressWarnings("removal") - String biop = java.security.AccessController.doPrivileged( - new sun.security.action.GetPropertyAction( - "sun.java2d.opengl.biopshader")); + String biop = System.getProperty("sun.java2d.opengl.biopshader"); isBIOpShaderEnabled = !"false".equals(biop); // gradshader currently enabled by default; use "false" to disable - @SuppressWarnings("removal") - String grad = java.security.AccessController.doPrivileged( - new sun.security.action.GetPropertyAction( - "sun.java2d.opengl.gradshader")); + String grad = System.getProperty("sun.java2d.opengl.gradshader"); isGradShaderEnabled = !"false".equals(grad); OGLRenderQueue rq = OGLRenderQueue.getInstance(); diff --git a/src/java.desktop/share/classes/sun/java2d/pipe/RenderingEngine.java b/src/java.desktop/share/classes/sun/java2d/pipe/RenderingEngine.java index e33eabd06b3c0..e6a5be7ca3b53 100644 --- a/src/java.desktop/share/classes/sun/java2d/pipe/RenderingEngine.java +++ b/src/java.desktop/share/classes/sun/java2d/pipe/RenderingEngine.java @@ -30,9 +30,6 @@ import java.awt.geom.PathIterator; import java.awt.geom.AffineTransform; -import java.security.AccessController; -import sun.security.action.GetPropertyAction; - import sun.awt.geom.PathConsumer2D; /** @@ -120,10 +117,7 @@ public static synchronized RenderingEngine getInstance() { /* Look first for an app-override renderer, * if not specified or present, then look for marlin. */ - GetPropertyAction gpa = - new GetPropertyAction("sun.java2d.renderer"); - @SuppressWarnings("removal") - String reClass = AccessController.doPrivileged(gpa); + String reClass = System.getProperty("sun.java2d.renderer"); if (reClass != null) { try { Class cls = Class.forName(reClass); @@ -144,16 +138,12 @@ public static synchronized RenderingEngine getInstance() { throw new InternalError("No RenderingEngine module found"); } - gpa = new GetPropertyAction("sun.java2d.renderer.verbose"); - @SuppressWarnings("removal") - String verbose = AccessController.doPrivileged(gpa); + String verbose = System.getProperty("sun.java2d.renderer.verbose"); if (verbose != null && verbose.startsWith("t")) { System.out.println("RenderingEngine = "+reImpl); } - gpa = new GetPropertyAction("sun.java2d.renderer.trace"); - @SuppressWarnings("removal") - String reTrace = AccessController.doPrivileged(gpa); + String reTrace = System.getProperty("sun.java2d.renderer.trace"); if (reTrace != null) { reImpl = new Tracer(reImpl); } diff --git a/src/java.desktop/share/classes/sun/print/PSPrinterJob.java b/src/java.desktop/share/classes/sun/print/PSPrinterJob.java index e64fb2cb0d501..a0f68a713aa5a 100644 --- a/src/java.desktop/share/classes/sun/print/PSPrinterJob.java +++ b/src/java.desktop/share/classes/sun/print/PSPrinterJob.java @@ -338,18 +338,9 @@ public class PSPrinterJob extends RasterPrinterJob { initStatic(); } - @SuppressWarnings("removal") private static void initStatic() { - //enable privileges so initProps can access system properties, - // open the property file, etc. - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Object run() { - mFontProps = initProps(); - isMac = OSInfo.getOSType() == OSInfo.OSType.MACOSX; - return null; - } - }); + mFontProps = initProps(); + isMac = OSInfo.getOSType() == OSInfo.OSType.MACOSX; } /* @@ -512,7 +503,6 @@ protected void setAttributes(PrintRequestAttributeSet attributes) * this method is called to mark the start of a * document. */ - @SuppressWarnings("removal") protected void startDoc() throws PrinterException { // A security check has been performed in the @@ -551,7 +541,7 @@ protected void startDoc() throws PrinterException { } } else { PrinterOpener po = new PrinterOpener(); - java.security.AccessController.doPrivileged(po); + po.run(); if (po.pex != null) { throw po.pex; } @@ -641,22 +631,16 @@ protected void startDoc() throws PrinterException { paperWidth + " "+ paperHeight+"]"); final PrintService pservice = getPrintService(); - Boolean isPS = java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Boolean run() { - try { - Class psClass = Class.forName("sun.print.IPPPrintService"); - if (psClass.isInstance(pservice)) { - Method isPSMethod = psClass.getMethod("isPostscript", - (Class[])null); - return (Boolean)isPSMethod.invoke(pservice, (Object[])null); - } - } catch (Throwable t) { - } - return Boolean.TRUE; - } + Boolean isPS = Boolean.TRUE; + try { + Class psClass = Class.forName("sun.print.IPPPrintService"); + if (psClass.isInstance(pservice)) { + Method isPSMethod = psClass.getMethod("isPostscript", + (Class[])null); + isPS = (Boolean)isPSMethod.invoke(pservice, (Object[])null); } - ); + } catch (Throwable t) { + } if (isPS) { mPSStream.print(" /DeferredMediaSelection true"); } @@ -677,9 +661,9 @@ public Boolean run() { mPSStream.println("%%EndSetup"); } - // Inner class to run "privileged" to open the printer output stream. + // Inner class to open the printer output stream. - private class PrinterOpener implements java.security.PrivilegedAction { + private class PrinterOpener { PrinterException pex; OutputStream result; @@ -704,9 +688,9 @@ public OutputStream run() { } } - // Inner class to run "privileged" to invoke the system print command + // Inner class to invoke the system print command - private class PrinterSpooler implements java.security.PrivilegedAction { + private class PrinterSpooler { PrinterException pex; private void handleProcessFailure(final Process failedProcess, @@ -767,21 +751,13 @@ mNoJobSheet, getJobNameInt(), /** * Invoked if the application cancelled the printjob. */ - @SuppressWarnings("removal") protected void abortDoc() { if (mPSStream != null && mDestType != RasterPrinterJob.STREAM) { mPSStream.close(); } - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - - public Object run() { - if (spoolFile != null && spoolFile.exists()) { - spoolFile.delete(); - } - return null; - } - }); + if (spoolFile != null && spoolFile.exists()) { + spoolFile.delete(); + } } /** @@ -789,7 +765,6 @@ public Object run() { * this method is called after that last page * has been imaged. */ - @SuppressWarnings("removal") protected void endDoc() throws PrinterException { if (mPSStream != null) { mPSStream.println(EOF_COMMENT); @@ -814,7 +789,7 @@ protected void endDoc() throws PrinterException { } } PrinterSpooler spooler = new PrinterSpooler(); - java.security.AccessController.doPrivileged(spooler); + spooler.run(); if (spooler.pex != null) { throw spooler.pex; } @@ -859,28 +834,18 @@ protected void startPage(PageFormat pageFormat, Printable painter, paperWidth + " " + paperHeight + "]"); final PrintService pservice = getPrintService(); - @SuppressWarnings("removal") - Boolean isPS = java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Boolean run() { - try { - Class psClass = - Class.forName("sun.print.IPPPrintService"); - if (psClass.isInstance(pservice)) { - Method isPSMethod = - psClass.getMethod("isPostscript", - (Class[])null); - return (Boolean) - isPSMethod.invoke(pservice, + Boolean isPS = Boolean.TRUE; + try { + Class psClass = Class.forName("sun.print.IPPPrintService"); + if (psClass.isInstance(pservice)) { + Method isPSMethod = + psClass.getMethod("isPostscript", + (Class[])null); + isPS = (Boolean) isPSMethod.invoke(pservice, (Object[])null); - } - } catch (Throwable t) { - } - return Boolean.TRUE; - } - } - ); - + } + } catch (Throwable t) { + } if (isPS) { mPSStream.print(" /DeferredMediaSelection true"); } diff --git a/src/java.desktop/share/classes/sun/print/RasterPrinterJob.java b/src/java.desktop/share/classes/sun/print/RasterPrinterJob.java index 82f47824bfae7..bf380873d2be5 100644 --- a/src/java.desktop/share/classes/sun/print/RasterPrinterJob.java +++ b/src/java.desktop/share/classes/sun/print/RasterPrinterJob.java @@ -174,9 +174,7 @@ public abstract class RasterPrinterJob extends PrinterJob { * use a particular pipeline. Either the raster * pipeline or the pdl pipeline can be forced. */ - @SuppressWarnings("removal") - String forceStr = java.security.AccessController.doPrivileged( - new sun.security.action.GetPropertyAction(FORCE_PIPE_PROP)); + String forceStr = System.getProperty(FORCE_PIPE_PROP); if (forceStr != null) { if (forceStr.equalsIgnoreCase(FORCE_PDL)) { @@ -186,9 +184,7 @@ public abstract class RasterPrinterJob extends PrinterJob { } } - @SuppressWarnings("removal") - String shapeTextStr =java.security.AccessController.doPrivileged( - new sun.security.action.GetPropertyAction(SHAPE_TEXT_PROP)); + String shapeTextStr = System.getProperty(SHAPE_TEXT_PROP); if (shapeTextStr != null) { shapeTextProp = true; @@ -731,20 +727,9 @@ public PageFormat pageDialog(PageFormat page) GraphicsEnvironment.getLocalGraphicsEnvironment(). getDefaultScreenDevice().getDefaultConfiguration(); - @SuppressWarnings("removal") - PrintService service = java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public PrintService run() { - PrintService service = getPrintService(); - if (service == null) { - ServiceDialog.showNoPrintService(gc); - return null; - } - return service; - } - }); - + PrintService service = getPrintService(); if (service == null) { + ServiceDialog.showNoPrintService(gc); return page; } updatePageAttributes(service, page); @@ -812,20 +797,9 @@ public PageFormat pageDialog(final PrintRequestAttributeSet attributes) } final GraphicsConfiguration gc = grCfg; - @SuppressWarnings("removal") - PrintService service = java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public PrintService run() { - PrintService service = getPrintService(); - if (service == null) { - ServiceDialog.showNoPrintService(gc); - return null; - } - return service; - } - }); - + PrintService service = getPrintService(); if (service == null) { + ServiceDialog.showNoPrintService(gc); return null; } @@ -953,7 +927,6 @@ protected PageFormat getPageFormatFromAttributes() { * returns true. * @see java.awt.GraphicsEnvironment#isHeadless */ - @SuppressWarnings("removal") public boolean printDialog(final PrintRequestAttributeSet attributes) throws HeadlessException { if (GraphicsEnvironment.isHeadless()) { @@ -1008,19 +981,9 @@ public boolean printDialog(final PrintRequestAttributeSet attributes) } final GraphicsConfiguration gc = grCfg; - PrintService service = java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public PrintService run() { - PrintService service = getPrintService(); - if (service == null) { - ServiceDialog.showNoPrintService(gc); - return null; - } - return service; - } - }); - + PrintService service = getPrintService(); if (service == null) { + ServiceDialog.showNoPrintService(gc); return false; } @@ -1033,13 +996,7 @@ public PrintService run() { services[i] = spsFactories[i].getPrintService(null); } } else { - services = java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public PrintService[] run() { - PrintService[] services = PrinterJob.lookupPrintServices(); - return services; - } - }); + services = PrinterJob.lookupPrintServices(); if ((services == null) || (services.length == 0)) { /* diff --git a/src/java.desktop/share/classes/sun/print/ServiceDialog.java b/src/java.desktop/share/classes/sun/print/ServiceDialog.java index 983be70bdbbb9..ae2c787ce3606 100644 --- a/src/java.desktop/share/classes/sun/print/ServiceDialog.java +++ b/src/java.desktop/share/classes/sun/print/ServiceDialog.java @@ -448,21 +448,13 @@ private void updatePanels() { /** * Initialize ResourceBundle */ - @SuppressWarnings("removal") public static void initResource() { - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Object run() { - try { - messageRB = ResourceBundle.getBundle(strBundle); - return null; - } catch (java.util.MissingResourceException e) { - throw new Error("Fatal: Resource for ServiceUI " + - "is missing"); - } - } - } - ); + try { + messageRB = ResourceBundle.getBundle(strBundle); + } catch (java.util.MissingResourceException e) { + throw new Error("Fatal: Resource for ServiceUI " + + "is missing"); + } } /** @@ -542,15 +534,7 @@ private static int getVKMnemonic(String key) { * Returns URL for image resource */ private static URL getImageResource(final String key) { - @SuppressWarnings("removal") - URL url = java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public URL run() { - URL url = ServiceDialog.class.getResource( - "resources/" + key); - return url; - } - }); + URL url = ServiceDialog.class.getResource("resources/" + key); if (url == null) { throw new Error("Fatal: Resource for ServiceUI is broken; " + @@ -2943,14 +2927,7 @@ public IconRadioButton(String key, String img, boolean selected, { super(new FlowLayout(FlowLayout.LEADING)); final URL imgURL = getImageResource(img); - @SuppressWarnings("removal") - Icon icon = java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Icon run() { - Icon icon = new ImageIcon(imgURL); - return icon; - } - }); + Icon icon = new ImageIcon(imgURL); lbl = new JLabel(icon); add(lbl); diff --git a/src/java.desktop/share/classes/sun/swing/JLightweightFrame.java b/src/java.desktop/share/classes/sun/swing/JLightweightFrame.java index d83b940a0bd6c..8e4b0ff3f7c76 100644 --- a/src/java.desktop/share/classes/sun/swing/JLightweightFrame.java +++ b/src/java.desktop/share/classes/sun/swing/JLightweightFrame.java @@ -40,7 +40,6 @@ import java.awt.image.DataBufferInt; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; -import java.security.AccessController; import javax.swing.JComponent; import javax.swing.JLayeredPane; @@ -55,7 +54,6 @@ import sun.awt.DisplayChangedListener; import sun.awt.LightweightFrame; import sun.awt.OverrideNativeWindowHandle; -import sun.security.action.GetPropertyAction; import sun.swing.SwingUtilities2.RepaintListener; /** @@ -105,24 +103,21 @@ public void updateCursor(JLightweightFrame frame) { * by the lock (managed with the {@link LightweightContent#paintLock()}, * {@link LightweightContent#paintUnlock()} methods). */ - @SuppressWarnings("removal") - private static boolean copyBufferEnabled = "true".equals(AccessController. - doPrivileged(new GetPropertyAction("swing.jlf.copyBufferEnabled", "true"))); + private static boolean copyBufferEnabled = "true".equals( + System.getProperty("swing.jlf.copyBufferEnabled", "true")); private int[] copyBuffer; /** * Constructs a new, initially invisible {@code JLightweightFrame} * instance. */ - @SuppressWarnings("removal") public JLightweightFrame() { super(); AffineTransform defaultTransform = getGraphicsConfiguration().getDefaultTransform(); scaleFactorX = defaultTransform.getScaleX(); scaleFactorY = defaultTransform.getScaleY(); - copyBufferEnabled = "true".equals(AccessController. - doPrivileged(new GetPropertyAction("swing.jlf.copyBufferEnabled", "true"))); + copyBufferEnabled = "true".equals(System.getProperty("swing.jlf.copyBufferEnabled", "true")); add(rootPane, BorderLayout.CENTER); setFocusTraversalPolicy(new LayoutFocusTraversalPolicy()); @@ -331,7 +326,6 @@ private void notifyImageUpdated(int x, int y, int width, int height) { content.imageUpdated(x, y, width, height); } - @SuppressWarnings("removal") private void initInterior() { contentPane = new JPanel() { @Override @@ -392,8 +386,7 @@ public void componentRemoved(ContainerEvent e) { contentPane.add(component); contentPane.revalidate(); contentPane.repaint(); - if ("true".equals(AccessController. - doPrivileged(new GetPropertyAction("swing.jlf.contentPaneTransparent", "false")))) + if ("true".equals(System.getProperty("swing.jlf.contentPaneTransparent", "false"))) { contentPane.setOpaque(false); } diff --git a/src/java.desktop/share/classes/sun/swing/SwingUtilities2.java b/src/java.desktop/share/classes/sun/swing/SwingUtilities2.java index d763a72d528be..2613ca326ea49 100644 --- a/src/java.desktop/share/classes/sun/swing/SwingUtilities2.java +++ b/src/java.desktop/share/classes/sun/swing/SwingUtilities2.java @@ -61,8 +61,6 @@ import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Modifier; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.text.AttributedCharacterIterator; import java.text.AttributedString; import java.text.BreakIterator; @@ -1706,10 +1704,8 @@ private static Object makeIcon(final Class baseClass, final String imageFile, final boolean enablePrivileges) { return (UIDefaults.LazyValue) (table) -> { - @SuppressWarnings("removal") - byte[] buffer = enablePrivileges ? AccessController.doPrivileged( - (PrivilegedAction) () - -> getIconBytes(baseClass, rootClass, imageFile)) + byte[] buffer = enablePrivileges ? + getIconBytes(baseClass, rootClass, imageFile) : getIconBytes(baseClass, rootClass, imageFile); if (buffer == null) { From cf158bc6cdadfdfa944b8ec1d3dc7069c8f055a9 Mon Sep 17 00:00:00 2001 From: Jan Lahoda Date: Wed, 20 Nov 2024 09:24:05 +0000 Subject: [PATCH 35/74] 8341631: JShell should auto-import java.io.IO.* Reviewed-by: asotona, cstein --- .../jshell/tool/ConsoleIOContext.java | 5 ++ .../jdk/internal/jshell/tool/IOContext.java | 4 ++ .../jdk/internal/jshell/tool/JShellTool.java | 47 +++++++++++++++---- .../jshell/execution/impl/ConsoleImpl.java | 20 ++++++-- .../jshell/tool/resources/PREVIEW_DEFAULT.jsh | 1 + .../langtools/jdk/jshell/ConsoleToolTest.java | 36 +++++++++++++- .../langtools/jdk/jshell/StartOptionTest.java | 45 ++++++++++++++++-- 7 files changed, 141 insertions(+), 17 deletions(-) diff --git a/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/ConsoleIOContext.java b/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/ConsoleIOContext.java index f4ca58d6af438..c92e6e11f1fa7 100644 --- a/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/ConsoleIOContext.java +++ b/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/ConsoleIOContext.java @@ -1001,6 +1001,11 @@ public synchronized String readUserLine(String prompt) throws IOException { return doReadUserLine(prompt, null); } + @Override + public String readUserLine() throws IOException { + return readUserLine(""); + } + private synchronized String doReadUserLine(String prompt, Character mask) throws IOException { History prevHistory = in.getHistory(); boolean prevDisableCr = Display.DISABLE_CR; diff --git a/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/IOContext.java b/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/IOContext.java index e22d927911c0a..7a1234628deea 100644 --- a/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/IOContext.java +++ b/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/IOContext.java @@ -64,6 +64,8 @@ public char readUserInputChar() throws IOException { } public String readUserLine(String prompt) throws IOException { + userOutput().write(prompt); + userOutput().flush(); throw new UserInterruptException(""); } @@ -76,6 +78,8 @@ public Writer userOutput() { } public char[] readPassword(String prompt) throws IOException { + userOutput().write(prompt); + userOutput().flush(); throw new UserInterruptException(""); } diff --git a/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/JShellTool.java b/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/JShellTool.java index d2d2ed10e6333..1adcb472b779c 100644 --- a/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/JShellTool.java +++ b/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/JShellTool.java @@ -35,6 +35,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; +import java.io.OutputStreamWriter; import java.io.PrintStream; import java.io.PrintWriter; import java.io.Reader; @@ -1192,7 +1193,7 @@ private void initFeedback(String initMode) { //where private void startUpRun(String start) { - try (IOContext suin = new ScannerIOContext(new StringReader(start))) { + try (IOContext suin = new ScannerIOContext(new StringReader(start), userout)) { while (run(suin)) { if (!live) { resetState(); @@ -3125,7 +3126,7 @@ private boolean runFile(String filename, String context) { throw new FileNotFoundException(filename); } } - try (var scannerIOContext = new ScannerIOContext(scanner)) { + try (var scannerIOContext = new ScannerIOContext(scanner, userout)) { run(scannerIOContext); } return true; @@ -3288,8 +3289,10 @@ private boolean doReload(ReplayableHistory history, boolean echo, Options oldOpt resetState(); } if (history != null) { - run(new ReloadIOContext(history.iterable(), - echo ? cmdout : null)); + try (ReloadIOContext ctx = new ReloadIOContext(history.iterable(), + echo ? cmdout : null, userout)) { + run(ctx); + } } return true; } @@ -4107,6 +4110,8 @@ public void close() throws IOException { public String readLine(String prompt) { try { return input.readUserLine(prompt); + } catch (UserInterruptException ex) { + return null; } catch (IOException ex) { throw new IOError(ex); } @@ -4125,6 +4130,8 @@ public String readLine() throws IOError { public char[] readPassword(String prompt) { try { return input.readPassword(prompt); + } catch (UserInterruptException ex) { + return null; } catch (IOException ex) { throw new IOError(ex); } @@ -4144,6 +4151,12 @@ public Charset charset() { abstract class NonInteractiveIOContext extends IOContext { + private final Writer userOutput; + + public NonInteractiveIOContext(PrintStream userOutput) { + this.userOutput = new OutputStreamWriter(userOutput); + } + @Override public boolean interactiveOutput() { return false; @@ -4178,17 +4191,33 @@ public void afterUserCode() { @Override public void replaceLastHistoryEntry(String source) { } + + @Override + public Writer userOutput() { + return userOutput; + } + + @Override + public void close() { + try { + userOutput.flush(); + } catch (IOException _) { + //ignore + } + } + } class ScannerIOContext extends NonInteractiveIOContext { private final Scanner scannerIn; - ScannerIOContext(Scanner scannerIn) { + ScannerIOContext(Scanner scannerIn, PrintStream userOutput) { + super(userOutput); this.scannerIn = scannerIn; } - ScannerIOContext(Reader rdr) throws FileNotFoundException { - this(new Scanner(rdr)); + ScannerIOContext(Reader rdr, PrintStream userOutput) throws FileNotFoundException { + this(new Scanner(rdr), userOutput); } @Override @@ -4202,6 +4231,7 @@ public String readLine(String firstLinePrompt, String continuationPrompt, boolea @Override public void close() { + super.close(); scannerIn.close(); } @@ -4215,7 +4245,8 @@ class ReloadIOContext extends NonInteractiveIOContext { private final Iterator it; private final PrintStream echoStream; - ReloadIOContext(Iterable history, PrintStream echoStream) { + ReloadIOContext(Iterable history, PrintStream echoStream, PrintStream userOutput) { + super(userOutput); this.it = history.iterator(); this.echoStream = echoStream; } diff --git a/src/jdk.jshell/share/classes/jdk/jshell/execution/impl/ConsoleImpl.java b/src/jdk.jshell/share/classes/jdk/jshell/execution/impl/ConsoleImpl.java index 876f61ec85675..a697a37141ed8 100644 --- a/src/jdk.jshell/share/classes/jdk/jshell/execution/impl/ConsoleImpl.java +++ b/src/jdk.jshell/share/classes/jdk/jshell/execution/impl/ConsoleImpl.java @@ -117,6 +117,9 @@ private int readChars(char[] data, int off, int len) throws IOException { private char[] readChars() throws IOException { int actualLen = readInt(); + if (actualLen == (-1)) { + return null; + } char[] result = new char[actualLen]; for (int i = 0; i < actualLen; i++) { result[i] = (char) ((remoteOutput.read() << 8) | @@ -267,6 +270,9 @@ public String readLine(Locale locale, String format, Object... args) { remoteInput.write(Task.READ_LINE.ordinal()); sendChars(chars, 0, chars.length); char[] line = readChars(); + if (line == null) { + return null; + } return new String(line); }); } catch (IOException ex) { @@ -417,8 +423,12 @@ public synchronized void write(int b) throws IOException { char[] data = readCharsOrNull(1); if (data != null) { String line = console.readLine(new String(data)); - char[] chars = line.toCharArray(); - sendChars(sinkOutput, chars, 0, chars.length); + if (line == null) { + sendInt(sinkOutput, -1); + } else { + char[] chars = line.toCharArray(); + sendChars(sinkOutput, chars, 0, chars.length); + } bp = 0; } } @@ -432,7 +442,11 @@ public synchronized void write(int b) throws IOException { char[] data = readCharsOrNull(1); if (data != null) { char[] chars = console.readPassword(new String(data)); - sendChars(sinkOutput, chars, 0, chars.length); + if (chars == null) { + sendInt(sinkOutput, -1); + } else { + sendChars(sinkOutput, chars, 0, chars.length); + } bp = 0; } } diff --git a/src/jdk.jshell/share/classes/jdk/jshell/tool/resources/PREVIEW_DEFAULT.jsh b/src/jdk.jshell/share/classes/jdk/jshell/tool/resources/PREVIEW_DEFAULT.jsh index 4644ac8638657..975d12155352b 100644 --- a/src/jdk.jshell/share/classes/jdk/jshell/tool/resources/PREVIEW_DEFAULT.jsh +++ b/src/jdk.jshell/share/classes/jdk/jshell/tool/resources/PREVIEW_DEFAULT.jsh @@ -1 +1,2 @@ import module java.base; +import static java.io.IO.*; diff --git a/test/langtools/jdk/jshell/ConsoleToolTest.java b/test/langtools/jdk/jshell/ConsoleToolTest.java index 8fa85a3ec2787..0af85a6186297 100644 --- a/test/langtools/jdk/jshell/ConsoleToolTest.java +++ b/test/langtools/jdk/jshell/ConsoleToolTest.java @@ -23,7 +23,7 @@ /* * @test - * @bug 8331535 + * @bug 8331535 8341631 * @summary Test the JShell tool Console handling * @modules jdk.internal.le/jdk.internal.org.jline.reader * jdk.jshell/jdk.internal.jshell.tool:+open @@ -56,6 +56,40 @@ public void testOutput() { ); } + @Test //JDK-8341631 + public void testIO() { + test(new String[] {"--enable-preview"}, + a -> {assertCommandWithOutputAndTerminal(a, + "java.io.IO.readln(\"%%s\");\ninput", //newline automatically appended + "$1 ==> \"input\"", + """ + \u0005java.io.IO.readln(\"%%s\"); + %%sinput + """);}, + a -> {assertCommandWithOutputAndTerminal(a, + "java.io.IO.readln();\ninput!", //newline automatically appended + "$2 ==> \"input!\"", + """ + \u0005java.io.IO.readln(); + input! + """);}, + a -> {assertCommandWithOutputAndTerminal(a, + "java.io.IO.println(\"Hello, World!\");", + "", + """ + \u0005java.io.IO.println(\"Hello, World!\"); + Hello, World! + """);}, + a -> {assertCommandWithOutputAndTerminal(a, + "java.io.IO.println();", + "", + """ + \u0005java.io.IO.println(); + + """);} + ); + } + void assertCommandWithOutputAndTerminal(boolean a, String command, String out, String terminalOut) { assertCommand(a, command, out, null, null, null, null, terminalOut); } diff --git a/test/langtools/jdk/jshell/StartOptionTest.java b/test/langtools/jdk/jshell/StartOptionTest.java index 60926e69843a7..b84b454480e5e 100644 --- a/test/langtools/jdk/jshell/StartOptionTest.java +++ b/test/langtools/jdk/jshell/StartOptionTest.java @@ -22,7 +22,7 @@ */ /* - * @test 8151754 8080883 8160089 8170162 8166581 8172102 8171343 8178023 8186708 8179856 8185840 8190383 + * @test 8151754 8080883 8160089 8170162 8166581 8172102 8171343 8178023 8186708 8179856 8185840 8190383 8341631 * @summary Testing startExCe-up options. * @modules jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main @@ -366,14 +366,49 @@ public void testShowVersion() { } public void testPreviewEnabled() { - String fn = writeToFile("System.out.println(\"prefix\");\n" + - "System.out.println(MethodHandle.class.getName());\n" + - "System.out.println(\"suffix\");\n" + - "/exit\n"); + String fn = writeToFile( + """ + System.out.println(\"prefix\"); + System.out.println(MethodHandle.class.getName()); + System.out.println(\"suffix\"); + /exit + """); startCheckUserOutput(s -> assertEquals(s, "prefix\nsuffix\n"), fn); startCheckUserOutput(s -> assertEquals(s, "prefix\njava.lang.invoke.MethodHandle\nsuffix\n"), "--enable-preview", fn); + //JDK-8341631: + String fn2 = writeToFile( + """ + System.out.println(\"prefix\"); + IO.println(\"test\"); + System.out.println(\"suffix\"); + /exit + """); + startCheckUserOutput(s -> assertEquals(s, "prefix\nsuffix\n"), + fn2); + startCheckUserOutput(s -> assertEquals(s, "prefix\ntest\nsuffix\n"), + "--enable-preview", fn2); + } + public void testInput() { + //readLine(String): + String readLinePrompt = writeToFile( + """ + var v = System.console().readLine("prompt: "); + System.out.println(v); + /exit + """); + startCheckUserOutput(s -> assertEquals(s, "prompt: null\n"), + readLinePrompt); + //readPassword(String): + String readPasswordPrompt = writeToFile( + """ + var v = System.console().readPassword("prompt: "); + System.out.println(java.util.Arrays.toString(v)); + /exit + """); + startCheckUserOutput(s -> assertEquals(s, "prompt: null\n"), + readPasswordPrompt); } @AfterMethod From 3a4a9b7af7693a836c3caa3112d0d68100535b28 Mon Sep 17 00:00:00 2001 From: Aggelos Biboudis Date: Wed, 20 Nov 2024 10:29:45 +0000 Subject: [PATCH 36/74] 8340145: Problem with generic pattern matching results in internal compiler error Reviewed-by: jlahoda --- .../com/sun/tools/javac/comp/Flow.java | 2 +- .../tools/javac/patterns/T8340145.java | 66 +++++++++++++++++++ 2 files changed, 67 insertions(+), 1 deletion(-) create mode 100644 test/langtools/tools/javac/patterns/T8340145.java diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Flow.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Flow.java index 29ab8435adae6..df28548152aec 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Flow.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Flow.java @@ -910,7 +910,7 @@ private Set reduceBindingPatterns(Type selectorType, Set toAdd = new HashSet<>(); for (Type sup : types.directSupertypes(bpOne.type)) { - ClassSymbol clazz = (ClassSymbol) sup.tsym; + ClassSymbol clazz = (ClassSymbol) types.erasure(sup).tsym; clazz.complete(); diff --git a/test/langtools/tools/javac/patterns/T8340145.java b/test/langtools/tools/javac/patterns/T8340145.java new file mode 100644 index 0000000000000..04b12664b72ac --- /dev/null +++ b/test/langtools/tools/javac/patterns/T8340145.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2024, 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. + * + * 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. + */ + +/* + * @test + * @bug 8340145 + * @summary Problem with generic pattern matching results in internal compiler error + * @compile T8340145.java + * @run main T8340145 + */ +public class T8340145 { + public static void main(String[] args) { + Option optionInteger = new Option.Some<>(21); + Number number = Option.unwrapOrElse(optionInteger, 5.2); + + Option2 optionBound = new Option2.Some<>(new Impl (){}); + Bound number2 = Option2.unwrapOrElse(optionBound, new Impl(){}); + } + + sealed interface Option permits Option.Some, Option.None { + record Some(T value) implements Option {} + record None() implements Option {} + + static T unwrapOrElse(Option option, T defaultValue) { + return switch (option) { + case Option.Some(T2 value) -> value; + case Option.None _ -> defaultValue; + }; + } + } + + interface Bound {} + interface Bound2 {} + static class Impl implements Bound, Bound2 {} + sealed interface Option2 permits Option2.Some, Option2.None { + record Some(T value) implements Option2 {} + record None() implements Option2 {} + + static T unwrapOrElse(Option2 option, T defaultValue) { + return switch (option) { + case Option2.Some(T value) -> value; + case Option2.None _ -> defaultValue; + }; + } + } +} From afee7405bd13cbe1cb829dd150a9de7e6faf49ae Mon Sep 17 00:00:00 2001 From: Xiaolong Peng Date: Wed, 20 Nov 2024 10:34:07 +0000 Subject: [PATCH 37/74] 8343541: C1: Plain memory accesses are emitted with membars with +AlwaysAtomicAccesses Reviewed-by: shade, vlivanov --- src/hotspot/share/gc/shared/c1/barrierSetC1.cpp | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/hotspot/share/gc/shared/c1/barrierSetC1.cpp b/src/hotspot/share/gc/shared/c1/barrierSetC1.cpp index fbaef426b51f7..8eaa23ab47612 100644 --- a/src/hotspot/share/gc/shared/c1/barrierSetC1.cpp +++ b/src/hotspot/share/gc/shared/c1/barrierSetC1.cpp @@ -140,7 +140,8 @@ LIR_Opr BarrierSetC1::atomic_add_at(LIRAccess& access, LIRItem& value) { void BarrierSetC1::store_at_resolved(LIRAccess& access, LIR_Opr value) { DecoratorSet decorators = access.decorators(); - bool is_volatile = (((decorators & MO_SEQ_CST) != 0) || AlwaysAtomicAccesses); + bool is_volatile = (decorators & MO_SEQ_CST) != 0; + bool is_atomic = is_volatile || AlwaysAtomicAccesses; bool needs_patching = (decorators & C1_NEEDS_PATCHING) != 0; bool mask_boolean = (decorators & C1_MASK_BOOLEAN) != 0; LIRGenerator* gen = access.gen(); @@ -154,7 +155,7 @@ void BarrierSetC1::store_at_resolved(LIRAccess& access, LIR_Opr value) { } LIR_PatchCode patch_code = needs_patching ? lir_patch_normal : lir_patch_none; - if (is_volatile && !needs_patching) { + if (is_atomic && !needs_patching) { gen->volatile_field_store(value, access.resolved_addr()->as_address_ptr(), access.access_emit_info()); } else { __ store(value, access.resolved_addr()->as_address_ptr(), access.access_emit_info(), patch_code); @@ -168,7 +169,8 @@ void BarrierSetC1::store_at_resolved(LIRAccess& access, LIR_Opr value) { void BarrierSetC1::load_at_resolved(LIRAccess& access, LIR_Opr result) { LIRGenerator *gen = access.gen(); DecoratorSet decorators = access.decorators(); - bool is_volatile = (((decorators & MO_SEQ_CST) != 0) || AlwaysAtomicAccesses); + bool is_volatile = (decorators & MO_SEQ_CST) != 0; + bool is_atomic = is_volatile || AlwaysAtomicAccesses; bool needs_patching = (decorators & C1_NEEDS_PATCHING) != 0; bool mask_boolean = (decorators & C1_MASK_BOOLEAN) != 0; bool in_native = (decorators & IN_NATIVE) != 0; @@ -180,7 +182,7 @@ void BarrierSetC1::load_at_resolved(LIRAccess& access, LIR_Opr result) { LIR_PatchCode patch_code = needs_patching ? lir_patch_normal : lir_patch_none; if (in_native) { __ move_wide(access.resolved_addr()->as_address_ptr(), result); - } else if (is_volatile && !needs_patching) { + } else if (is_atomic && !needs_patching) { gen->volatile_field_load(access.resolved_addr()->as_address_ptr(), result, access.access_emit_info()); } else { __ load(access.resolved_addr()->as_address_ptr(), result, access.access_emit_info(), patch_code); From e2f8f1aded319034a79fe78af7e011e83df75d62 Mon Sep 17 00:00:00 2001 From: David Holmes Date: Wed, 20 Nov 2024 11:51:52 +0000 Subject: [PATCH 38/74] 8344621: ProblemList runtime/CommandLine/OptionsValidation/TestOptionsWithRanges.java Reviewed-by: jpai --- test/hotspot/jtreg/ProblemList.txt | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/test/hotspot/jtreg/ProblemList.txt b/test/hotspot/jtreg/ProblemList.txt index d3de1f871e8d4..f2f1c4f2f5025 100644 --- a/test/hotspot/jtreg/ProblemList.txt +++ b/test/hotspot/jtreg/ProblemList.txt @@ -100,6 +100,17 @@ gc/stress/gclocker/TestExcessGCLockerCollections.java 8229120 generic-all # :hotspot_runtime +runtime/CommandLine/OptionsValidation/TestOptionsWithRanges.java#id0 8344583 macosx-aarch64 +runtime/CommandLine/OptionsValidation/TestOptionsWithRanges.java#id1 8344583 macosx-aarch64 +runtime/CommandLine/OptionsValidation/TestOptionsWithRanges.java#id2 8344583 macosx-aarch64 +runtime/CommandLine/OptionsValidation/TestOptionsWithRanges.java#id3 8344583 macosx-aarch64 +runtime/CommandLine/OptionsValidation/TestOptionsWithRanges.java#id4 8344583 macosx-aarch64 +runtime/CommandLine/OptionsValidation/TestOptionsWithRanges.java#id5 8344583 macosx-aarch64 +runtime/CommandLine/OptionsValidation/TestOptionsWithRanges.java#id6 8344583 macosx-aarch64 +runtime/CommandLine/OptionsValidation/TestOptionsWithRanges.java#id7 8344583 macosx-aarch64 +runtime/CommandLine/OptionsValidation/TestOptionsWithRanges.java#id8 8344583 macosx-aarch64 +runtime/CommandLine/OptionsValidation/TestOptionsWithRanges.java#id9 8344583 macosx-aarch64 + runtime/jni/terminatedThread/TestTerminatedThread.java 8317789 aix-ppc64 runtime/handshake/HandshakeSuspendExitTest.java 8294313 generic-all runtime/Monitor/SyncOnValueBasedClassTest.java 8340995 linux-s390x From ea7e722ca04752f0b58bf98e0a1907c015644fb5 Mon Sep 17 00:00:00 2001 From: Robbin Ehn Date: Wed, 20 Nov 2024 12:05:53 +0000 Subject: [PATCH 39/74] 8344010: RISC-V: Zacas do not work with LW locking Reviewed-by: fyang, mli --- .../cpu/riscv/macroAssembler_riscv.cpp | 102 +++++------------- .../cpu/riscv/macroAssembler_riscv.hpp | 10 -- 2 files changed, 25 insertions(+), 87 deletions(-) diff --git a/src/hotspot/cpu/riscv/macroAssembler_riscv.cpp b/src/hotspot/cpu/riscv/macroAssembler_riscv.cpp index ac0445e5e4e62..81d3338638d8d 100644 --- a/src/hotspot/cpu/riscv/macroAssembler_riscv.cpp +++ b/src/hotspot/cpu/riscv/macroAssembler_riscv.cpp @@ -3466,6 +3466,17 @@ void MacroAssembler::cmpxchg(Register addr, Register expected, assert_different_registers(expected, t0); assert_different_registers(new_val, t0); + // NOTE: + // Register _result_ may be the same register as _new_val_ or _expected_. + // Hence do NOT use _result_ until after 'cas'. + // + // Register _expected_ may be the same register as _new_val_ and is assumed to be preserved. + // Hence do NOT change _expected_ or _new_val_. + // + // Having _expected_ and _new_val_ being the same register is a very puzzling cas. + // + // TODO: Address these issues. + if (UseZacas) { if (result_as_bool) { mv(t0, expected); @@ -3473,8 +3484,9 @@ void MacroAssembler::cmpxchg(Register addr, Register expected, xorr(t0, t0, expected); seqz(result, t0); } else { - mv(result, expected); - atomic_cas(result, new_val, addr, size, acquire, release); + mv(t0, expected); + atomic_cas(t0, new_val, addr, size, acquire, release); + mv(result, t0); } return; } @@ -3510,15 +3522,16 @@ void MacroAssembler::cmpxchg_weak(Register addr, Register expected, enum operand_size size, Assembler::Aqrl acquire, Assembler::Aqrl release, Register result) { - if (UseZacas) { - cmpxchg(addr, expected, new_val, size, acquire, release, result, true); - return; - } assert_different_registers(addr, t0); assert_different_registers(expected, t0); assert_different_registers(new_val, t0); + if (UseZacas) { + cmpxchg(addr, expected, new_val, size, acquire, release, result, true); + return; + } + Label fail, done; load_reserved(t0, addr, size, acquire); bne(t0, expected, fail); @@ -3581,83 +3594,18 @@ ATOMIC_XCHGU(xchgalwu, xchgalw) #undef ATOMIC_XCHGU -#define ATOMIC_CAS(OP, AOP, ACQUIRE, RELEASE) \ -void MacroAssembler::atomic_##OP(Register prev, Register newv, Register addr) { \ - assert(UseZacas, "invariant"); \ - prev = prev->is_valid() ? prev : zr; \ - AOP(prev, addr, newv, (Assembler::Aqrl)(ACQUIRE | RELEASE)); \ - return; \ -} - -ATOMIC_CAS(cas, amocas_d, Assembler::relaxed, Assembler::relaxed) -ATOMIC_CAS(casw, amocas_w, Assembler::relaxed, Assembler::relaxed) -ATOMIC_CAS(casl, amocas_d, Assembler::relaxed, Assembler::rl) -ATOMIC_CAS(caslw, amocas_w, Assembler::relaxed, Assembler::rl) -ATOMIC_CAS(casal, amocas_d, Assembler::aq, Assembler::rl) -ATOMIC_CAS(casalw, amocas_w, Assembler::aq, Assembler::rl) - -#undef ATOMIC_CAS - -#define ATOMIC_CASU(OP1, OP2) \ -void MacroAssembler::atomic_##OP1(Register prev, Register newv, Register addr) { \ - atomic_##OP2(prev, newv, addr); \ - zero_extend(prev, prev, 32); \ - return; \ -} - -ATOMIC_CASU(caswu, casw) -ATOMIC_CASU(caslwu, caslw) -ATOMIC_CASU(casalwu, casalw) - -#undef ATOMIC_CASU - -void MacroAssembler::atomic_cas( - Register prev, Register newv, Register addr, enum operand_size size, Assembler::Aqrl acquire, Assembler::Aqrl release) { +void MacroAssembler::atomic_cas(Register prev, Register newv, Register addr, + enum operand_size size, Assembler::Aqrl acquire, Assembler::Aqrl release) { switch (size) { case int64: - switch ((Assembler::Aqrl)(acquire | release)) { - case Assembler::relaxed: - atomic_cas(prev, newv, addr); - break; - case Assembler::rl: - atomic_casl(prev, newv, addr); - break; - case Assembler::aqrl: - atomic_casal(prev, newv, addr); - break; - default: - ShouldNotReachHere(); - } + amocas_d(prev, addr, newv, (Assembler::Aqrl)(acquire | release)); break; case int32: - switch ((Assembler::Aqrl)(acquire | release)) { - case Assembler::relaxed: - atomic_casw(prev, newv, addr); - break; - case Assembler::rl: - atomic_caslw(prev, newv, addr); - break; - case Assembler::aqrl: - atomic_casalw(prev, newv, addr); - break; - default: - ShouldNotReachHere(); - } + amocas_w(prev, addr, newv, (Assembler::Aqrl)(acquire | release)); break; case uint32: - switch ((Assembler::Aqrl)(acquire | release)) { - case Assembler::relaxed: - atomic_caswu(prev, newv, addr); - break; - case Assembler::rl: - atomic_caslwu(prev, newv, addr); - break; - case Assembler::aqrl: - atomic_casalwu(prev, newv, addr); - break; - default: - ShouldNotReachHere(); - } + amocas_w(prev, addr, newv, (Assembler::Aqrl)(acquire | release)); + zero_extend(prev, prev, 32); break; default: ShouldNotReachHere(); diff --git a/src/hotspot/cpu/riscv/macroAssembler_riscv.hpp b/src/hotspot/cpu/riscv/macroAssembler_riscv.hpp index dc06708b0ff5f..568df0562225c 100644 --- a/src/hotspot/cpu/riscv/macroAssembler_riscv.hpp +++ b/src/hotspot/cpu/riscv/macroAssembler_riscv.hpp @@ -1175,16 +1175,6 @@ class MacroAssembler: public Assembler { void atomic_xchgwu(Register prev, Register newv, Register addr); void atomic_xchgalwu(Register prev, Register newv, Register addr); - void atomic_cas(Register prev, Register newv, Register addr); - void atomic_casw(Register prev, Register newv, Register addr); - void atomic_casl(Register prev, Register newv, Register addr); - void atomic_caslw(Register prev, Register newv, Register addr); - void atomic_casal(Register prev, Register newv, Register addr); - void atomic_casalw(Register prev, Register newv, Register addr); - void atomic_caswu(Register prev, Register newv, Register addr); - void atomic_caslwu(Register prev, Register newv, Register addr); - void atomic_casalwu(Register prev, Register newv, Register addr); - void atomic_cas(Register prev, Register newv, Register addr, enum operand_size size, Assembler::Aqrl acquire = Assembler::relaxed, Assembler::Aqrl release = Assembler::relaxed); From 21b8749bfdede7dfee3e8433dd9443320db99076 Mon Sep 17 00:00:00 2001 From: Coleen Phillimore Date: Wed, 20 Nov 2024 12:21:41 +0000 Subject: [PATCH 40/74] 8344479: Declare MetaspaceObj::operator delete to be deleted Reviewed-by: stefank, kbarrett, jwaters --- src/hotspot/share/memory/allocation.hpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/hotspot/share/memory/allocation.hpp b/src/hotspot/share/memory/allocation.hpp index 9841ce3183caa..ae834ec9a729f 100644 --- a/src/hotspot/share/memory/allocation.hpp +++ b/src/hotspot/share/memory/allocation.hpp @@ -353,7 +353,7 @@ class MetaspaceObj { void* operator new(size_t size, ClassLoaderData* loader_data, size_t word_size, Type type) throw(); - void operator delete(void* p) { ShouldNotCallThis(); } + void operator delete(void* p) = delete; // Declare a *static* method with the same signature in any subclass of MetaspaceObj // that should be read-only by default. See symbol.hpp for an example. This function From 7bb4474d81a55028de5434f445747c56a8dc333c Mon Sep 17 00:00:00 2001 From: Coleen Phillimore Date: Wed, 20 Nov 2024 12:22:43 +0000 Subject: [PATCH 41/74] 8344579: Clean up forward declarations and includes Reviewed-by: stefank --- src/hotspot/share/oops/instanceKlass.hpp | 2 -- src/hotspot/share/oops/klass.hpp | 4 ---- src/hotspot/share/oops/method.hpp | 1 - src/hotspot/share/runtime/vmStructs.cpp | 1 - 4 files changed, 8 deletions(-) diff --git a/src/hotspot/share/oops/instanceKlass.hpp b/src/hotspot/share/oops/instanceKlass.hpp index b3283a04d448a..13b50859ee366 100644 --- a/src/hotspot/share/oops/instanceKlass.hpp +++ b/src/hotspot/share/oops/instanceKlass.hpp @@ -45,7 +45,6 @@ class ConstantPool; class DeoptimizationScope; class klassItable; -class Monitor; class RecordComponent; // An InstanceKlass is the VM level representation of a Java class. @@ -68,7 +67,6 @@ class ClassFileStream; class KlassDepChange; class DependencyContext; class fieldDescriptor; -class jniIdMapBase; class JNIid; class JvmtiCachedClassFieldMap; class nmethodBucket; diff --git a/src/hotspot/share/oops/klass.hpp b/src/hotspot/share/oops/klass.hpp index 8c128ab9ce61f..2c75d6da3b8cb 100644 --- a/src/hotspot/share/oops/klass.hpp +++ b/src/hotspot/share/oops/klass.hpp @@ -25,8 +25,6 @@ #ifndef SHARE_OOPS_KLASS_HPP #define SHARE_OOPS_KLASS_HPP -#include "memory/iterator.hpp" -#include "memory/memRegion.hpp" #include "oops/klassFlags.hpp" #include "oops/markWord.hpp" #include "oops/metadata.hpp" @@ -60,8 +58,6 @@ class fieldDescriptor; class klassVtable; class ModuleEntry; class PackageEntry; -class ParCompactionManager; -class PSPromotionManager; class vtableEntry; class Klass : public Metadata { diff --git a/src/hotspot/share/oops/method.hpp b/src/hotspot/share/oops/method.hpp index cc3caccd16ae5..271d8b3986378 100644 --- a/src/hotspot/share/oops/method.hpp +++ b/src/hotspot/share/oops/method.hpp @@ -32,7 +32,6 @@ #include "oops/methodFlags.hpp" #include "oops/instanceKlass.hpp" #include "oops/oop.hpp" -#include "oops/typeArrayOop.hpp" #include "utilities/accessFlags.hpp" #include "utilities/align.hpp" #include "utilities/growableArray.hpp" diff --git a/src/hotspot/share/runtime/vmStructs.cpp b/src/hotspot/share/runtime/vmStructs.cpp index bc941534242e3..a1c1551ae0910 100644 --- a/src/hotspot/share/runtime/vmStructs.cpp +++ b/src/hotspot/share/runtime/vmStructs.cpp @@ -1930,7 +1930,6 @@ declare_toplevel_type(jbyte*) \ declare_toplevel_type(jbyte**) \ declare_toplevel_type(jint*) \ - declare_toplevel_type(jniIdMapBase*) \ declare_unsigned_integer_type(juint) \ declare_unsigned_integer_type(julong) \ declare_toplevel_type(JNIHandleBlock*) \ From 6f4dfa66268c7aef0298af7f18d8e8bd4eb21656 Mon Sep 17 00:00:00 2001 From: Jaikiran Pai Date: Wed, 20 Nov 2024 12:29:32 +0000 Subject: [PATCH 42/74] 8344190: Cleanup code in sun.net.www.protocol.http and sun.net.www.protocol.https after JEP 486 integration Reviewed-by: dfuchs --- .../protocol/http/AuthenticationHeader.java | 5 +- .../www/protocol/http/AuthenticationInfo.java | 9 +- .../protocol/http/BasicAuthentication.java | 10 +- .../protocol/http/DigestAuthentication.java | 28 +- .../www/protocol/http/HttpURLConnection.java | 558 ++++-------------- .../http/NegotiateAuthentication.java | 14 +- .../net/www/protocol/https/HttpsClient.java | 122 +--- .../http/ntlm/NTLMAuthentication.java | 4 +- .../http/ntlm/NTLMAuthentication.java | 48 +- 9 files changed, 129 insertions(+), 669 deletions(-) diff --git a/src/java.base/share/classes/sun/net/www/protocol/http/AuthenticationHeader.java b/src/java.base/share/classes/sun/net/www/protocol/http/AuthenticationHeader.java index 8083fb36f3984..8bccc53cafcd7 100644 --- a/src/java.base/share/classes/sun/net/www/protocol/http/AuthenticationHeader.java +++ b/src/java.base/share/classes/sun/net/www/protocol/http/AuthenticationHeader.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2024, 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 @@ -32,7 +32,6 @@ import java.util.Set; import sun.net.www.*; -import sun.security.action.GetPropertyAction; /** * This class is used to parse the information in WWW-Authenticate: and Proxy-Authenticate: @@ -98,7 +97,7 @@ public String toString() { } static { - String pref = GetPropertyAction.privilegedGetProperty("http.auth.preference"); + String pref = System.getProperty("http.auth.preference"); // http.auth.preference can be set to SPNEGO or Kerberos. // In fact they means "Negotiate with SPNEGO" and "Negotiate with diff --git a/src/java.base/share/classes/sun/net/www/protocol/http/AuthenticationInfo.java b/src/java.base/share/classes/sun/net/www/protocol/http/AuthenticationInfo.java index 4a2b5b628c684..f567d7bd643da 100644 --- a/src/java.base/share/classes/sun/net/www/protocol/http/AuthenticationInfo.java +++ b/src/java.base/share/classes/sun/net/www/protocol/http/AuthenticationInfo.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2024, 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 @@ -25,8 +25,6 @@ package sun.net.www.protocol.http; -import java.io.IOException; -import java.io.ObjectInputStream; import java.net.PasswordAuthentication; import java.net.URL; import java.util.HashMap; @@ -67,10 +65,7 @@ public abstract class AuthenticationInfo extends AuthCacheValue implements Clone * repeatedly, via the Authenticator. Default is false, which means that this * behavior is switched off. */ - @SuppressWarnings("removal") - static final boolean serializeAuth = java.security.AccessController.doPrivileged( - new sun.security.action.GetBooleanAction( - "http.auth.serializeRequests")).booleanValue(); + static final boolean serializeAuth = Boolean.getBoolean("http.auth.serializeRequests"); /* AuthCacheValue: */ diff --git a/src/java.base/share/classes/sun/net/www/protocol/http/BasicAuthentication.java b/src/java.base/share/classes/sun/net/www/protocol/http/BasicAuthentication.java index 73d5ff98b3a5c..f008c185b5d6d 100644 --- a/src/java.base/share/classes/sun/net/www/protocol/http/BasicAuthentication.java +++ b/src/java.base/share/classes/sun/net/www/protocol/http/BasicAuthentication.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2024, 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 @@ -32,11 +32,8 @@ import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; -import java.io.IOException; -import java.io.OutputStream; import java.util.Arrays; import java.util.Base64; -import java.util.Objects; import sun.net.www.HeaderParser; import sun.nio.cs.ISO_8859_1; import sun.nio.cs.UTF_8; @@ -49,10 +46,7 @@ */ -class BasicAuthentication extends AuthenticationInfo { - - @java.io.Serial - private static final long serialVersionUID = 100L; +final class BasicAuthentication extends AuthenticationInfo { /** The authentication string for this host, port, and realm. This is a simple BASE64 encoding of "login:password". */ diff --git a/src/java.base/share/classes/sun/net/www/protocol/http/DigestAuthentication.java b/src/java.base/share/classes/sun/net/www/protocol/http/DigestAuthentication.java index faee05b4dfd10..28d7bc5cf4e0d 100644 --- a/src/java.base/share/classes/sun/net/www/protocol/http/DigestAuthentication.java +++ b/src/java.base/share/classes/sun/net/www/protocol/http/DigestAuthentication.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2024, 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 @@ -35,17 +35,13 @@ import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; import java.nio.charset.StandardCharsets; -import java.security.AccessController; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; -import java.security.PrivilegedAction; import java.security.Security; import java.text.Normalizer; import java.util.Arrays; -import java.util.Collections; import java.util.HashSet; import java.util.Locale; -import java.util.Objects; import java.util.Random; import java.util.Set; import java.util.function.BiConsumer; @@ -65,10 +61,7 @@ * @author Bill Foote */ -class DigestAuthentication extends AuthenticationInfo { - - @java.io.Serial - private static final long serialVersionUID = 100L; +final class DigestAuthentication extends AuthenticationInfo { private String authMethod; @@ -110,26 +103,15 @@ private static void processPropValue(String input, HttpURLConnection.getHttpLogger(); static { - @SuppressWarnings("removal") - Boolean b = AccessController.doPrivileged( - (PrivilegedAction) () -> NetProperties.getBoolean(compatPropName) - ); + Boolean b = NetProperties.getBoolean(compatPropName); delimCompatFlag = (b == null) ? false : b.booleanValue(); - @SuppressWarnings("removal") - String secprops = AccessController.doPrivileged( - (PrivilegedAction) () -> Security.getProperty(secPropName) - ); - + String secprops = Security.getProperty(secPropName); Set algs = new HashSet<>(); - // add the default insecure algorithms to set processPropValue(secprops, algs, (set, elem) -> set.add(elem)); - @SuppressWarnings("removal") - String netprops = AccessController.doPrivileged( - (PrivilegedAction) () -> NetProperties.get(enabledAlgPropName) - ); + String netprops = NetProperties.get(enabledAlgPropName); // remove any algorithms from disabled set that were opted-in by user processPropValue(netprops, algs, (set, elem) -> set.remove(elem)); disabledDigests = Set.copyOf(algs); diff --git a/src/java.base/share/classes/sun/net/www/protocol/http/HttpURLConnection.java b/src/java.base/share/classes/sun/net/www/protocol/http/HttpURLConnection.java index 8351185350269..602f798448cc4 100644 --- a/src/java.base/share/classes/sun/net/www/protocol/http/HttpURLConnection.java +++ b/src/java.base/share/classes/sun/net/www/protocol/http/HttpURLConnection.java @@ -25,7 +25,6 @@ package sun.net.www.protocol.http; -import java.security.PrivilegedAction; import java.util.Arrays; import java.net.URL; import java.net.URLConnection; @@ -37,7 +36,6 @@ import java.net.InetAddress; import java.net.UnknownHostException; import java.net.SocketTimeoutException; -import java.net.SocketPermission; import java.net.Proxy; import java.net.ProxySelector; import java.net.URI; @@ -47,11 +45,7 @@ import java.net.CacheResponse; import java.net.SecureCacheResponse; import java.net.CacheRequest; -import java.net.URLPermission; import java.net.Authenticator.RequestorType; -import java.security.AccessController; -import java.security.PrivilegedExceptionAction; -import java.security.PrivilegedActionException; import java.io.*; import java.util.ArrayList; import java.util.Collections; @@ -81,7 +75,6 @@ import java.net.MalformedURLException; import java.nio.ByteBuffer; import java.util.Objects; -import java.util.Properties; import java.util.concurrent.locks.ReentrantLock; import static sun.net.www.protocol.http.AuthScheme.BASIC; @@ -90,8 +83,6 @@ import static sun.net.www.protocol.http.AuthScheme.NEGOTIATE; import static sun.net.www.protocol.http.AuthScheme.KERBEROS; import static sun.net.www.protocol.http.AuthScheme.UNKNOWN; -import sun.security.action.GetIntegerAction; -import sun.security.action.GetPropertyAction; /** * A class to represent an HTTP connection to a remote object. @@ -178,8 +169,7 @@ public class HttpURLConnection extends java.net.HttpURLConnection { * Restrict setting of request headers through the public api * consistent with JavaScript XMLHttpRequest2 with a few * exceptions. Disallowed headers are silently ignored for - * backwards compatibility reasons rather than throwing a - * SecurityException. For example, some applets set the + * backwards compatibility reasons. For example, some applets set the * Host header since old JREs did not implement HTTP 1.1. * Additionally, any header starting with Sec- is * disallowed. @@ -222,12 +212,6 @@ public class HttpURLConnection extends java.net.HttpURLConnection { "Via" }; - @SuppressWarnings("removal") - private static String getNetProperty(String name) { - PrivilegedAction pa = () -> NetProperties.get(name); - return AccessController.doPrivileged(pa); - } - private static Set schemesListToSet(String list) { if (list == null || list.isEmpty()) return Collections.emptySet(); @@ -240,11 +224,9 @@ private static Set schemesListToSet(String list) { } static { - Properties props = GetPropertyAction.privilegedGetProperties(); - maxRedirects = GetIntegerAction.privilegedGetProperty( - "http.maxRedirects", defaultmaxRedirects); - version = props.getProperty("java.version"); - String agent = props.getProperty("http.agent"); + maxRedirects = Integer.getInteger("http.maxRedirects", defaultmaxRedirects); + version = System.getProperty("java.version"); + String agent = System.getProperty("http.agent"); if (agent == null) { agent = "Java/"+version; } else { @@ -254,34 +236,30 @@ private static Set schemesListToSet(String list) { // A set of net properties to control the use of authentication schemes // when proxying/tunneling. - String p = getNetProperty("jdk.http.auth.tunneling.disabledSchemes"); + String p = NetProperties.get("jdk.http.auth.tunneling.disabledSchemes"); disabledTunnelingSchemes = schemesListToSet(p); - p = getNetProperty("jdk.http.auth.proxying.disabledSchemes"); + p = NetProperties.get("jdk.http.auth.proxying.disabledSchemes"); disabledProxyingSchemes = schemesListToSet(p); - validateProxy = Boolean.parseBoolean( - props.getProperty("http.auth.digest.validateProxy")); - validateServer = Boolean.parseBoolean( - props.getProperty("http.auth.digest.validateServer")); + validateProxy = Boolean.getBoolean("http.auth.digest.validateProxy"); + validateServer = Boolean.getBoolean("http.auth.digest.validateServer"); - enableESBuffer = Boolean.parseBoolean( - props.getProperty("sun.net.http.errorstream.enableBuffering")); - int esBufferTimeout = GetIntegerAction.privilegedGetProperty( + enableESBuffer = Boolean.getBoolean("sun.net.http.errorstream.enableBuffering"); + int esBufferTimeout = Integer.getInteger( "sun.net.http.errorstream.timeout", 300); if (esBufferTimeout <= 0) { esBufferTimeout = 300; // use the default } timeout4ESBuffer = esBufferTimeout; - int esBufSize = GetIntegerAction.privilegedGetProperty( + int esBufSize = Integer.getInteger( "sun.net.http.errorstream.bufferSize", 4096); if (esBufSize <= 0) { esBufSize = 4096; // use the default } bufSize4ES = esBufSize; - allowRestrictedHeaders = Boolean.parseBoolean( - props.getProperty("sun.net.http.allowRestrictedHeaders")); + allowRestrictedHeaders = Boolean.getBoolean("sun.net.http.allowRestrictedHeaders"); if (!allowRestrictedHeaders) { restrictedHeaderSet = HashSet.newHashSet(restrictedHeaders.length); for (int i=0; i < restrictedHeaders.length; i++) { @@ -292,7 +270,7 @@ private static Set schemesListToSet(String list) { } int defMaxHeaderSize = 384 * 1024; - String maxHeaderSizeStr = getNetProperty("jdk.http.maxHeaderSize"); + String maxHeaderSizeStr = NetProperties.get("jdk.http.maxHeaderSize"); int maxHeaderSizeVal = defMaxHeaderSize; if (maxHeaderSizeStr != null) { try { @@ -439,9 +417,6 @@ public enum TunnelState { private int connectTimeout = NetworkClient.DEFAULT_CONNECT_TIMEOUT; private int readTimeout = NetworkClient.DEFAULT_READ_TIMEOUT; - /* A permission converted from a URLPermission */ - private SocketPermission socketPermission; - /* Logging support */ private static final PlatformLogger logger = PlatformLogger.getLogger("sun.net.www.protocol.http.HttpURLConnection"); @@ -462,36 +437,30 @@ public final boolean isLockHeldByCurrentThread() { } /* - * privileged request password authentication + * Calls Authenticator.requestPasswordAuthentication * */ - @SuppressWarnings("removal") - private static PasswordAuthentication - privilegedRequestPasswordAuthentication( - final Authenticator authenticator, - final String host, - final InetAddress addr, - final int port, - final String protocol, - final String prompt, - final String scheme, - final URL url, - final RequestorType authType) { - return java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction<>() { - public PasswordAuthentication run() { - if (logger.isLoggable(PlatformLogger.Level.FINEST)) { - logger.finest("Requesting Authentication: host =" + host + " url = " + url); - } - PasswordAuthentication pass = Authenticator.requestPasswordAuthentication( - authenticator, host, addr, port, protocol, - prompt, scheme, url, authType); - if (logger.isLoggable(PlatformLogger.Level.FINEST)) { - logger.finest("Authentication returned: " + (pass != null ? pass.toString() : "null")); - } - return pass; - } - }); + private static PasswordAuthentication requestPassword( + final Authenticator authenticator, + final String host, + final InetAddress addr, + final int port, + final String protocol, + final String prompt, + final String scheme, + final URL url, + final RequestorType authType) { + + if (logger.isLoggable(PlatformLogger.Level.FINEST)) { + logger.finest("Requesting Authentication: host =" + host + " url = " + url); + } + PasswordAuthentication pass = Authenticator.requestPasswordAuthentication( + authenticator, host, addr, port, protocol, + prompt, scheme, url, authType); + if (logger.isLoggable(PlatformLogger.Level.FINEST)) { + logger.finest("Authentication returned: " + (pass != null ? pass.toString() : "null")); + } + return pass; } private boolean isRestrictedHeader(String key, String value) { @@ -640,7 +609,6 @@ private void writeRequests() throws IOException { if (requestLineIndex != 0) { // we expect the request line to be at index 0. we set it here // if we don't find the request line at that index. - checkURLFile(); requests.prepend(requestLine, null); } if (!getUseCaches()) { @@ -654,9 +622,7 @@ private void writeRequests() throws IOException { host += ":" + String.valueOf(port); } String reqHost = requests.findValue("Host"); - if (reqHost == null || - (!reqHost.equalsIgnoreCase(host) && !checkSetHost())) - { + if (reqHost == null || !reqHost.equalsIgnoreCase(host)) { requests.set("Host", host); } requests.setIfNotSet("Accept", acceptString); @@ -776,47 +742,6 @@ private void writeRequests() throws IOException { } } - private boolean checkSetHost() { - @SuppressWarnings("removal") - SecurityManager s = System.getSecurityManager(); - if (s != null) { - String name = s.getClass().getName(); - if (name.equals("sun.plugin2.applet.AWTAppletSecurityManager") || - name.equals("sun.plugin2.applet.FXAppletSecurityManager") || - name.equals("com.sun.javaws.security.JavaWebStartSecurity") || - name.equals("sun.plugin.security.ActivatorSecurityManager")) - { - int CHECK_SET_HOST = -2; - try { - s.checkConnect(url.toExternalForm(), CHECK_SET_HOST); - } catch (SecurityException ex) { - return false; - } - } - } - return true; - } - - private void checkURLFile() { - @SuppressWarnings("removal") - SecurityManager s = System.getSecurityManager(); - if (s != null) { - String name = s.getClass().getName(); - if (name.equals("sun.plugin2.applet.AWTAppletSecurityManager") || - name.equals("sun.plugin2.applet.FXAppletSecurityManager") || - name.equals("com.sun.javaws.security.JavaWebStartSecurity") || - name.equals("sun.plugin.security.ActivatorSecurityManager")) - { - int CHECK_SUBPATH = -3; - try { - s.checkConnect(url.toExternalForm(), CHECK_SUBPATH); - } catch (SecurityException ex) { - throw new SecurityException("denied access outside a permitted URL subpath", ex); - } - } - } - } - /** * Create a new HttpClient object, bypassing the cache of * HTTP client objects/connections. @@ -922,7 +847,6 @@ private static URL checkURL(URL u) throws IOException { return u; } - @SuppressWarnings("removal") protected HttpURLConnection(URL u, Proxy p, Handler handler) throws IOException { super(checkURL(u)); @@ -931,119 +855,8 @@ protected HttpURLConnection(URL u, Proxy p, Handler handler) userHeaders = new MessageHeader(); this.handler = handler; instProxy = p; - if (instProxy instanceof sun.net.ApplicationProxy) { - /* Application set Proxies should not have access to cookies - * in a secure environment unless explicitly allowed. */ - try { - cookieHandler = CookieHandler.getDefault(); - } catch (SecurityException se) { /* swallow exception */ } - } else { - cookieHandler = java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction<>() { - public CookieHandler run() { - return CookieHandler.getDefault(); - } - }); - } - cacheHandler = java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction<>() { - public ResponseCache run() { - return ResponseCache.getDefault(); - } - }); - } - - /** - * opens a stream allowing redirects only to the same host. - */ - public static InputStream openConnectionCheckRedirects(URLConnection c) - throws IOException - { - boolean redir; - int redirects = 0; - InputStream in; - Authenticator a = null; - - do { - if (c instanceof HttpURLConnection) { - ((HttpURLConnection) c).setInstanceFollowRedirects(false); - if (a == null) { - a = ((HttpURLConnection) c).authenticator; - } - } - - // We want to open the input stream before - // getting headers, because getHeaderField() - // et al swallow IOExceptions. - in = c.getInputStream(); - redir = false; - - if (c instanceof HttpURLConnection) { - HttpURLConnection http = (HttpURLConnection) c; - int stat = http.getResponseCode(); - if (stat >= 300 && stat <= 307 && stat != 306 && - stat != HttpURLConnection.HTTP_NOT_MODIFIED) { - URL base = http.getURL(); - String loc = http.getHeaderField("Location"); - URL target = null; - if (loc != null) { - target = newURL(base, loc); - } - http.disconnect(); - if (target == null - || !base.getProtocol().equals(target.getProtocol()) - || base.getPort() != target.getPort() - || !hostsEqual(base, target) - || redirects >= 5) - { - throw new SecurityException("illegal URL redirect"); - } - redir = true; - c = target.openConnection(); - if (a != null && c instanceof HttpURLConnection) { - ((HttpURLConnection)c).setAuthenticator(a); - } - redirects++; - } - } - } while (redir); - return in; - } - - - // - // Same as java.net.URL.hostsEqual - // - @SuppressWarnings("removal") - private static boolean hostsEqual(URL u1, URL u2) { - final String h1 = u1.getHost(); - final String h2 = u2.getHost(); - - if (h1 == null) { - return h2 == null; - } else if (h2 == null) { - return false; - } else if (h1.equalsIgnoreCase(h2)) { - return true; - } - // Have to resolve addresses before comparing, otherwise - // names like tachyon and tachyon.eng would compare different - final boolean result[] = {false}; - - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction<>() { - public Void run() { - try { - InetAddress a1 = InetAddress.getByName(h1); - InetAddress a2 = InetAddress.getByName(h2); - result[0] = a1.equals(a2); - } catch(UnknownHostException | SecurityException e) { - } - return null; - } - }); - - return result[0]; + cookieHandler = CookieHandler.getDefault(); + cacheHandler = ResponseCache.getDefault(); } // overridden in HTTPS subclass @@ -1073,34 +886,6 @@ private boolean checkReuseConnection () { return false; } - @SuppressWarnings("removal") - private String getHostAndPort(URL url) { - String host = url.getHost(); - final String hostarg = host; - try { - // lookup hostname and use IP address if available - host = AccessController.doPrivileged( - new PrivilegedExceptionAction<>() { - public String run() throws IOException { - InetAddress addr = InetAddress.getByName(hostarg); - return addr.getHostAddress(); - } - } - ); - } catch (PrivilegedActionException e) {} - int port = url.getPort(); - if (port == -1) { - String scheme = url.getProtocol(); - if ("http".equals(scheme)) { - return host + ":80"; - } else { // scheme must be https - return host + ":443"; - } - } - return host + ":" + Integer.toString(port); - } - - @SuppressWarnings("removal") protected void plainConnect() throws IOException { lock(); try { @@ -1110,66 +895,7 @@ protected void plainConnect() throws IOException { } finally { unlock(); } - SocketPermission p = URLtoSocketPermission(this.url); - if (p != null) { - try { - AccessController.doPrivilegedWithCombiner( - new PrivilegedExceptionAction<>() { - public Void run() throws IOException { - plainConnect0(); - return null; - } - }, null, p - ); - } catch (PrivilegedActionException e) { - throw (IOException) e.getException(); - } - } else { - // run without additional permission - plainConnect0(); - } - } - - /** - * if the caller has a URLPermission for connecting to the - * given URL, then return a SocketPermission which permits - * access to that destination. Return null otherwise. The permission - * is cached in a field (which can only be changed by redirects) - */ - SocketPermission URLtoSocketPermission(URL url) throws IOException { - - if (socketPermission != null) { - return socketPermission; - } - - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - - if (sm == null) { - return null; - } - - // the permission, which we might grant - - SocketPermission newPerm = new SocketPermission( - getHostAndPort(url), "connect" - ); - - String actions = getRequestMethod()+":" + - getUserSetHeaders().getHeaderNamesInList(); - - String urlstring = url.getProtocol() + "://" + url.getAuthority() - + url.getPath(); - - URLPermission p = new URLPermission(urlstring, actions); - try { - sm.checkPermission(p); - socketPermission = newPerm; - return socketPermission; - } catch (SecurityException e) { - // fall thru - } - return null; + plainConnect0(); } protected void plainConnect0() throws IOException { @@ -1215,14 +941,7 @@ protected void plainConnect0() throws IOException { /** * Do we have to use a proxy? */ - @SuppressWarnings("removal") - ProxySelector sel = - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction<>() { - public ProxySelector run() { - return ProxySelector.getDefault(); - } - }); + final ProxySelector sel = ProxySelector.getDefault(); if (sel != null) { URI uri = sun.net.www.ParseUtil.toURI(url); if (logger.isLoggable(PlatformLogger.Level.FINEST)) { @@ -1399,29 +1118,12 @@ private void expect100Continue() throws IOException { * - get input, [read input,] get output, [write output] */ - @SuppressWarnings("removal") @Override public OutputStream getOutputStream() throws IOException { lock(); try { connecting = true; - SocketPermission p = URLtoSocketPermission(this.url); - - if (p != null) { - try { - return AccessController.doPrivilegedWithCombiner( - new PrivilegedExceptionAction<>() { - public OutputStream run() throws IOException { - return getOutputStream0(); - } - }, null, p - ); - } catch (PrivilegedActionException e) { - throw (IOException) e.getException(); - } - } else { - return getOutputStream0(); - } + return getOutputStream0(); } finally { unlock(); } @@ -1591,29 +1293,12 @@ private void setCookieHeader() throws IOException { } // end of getting cookies } - @SuppressWarnings("removal") @Override public InputStream getInputStream() throws IOException { lock(); try { connecting = true; - SocketPermission p = URLtoSocketPermission(this.url); - - if (p != null) { - try { - return AccessController.doPrivilegedWithCombiner( - new PrivilegedExceptionAction<>() { - public InputStream run() throws IOException { - return getInputStream0(); - } - }, null, p - ); - } catch (PrivilegedActionException e) { - throw (IOException) e.getException(); - } - } else { - return getInputStream0(); - } + return getInputStream0(); } finally { unlock(); } @@ -2060,17 +1745,9 @@ private InputStream getInputStream0() throws IOException { private IOException getChainedException(final IOException rememberedException) { try { final Object[] args = { rememberedException.getMessage() }; - @SuppressWarnings("removal") - IOException chainedException = - java.security.AccessController.doPrivileged( - new java.security.PrivilegedExceptionAction<>() { - public IOException run() throws Exception { - return (IOException) - rememberedException.getClass() - .getConstructor(new Class[] { String.class }) - .newInstance(args); - } - }); + IOException chainedException = rememberedException.getClass() + .getConstructor(new Class[] { String.class }) + .newInstance(args); chainedException.initCause(rememberedException); return chainedException; } catch (Exception ignored) { @@ -2392,7 +2069,7 @@ private void setPreemptiveProxyAuthentication(MessageHeader requests) throws IOE * Gets the authentication for an HTTP proxy, and applies it to * the connection. */ - @SuppressWarnings({"removal","fallthrough"}) + @SuppressWarnings("fallthrough") private AuthenticationInfo getHttpProxyAuthentication(AuthenticationHeader authhdr) throws IOException { @@ -2430,44 +2107,40 @@ private AuthenticationInfo getHttpProxyAuthentication(AuthenticationHeader authh proxyAuthKey = AuthenticationInfo.getProxyAuthKey(host, port, realm, authScheme); ret = AuthenticationInfo.getProxyAuth(proxyAuthKey, authCache); if (ret == null) { - switch (authScheme) { - case BASIC: - InetAddress addr = null; - try { - final String finalHost = host; - addr = java.security.AccessController.doPrivileged( - new java.security.PrivilegedExceptionAction<>() { - public InetAddress run() - throws java.net.UnknownHostException { - return InetAddress.getByName(finalHost); - } - }); - } catch (java.security.PrivilegedActionException ignored) { - // User will have an unknown host. - } - PasswordAuthentication a = - privilegedRequestPasswordAuthentication( - authenticator, - host, addr, port, "http", - realm, scheme, url, RequestorType.PROXY); - if (a != null) { - ret = new BasicAuthentication(true, host, port, realm, a, isUTF8); + ret = switch (authScheme) { + case BASIC -> { + InetAddress addr = null; + try { + addr = InetAddress.getByName(host); + } catch (UnknownHostException uhe) { + // Ignore the exception. The Authenticator instance will + // be passed a null InetAddress when requesting a password from the + // Authenticator. + } + final PasswordAuthentication a = requestPassword(authenticator, + host, addr, port, "http", + realm, scheme, url, RequestorType.PROXY); + if (a != null) { + yield new BasicAuthentication(true, host, port, realm, a, isUTF8); + } + yield null; } - break; - case DIGEST: - a = privilegedRequestPasswordAuthentication( - authenticator, - host, null, port, url.getProtocol(), - realm, scheme, url, RequestorType.PROXY); - if (a != null) { - DigestAuthentication.Parameters params = - new DigestAuthentication.Parameters(); - ret = new DigestAuthentication(true, host, port, realm, - scheme, a, params); + case DIGEST -> { + final PasswordAuthentication a = requestPassword(authenticator, + host, null, port, url.getProtocol(), + realm, scheme, url, RequestorType.PROXY); + if (a != null) { + DigestAuthentication.Parameters params = + new DigestAuthentication.Parameters(); + yield new DigestAuthentication(true, host, port, realm, + scheme, a, params); + } + yield null; } - break; - case NTLM: - if (NTLMAuthenticationProxy.supported) { + case NTLM -> { + if (!NTLMAuthenticationProxy.supported) { + yield null; + } /* tryTransparentNTLMProxy will always be true the first * time around, but verify that the platform supports it * otherwise don't try. */ @@ -2484,14 +2157,14 @@ public InetAddress run() } } - a = null; + PasswordAuthentication a = null; if (tryTransparentNTLMProxy) { logger.finest("Trying Transparent NTLM authentication"); } else { - a = privilegedRequestPasswordAuthentication( - authenticator, - host, null, port, url.getProtocol(), - "", scheme, url, RequestorType.PROXY); + a = requestPassword( + authenticator, + host, null, port, url.getProtocol(), + "", scheme, url, RequestorType.PROXY); validateNTLMCredentials(a); } /* If we are not trying transparent authentication then @@ -2500,29 +2173,27 @@ public InetAddress run() * and password will be picked up from the current logged * on users credentials. */ + AuthenticationInfo authInfo = null; if (tryTransparentNTLMProxy || - (!tryTransparentNTLMProxy && a != null)) { - ret = NTLMAuthenticationProxy.proxy.create(true, host, port, a); + (!tryTransparentNTLMProxy && a != null)) { + authInfo = NTLMAuthenticationProxy.proxy.create(true, host, port, a); } /* set to false so that we do not try again */ tryTransparentNTLMProxy = false; + yield authInfo; } - break; - case NEGOTIATE: - ret = new NegotiateAuthentication(new HttpCallerInfo(authhdr.getHttpCallerInfo(), "Negotiate")); - break; - case KERBEROS: - ret = new NegotiateAuthentication(new HttpCallerInfo(authhdr.getHttpCallerInfo(), "Kerberos")); - break; - case UNKNOWN: - if (logger.isLoggable(PlatformLogger.Level.FINEST)) { - logger.finest("Unknown/Unsupported authentication scheme: " + scheme); + case NEGOTIATE -> + new NegotiateAuthentication(new HttpCallerInfo(authhdr.getHttpCallerInfo(), "Negotiate")); + case KERBEROS -> + new NegotiateAuthentication(new HttpCallerInfo(authhdr.getHttpCallerInfo(), "Kerberos")); + case UNKNOWN -> { + if (logger.isLoggable(PlatformLogger.Level.FINEST)) { + logger.finest("Unknown/Unsupported authentication scheme: " + scheme); + } + yield null; } - /*fall through*/ - default: - throw new AssertionError("should not reach here"); - } + }; } if (ret != null) { if (!ret.setHeaders(this, p, raw)) { @@ -2604,7 +2275,7 @@ private AuthenticationInfo getServerAuthentication(AuthenticationHeader authhdr) break; case BASIC: PasswordAuthentication a = - privilegedRequestPasswordAuthentication( + requestPassword( authenticator, url.getHost(), addr, port, url.getProtocol(), realm, scheme, url, RequestorType.SERVER); @@ -2613,7 +2284,7 @@ private AuthenticationInfo getServerAuthentication(AuthenticationHeader authhdr) } break; case DIGEST: - a = privilegedRequestPasswordAuthentication( + a = requestPassword( authenticator, url.getHost(), addr, port, url.getProtocol(), realm, scheme, url, RequestorType.SERVER); @@ -2650,7 +2321,7 @@ private AuthenticationInfo getServerAuthentication(AuthenticationHeader authhdr) if (tryTransparentNTLMServer) { logger.finest("Trying Transparent NTLM authentication"); } else { - a = privilegedRequestPasswordAuthentication( + a = requestPassword( authenticator, url.getHost(), addr, port, url.getProtocol(), "", scheme, url, RequestorType.SERVER); @@ -2753,7 +2424,6 @@ String getRequestURI() throws IOException { * resets the url, re-connects, and resets the request * property. */ - @SuppressWarnings("removal") private boolean followRedirect() throws IOException { if (!getInstanceFollowRedirects()) { return false; @@ -2783,27 +2453,7 @@ private boolean followRedirect() throws IOException { // treat loc as a relative URI to conform to popular browsers locUrl = newURL(url, loc); } - - final URL locUrl0 = locUrl; - socketPermission = null; // force recalculation - SocketPermission p = URLtoSocketPermission(locUrl); - - if (p != null) { - try { - return AccessController.doPrivilegedWithCombiner( - new PrivilegedExceptionAction<>() { - public Boolean run() throws IOException { - return followRedirect0(loc, stat, locUrl0); - } - }, null, p - ); - } catch (PrivilegedActionException e) { - throw (IOException) e.getException(); - } - } else { - // run without additional permission - return followRedirect0(loc, stat, locUrl); - } + return followRedirect0(loc, stat, locUrl); } /* Tells us whether to follow a redirect. If so, it @@ -2838,12 +2488,6 @@ private boolean followRedirect0(String loc, int stat, URL locUrl) String proxyHost = locUrl.getHost(); int proxyPort = locUrl.getPort(); - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); - if (security != null) { - security.checkConnect(proxyHost, proxyPort); - } - setProxiedClient (url, proxyHost, proxyPort); requests.set(0, method + " " + getRequestURI()+" " + httpVersion, null); diff --git a/src/java.base/share/classes/sun/net/www/protocol/http/NegotiateAuthentication.java b/src/java.base/share/classes/sun/net/www/protocol/http/NegotiateAuthentication.java index 27442382ec72d..c27d866f5eff0 100644 --- a/src/java.base/share/classes/sun/net/www/protocol/http/NegotiateAuthentication.java +++ b/src/java.base/share/classes/sun/net/www/protocol/http/NegotiateAuthentication.java @@ -36,7 +36,6 @@ import sun.net.www.HeaderParser; import static sun.net.www.protocol.http.AuthScheme.NEGOTIATE; import static sun.net.www.protocol.http.AuthScheme.KERBEROS; -import sun.security.action.GetPropertyAction; /** * NegotiateAuthentication: @@ -45,10 +44,7 @@ * @since 1.6 */ -class NegotiateAuthentication extends AuthenticationInfo { - - @java.io.Serial - private static final long serialVersionUID = 100L; +final class NegotiateAuthentication extends AuthenticationInfo { private final HttpCallerInfo hci; @@ -61,14 +57,6 @@ class NegotiateAuthentication extends AuthenticationInfo { static ThreadLocal > cache = null; private static final ReentrantLock negotiateLock = new ReentrantLock(); - /* Whether cache is enabled for Negotiate/Kerberos */ - private static final boolean cacheSPNEGO; - static { - String spnegoCacheProp = - GetPropertyAction.privilegedGetProperty("jdk.spnego.cache", "true"); - cacheSPNEGO = Boolean.parseBoolean(spnegoCacheProp); - } - // The HTTP Negotiate Helper private Negotiator negotiator = null; diff --git a/src/java.base/share/classes/sun/net/www/protocol/https/HttpsClient.java b/src/java.base/share/classes/sun/net/www/protocol/https/HttpsClient.java index 9bc28a353ab65..fb2dfe6fff311 100644 --- a/src/java.base/share/classes/sun/net/www/protocol/https/HttpsClient.java +++ b/src/java.base/share/classes/sun/net/www/protocol/https/HttpsClient.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2024, 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 @@ -30,7 +30,6 @@ import java.io.UnsupportedEncodingException; import java.io.PrintStream; import java.io.BufferedOutputStream; -import java.net.InetAddress; import java.net.Socket; import java.net.SocketException; import java.net.URL; @@ -48,7 +47,6 @@ import sun.net.www.http.HttpClient; import sun.net.www.protocol.http.AuthCacheImpl; import sun.net.www.protocol.http.HttpURLConnection; -import sun.security.action.*; import sun.security.util.HostnameChecker; import sun.security.ssl.SSLSocketImpl; @@ -138,10 +136,8 @@ final class HttpsClient extends HttpClient // // If ciphers are assigned, sort them into an array. // - String ciphers []; - String cipherString = - GetPropertyAction.privilegedGetProperty("https.cipherSuites"); - + String[] ciphers; + String cipherString = System.getProperty("https.cipherSuites"); if (cipherString == null || cipherString.isEmpty()) { ciphers = null; } else { @@ -162,10 +158,8 @@ final class HttpsClient extends HttpClient // // If protocols are assigned, sort them into an array. // - String protocols []; - String protocolString = - GetPropertyAction.privilegedGetProperty("https.protocols"); - + String[] protocols; + String protocolString = System.getProperty("https.protocols"); if (protocolString == null || protocolString.isEmpty()) { protocols = null; } else { @@ -183,65 +177,12 @@ final class HttpsClient extends HttpClient return protocols; } - private String getUserAgent() { - String userAgent = - GetPropertyAction.privilegedGetProperty("https.agent"); - if (userAgent == null || userAgent.isEmpty()) { - userAgent = "JSSE"; - } - return userAgent; - } - // CONSTRUCTOR, FACTORY - - /** - * Create an HTTPS client URL. Traffic will be tunneled through any - * intermediate nodes rather than proxied, so that confidentiality - * of data exchanged can be preserved. However, note that all the - * anonymous SSL flavors are subject to "person-in-the-middle" - * attacks against confidentiality. If you enable use of those - * flavors, you may be giving up the protection you get through - * SSL tunneling. - * - * Use New to get new HttpsClient. This constructor is meant to be - * used only by New method. New properly checks for URL spoofing. - * - * @param url https URL with which a connection must be established - */ - private HttpsClient(SSLSocketFactory sf, URL url) - throws IOException - { - // HttpClient-level proxying is always disabled, - // because we override doConnect to do tunneling instead. - this(sf, url, (String)null, -1); - } - /** - * Create an HTTPS client URL. Traffic will be tunneled through - * the specified proxy server. - */ - HttpsClient(SSLSocketFactory sf, URL url, String proxyHost, int proxyPort) - throws IOException { - this(sf, url, proxyHost, proxyPort, -1); - } - - /** - * Create an HTTPS client URL. Traffic will be tunneled through + * Create an HTTPS client URL. Traffic will be tunneled through * the specified proxy server, with a connect timeout */ - HttpsClient(SSLSocketFactory sf, URL url, String proxyHost, int proxyPort, - int connectTimeout) - throws IOException { - this(sf, url, - (proxyHost == null? null: - HttpClient.newHttpProxy(proxyHost, proxyPort, "https")), - connectTimeout); - } - - /** - * Same as previous constructor except using a Proxy - */ HttpsClient(SSLSocketFactory sf, URL url, Proxy proxy, int connectTimeout) throws IOException { @@ -268,37 +209,6 @@ private HttpsClient(SSLSocketFactory sf, URL url) // This code largely ripped off from HttpClient.New, and // it uses the same keepalive cache. - static HttpClient New(SSLSocketFactory sf, URL url, HostnameVerifier hv, - HttpURLConnection httpuc) - throws IOException { - return HttpsClient.New(sf, url, hv, true, httpuc); - } - - /** See HttpClient for the model for this method. */ - static HttpClient New(SSLSocketFactory sf, URL url, - HostnameVerifier hv, boolean useCache, - HttpURLConnection httpuc) throws IOException { - return HttpsClient.New(sf, url, hv, (String)null, -1, useCache, httpuc); - } - - /** - * Get a HTTPS client to the URL. Traffic will be tunneled through - * the specified proxy server. - */ - static HttpClient New(SSLSocketFactory sf, URL url, HostnameVerifier hv, - String proxyHost, int proxyPort, - HttpURLConnection httpuc) throws IOException { - return HttpsClient.New(sf, url, hv, proxyHost, proxyPort, true, httpuc); - } - - static HttpClient New(SSLSocketFactory sf, URL url, HostnameVerifier hv, - String proxyHost, int proxyPort, boolean useCache, - HttpURLConnection httpuc) - throws IOException { - return HttpsClient.New(sf, url, hv, proxyHost, proxyPort, useCache, -1, - httpuc); - } - static HttpClient New(SSLSocketFactory sf, URL url, HostnameVerifier hv, String proxyHost, int proxyPort, boolean useCache, int connectTimeout, HttpURLConnection httpuc) @@ -379,15 +289,6 @@ static HttpClient New(SSLSocketFactory sf, URL url, HostnameVerifier hv, ret.authcache = httpuc.getAuthCache(); } } else { - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); - if (security != null) { - if (ret.proxy == Proxy.NO_PROXY || ret.proxy == null) { - security.checkConnect(InetAddress.getByName(url.getHost()).getHostAddress(), url.getPort()); - } else { - security.checkConnect(url.getHost(), url.getPort()); - } - } ret.url = url; } ret.setHostnameVerifier(hv); @@ -395,22 +296,17 @@ static HttpClient New(SSLSocketFactory sf, URL url, HostnameVerifier hv, return ret; } - // METHODS - void setHostnameVerifier(HostnameVerifier hv) { + private void setHostnameVerifier(HostnameVerifier hv) { this.hv = hv; } - void setSSLSocketFactory(SSLSocketFactory sf) { + private void setSSLSocketFactory(SSLSocketFactory sf) { sslSocketFactory = sf; } - SSLSocketFactory getSSLSocketFactory() { - return sslSocketFactory; - } - /** * The following method, createSocket, is defined in NetworkClient - * and overridden here so that the socket facroty is used to create + * and overridden here so that the socket factory is used to create * new sockets. */ @Override diff --git a/src/java.base/unix/classes/sun/net/www/protocol/http/ntlm/NTLMAuthentication.java b/src/java.base/unix/classes/sun/net/www/protocol/http/ntlm/NTLMAuthentication.java index 8a2944081d534..c034cd4dcd7ec 100644 --- a/src/java.base/unix/classes/sun/net/www/protocol/http/ntlm/NTLMAuthentication.java +++ b/src/java.base/unix/classes/sun/net/www/protocol/http/ntlm/NTLMAuthentication.java @@ -35,7 +35,6 @@ import java.security.GeneralSecurityException; import java.util.Base64; import java.util.Locale; -import java.util.Objects; import java.util.Properties; import sun.net.www.HeaderParser; @@ -70,8 +69,7 @@ * through a proxy, rather between client and proxy, or between client and server (with no proxy) */ -public class NTLMAuthentication extends AuthenticationInfo { - private static final long serialVersionUID = 170L; +public final class NTLMAuthentication extends AuthenticationInfo { private static final NTLMAuthenticationCallback NTLMAuthCallback = NTLMAuthenticationCallback.getNTLMAuthenticationCallback(); diff --git a/src/java.base/windows/classes/sun/net/www/protocol/http/ntlm/NTLMAuthentication.java b/src/java.base/windows/classes/sun/net/www/protocol/http/ntlm/NTLMAuthentication.java index d3b60daad7440..a7056082e1291 100644 --- a/src/java.base/windows/classes/sun/net/www/protocol/http/ntlm/NTLMAuthentication.java +++ b/src/java.base/windows/classes/sun/net/www/protocol/http/ntlm/NTLMAuthentication.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2024, 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 @@ -31,14 +31,11 @@ import java.net.UnknownHostException; import java.net.URL; import java.util.Locale; -import java.util.Objects; -import java.util.Properties; import sun.net.NetProperties; import sun.net.www.HeaderParser; import sun.net.www.protocol.http.AuthenticationInfo; import sun.net.www.protocol.http.AuthScheme; import sun.net.www.protocol.http.HttpURLConnection; -import sun.security.action.GetPropertyAction; /** * NTLMAuthentication: @@ -46,14 +43,11 @@ * @author Michael McMahon */ -public class NTLMAuthentication extends AuthenticationInfo { - - private static final long serialVersionUID = 100L; +public final class NTLMAuthentication extends AuthenticationInfo { private static final NTLMAuthenticationCallback NTLMAuthCallback = - NTLMAuthenticationCallback.getNTLMAuthenticationCallback(); + NTLMAuthenticationCallback.getNTLMAuthenticationCallback(); - private String hostname; /* Domain to use if not specified by user */ private static final String defaultDomain; /* Whether cache is enabled for NTLM */ @@ -68,18 +62,10 @@ enum TransparentAuth { private static final TransparentAuth authMode; static { - Properties props = GetPropertyAction.privilegedGetProperties(); - defaultDomain = props.getProperty("http.auth.ntlm.domain", "domain"); - String ntlmCacheProp = props.getProperty("jdk.ntlm.cache", "true"); + defaultDomain = System.getProperty("http.auth.ntlm.domain", "domain"); + String ntlmCacheProp = System.getProperty("jdk.ntlm.cache", "true"); ntlmCache = Boolean.parseBoolean(ntlmCacheProp); - @SuppressWarnings("removal") - String modeProp = java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public String run() { - return NetProperties.get("jdk.http.ntlm.transparentAuth"); - } - }); - + String modeProp = NetProperties.get("jdk.http.ntlm.transparentAuth"); if ("trustedHosts".equalsIgnoreCase(modeProp)) authMode = TransparentAuth.TRUSTED_HOSTS; else if ("allHosts".equalsIgnoreCase(modeProp)) @@ -88,27 +74,6 @@ else if ("allHosts".equalsIgnoreCase(modeProp)) authMode = TransparentAuth.DISABLED; } - @SuppressWarnings("removal") - private void init0() { - - hostname = java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public String run() { - String localhost; - try { - localhost = InetAddress.getLocalHost().getHostName().toUpperCase(Locale.ROOT); - } catch (UnknownHostException e) { - localhost = "localhost"; - } - return localhost; - } - }); - int x = hostname.indexOf ('.'); - if (x != -1) { - hostname = hostname.substring (0, x); - } - } - String username; String ntdomain; String password; @@ -147,7 +112,6 @@ private void init (PasswordAuthentication pw) { ntdomain = null; password = null; } - init0(); } /** From db7ee3dad1d9c9578794d946dd5de1f51d77e5a1 Mon Sep 17 00:00:00 2001 From: Jaikiran Pai Date: Wed, 20 Nov 2024 12:41:39 +0000 Subject: [PATCH 43/74] 8344223: Remove calls to SecurityManager and doPrivileged in java.net.URLClassLoader after JEP 486 integration Reviewed-by: alanb, yzheng --- .../classes/java/net/URLClassLoader.java | 197 ++---------- .../internal/loader/BuiltinClassLoader.java | 23 +- .../jdk/internal/loader/URLClassPath.java | 289 +++++------------- 3 files changed, 112 insertions(+), 397 deletions(-) diff --git a/src/java.base/share/classes/java/net/URLClassLoader.java b/src/java.base/share/classes/java/net/URLClassLoader.java index 4d43d358a641a..d867b7e2b62e3 100644 --- a/src/java.base/share/classes/java/net/URLClassLoader.java +++ b/src/java.base/share/classes/java/net/URLClassLoader.java @@ -30,14 +30,10 @@ import java.io.FilePermission; import java.io.IOException; import java.io.InputStream; -import java.security.AccessControlContext; -import java.security.AccessController; import java.security.CodeSigner; import java.security.CodeSource; import java.security.Permission; import java.security.PermissionCollection; -import java.security.PrivilegedAction; -import java.security.PrivilegedExceptionAction; import java.security.SecureClassLoader; import java.util.Enumeration; import java.util.List; @@ -76,10 +72,6 @@ public class URLClassLoader extends SecureClassLoader implements Closeable { /* The search path for classes and resources */ private final URLClassPath ucp; - /* The context to be used when loading classes and resources */ - @SuppressWarnings("removal") - private final AccessControlContext acc; - /** * Constructs a new URLClassLoader for the given URLs. The URLs will be * searched in the order specified for classes and resources after first @@ -94,18 +86,9 @@ public class URLClassLoader extends SecureClassLoader implements Closeable { * @throws NullPointerException if {@code urls} or any of its * elements is {@code null}. */ - @SuppressWarnings("removal") public URLClassLoader(URL[] urls, ClassLoader parent) { super(parent); - this.acc = AccessController.getContext(); - this.ucp = new URLClassPath(urls, acc); - } - - URLClassLoader(String name, URL[] urls, ClassLoader parent, - @SuppressWarnings("removal") AccessControlContext acc) { - super(name, parent); - this.acc = acc; - this.ucp = new URLClassPath(urls, acc); + this.ucp = new URLClassPath(urls); } /** @@ -122,17 +105,9 @@ public URLClassLoader(URL[] urls, ClassLoader parent) { * @throws NullPointerException if {@code urls} or any of its * elements is {@code null}. */ - @SuppressWarnings("removal") public URLClassLoader(URL[] urls) { super(); - this.acc = AccessController.getContext(); - this.ucp = new URLClassPath(urls, acc); - } - - URLClassLoader(URL[] urls, @SuppressWarnings("removal") AccessControlContext acc) { - super(); - this.acc = acc; - this.ucp = new URLClassPath(urls, acc); + this.ucp = new URLClassPath(urls); } /** @@ -149,12 +124,10 @@ public URLClassLoader(URL[] urls) { * @throws NullPointerException if {@code urls} or any of its * elements is {@code null}. */ - @SuppressWarnings("removal") public URLClassLoader(URL[] urls, ClassLoader parent, URLStreamHandlerFactory factory) { super(parent); - this.acc = AccessController.getContext(); - this.ucp = new URLClassPath(urls, factory, acc); + this.ucp = new URLClassPath(urls, factory); } @@ -176,13 +149,11 @@ public URLClassLoader(URL[] urls, ClassLoader parent, * * @since 9 */ - @SuppressWarnings("removal") public URLClassLoader(String name, URL[] urls, ClassLoader parent) { super(name, parent); - this.acc = AccessController.getContext(); - this.ucp = new URLClassPath(urls, acc); + this.ucp = new URLClassPath(urls); } /** @@ -203,12 +174,10 @@ public URLClassLoader(String name, * * @since 9 */ - @SuppressWarnings("removal") public URLClassLoader(String name, URL[] urls, ClassLoader parent, URLStreamHandlerFactory factory) { super(name, parent); - this.acc = AccessController.getContext(); - this.ucp = new URLClassPath(urls, factory, acc); + this.ucp = new URLClassPath(urls, factory); } /* A map (used as a set) to keep track of closeable local resources @@ -299,11 +268,6 @@ public InputStream getResourceAsStream(String name) { * @since 1.7 */ public void close() throws IOException { - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); - if (security != null) { - security.checkPermission(new RuntimePermission("closeClassLoader")); - } List errors = ucp.closeLoaders(); // now close any remaining streams. @@ -369,40 +333,24 @@ public URL[] getURLs() { * or if the loader is closed. * @throws NullPointerException if {@code name} is {@code null}. */ - @SuppressWarnings("removal") protected Class findClass(final String name) throws ClassNotFoundException { - final Class result; - try { - result = AccessController.doPrivileged( - new PrivilegedExceptionAction<>() { - public Class run() throws ClassNotFoundException { - String path = name.replace('.', '/').concat(".class"); - Resource res = ucp.getResource(path, false); - if (res != null) { - try { - return defineClass(name, res); - } catch (IOException e) { - throw new ClassNotFoundException(name, e); - } catch (ClassFormatError e2) { - if (res.getDataError() != null) { - e2.addSuppressed(res.getDataError()); - } - throw e2; - } - } else { - return null; - } - } - }, acc); - } catch (java.security.PrivilegedActionException pae) { - throw (ClassNotFoundException) pae.getException(); - } - if (result == null) { - throw new ClassNotFoundException(name); + String path = name.replace('.', '/').concat(".class"); + Resource res = ucp.getResource(path); + if (res != null) { + try { + return defineClass(name, res); + } catch (IOException e) { + throw new ClassNotFoundException(name, e); + } catch (ClassFormatError e2) { + if (res.getDataError() != null) { + e2.addSuppressed(res.getDataError()); + } + throw e2; + } } - return result; + throw new ClassNotFoundException(name); } /* @@ -575,18 +523,7 @@ private boolean isSealed(String name, Manifest man) { * if the resource could not be found, or if the loader is closed. */ public URL findResource(final String name) { - /* - * The same restriction to finding classes applies to resources - */ - @SuppressWarnings("removal") - URL url = AccessController.doPrivileged( - new PrivilegedAction<>() { - public URL run() { - return ucp.findResource(name, true); - } - }, acc); - - return url != null ? URLClassPath.checkURL(url) : null; + return ucp.findResource(name); } /** @@ -598,10 +535,11 @@ public URL run() { * @return An {@code Enumeration} of {@code URL}s. * If the loader is closed, the Enumeration contains no elements. */ + @Override public Enumeration findResources(final String name) throws IOException { - final Enumeration e = ucp.findResources(name, true); + final Enumeration e = ucp.findResources(name); return new Enumeration<>() { private URL url = null; @@ -610,23 +548,14 @@ private boolean next() { if (url != null) { return true; } - do { - @SuppressWarnings("removal") - URL u = AccessController.doPrivileged( - new PrivilegedAction<>() { - public URL run() { - if (!e.hasMoreElements()) - return null; - return e.nextElement(); - } - }, acc); - if (u == null) - break; - url = URLClassPath.checkURL(u); - } while (url == null); + if (!e.hasMoreElements()) { + return false; + } + url = e.nextElement(); return url != null; } + @Override public URL nextElement() { if (!next()) { throw new NoSuchElementException(); @@ -636,6 +565,7 @@ public URL nextElement() { return u; } + @Override public boolean hasMoreElements() { return next(); } @@ -666,7 +596,6 @@ public boolean hasMoreElements() { * @throws NullPointerException if {@code codesource} is {@code null}. * @return the permissions for the codesource */ - @SuppressWarnings("removal") protected PermissionCollection getPermissions(CodeSource codesource) { PermissionCollection perms = super.getPermissions(codesource); @@ -712,23 +641,13 @@ protected PermissionCollection getPermissions(CodeSource codesource) String host = locUrl.getHost(); if (host != null && !host.isEmpty()) p = new SocketPermission(host, - SecurityConstants.SOCKET_CONNECT_ACCEPT_ACTION); + SecurityConstants.SOCKET_CONNECT_ACCEPT_ACTION); } // make sure the person that created this class loader // would have this permission if (p != null) { - final SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - final Permission fp = p; - AccessController.doPrivileged(new PrivilegedAction<>() { - public Void run() throws SecurityException { - sm.checkPermission(fp); - return null; - } - }, acc); - } perms.add(p); } return perms; @@ -746,18 +665,7 @@ public Void run() throws SecurityException { */ public static URLClassLoader newInstance(final URL[] urls, final ClassLoader parent) { - // Save the caller's context - @SuppressWarnings("removal") - final AccessControlContext acc = AccessController.getContext(); - // Need a privileged block to create the class loader - @SuppressWarnings("removal") - URLClassLoader ucl = AccessController.doPrivileged( - new PrivilegedAction<>() { - public URLClassLoader run() { - return new FactoryURLClassLoader(null, urls, parent, acc); - } - }); - return ucl; + return new URLClassLoader(null, urls, parent); } /** @@ -770,53 +678,10 @@ public URLClassLoader run() { * @return the resulting class loader */ public static URLClassLoader newInstance(final URL[] urls) { - // Save the caller's context - @SuppressWarnings("removal") - final AccessControlContext acc = AccessController.getContext(); - // Need a privileged block to create the class loader - @SuppressWarnings("removal") - URLClassLoader ucl = AccessController.doPrivileged( - new PrivilegedAction<>() { - public URLClassLoader run() { - return new FactoryURLClassLoader(urls, acc); - } - }); - return ucl; + return new URLClassLoader(urls); } static { ClassLoader.registerAsParallelCapable(); } } - -final class FactoryURLClassLoader extends URLClassLoader { - - static { - ClassLoader.registerAsParallelCapable(); - } - - FactoryURLClassLoader(String name, URL[] urls, ClassLoader parent, - @SuppressWarnings("removal") AccessControlContext acc) { - super(name, urls, parent, acc); - } - - FactoryURLClassLoader(URL[] urls, @SuppressWarnings("removal") AccessControlContext acc) { - super(urls, acc); - } - - public final Class loadClass(String name, boolean resolve) - throws ClassNotFoundException - { - // First check if we have permission to access the package. This - // should go away once we've added support for exported packages. - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - int i = name.lastIndexOf('.'); - if (i != -1) { - sm.checkPackageAccess(name.substring(0, i)); - } - } - return super.loadClass(name, resolve); - } -} diff --git a/src/java.base/share/classes/jdk/internal/loader/BuiltinClassLoader.java b/src/java.base/share/classes/jdk/internal/loader/BuiltinClassLoader.java index ddf35a88d0ab0..f6cc79fd1277d 100644 --- a/src/java.base/share/classes/jdk/internal/loader/BuiltinClassLoader.java +++ b/src/java.base/share/classes/jdk/internal/loader/BuiltinClassLoader.java @@ -315,7 +315,7 @@ public URL findResource(String name) { if (module.loader() == this) { URL url; try { - url = findResource(module.name(), name); // checks URL + url = findResource(module.name(), name); } catch (IOException ioe) { return null; } @@ -355,7 +355,7 @@ public URL findResource(String name) { */ @Override public Enumeration findResources(String name) throws IOException { - List checked = new ArrayList<>(); // list of checked URLs + List resources = new ArrayList<>(); // list of resource URLs String pn = Resources.toPackageName(name); LoadedModule module = packageToModule.get(pn); @@ -363,12 +363,12 @@ public Enumeration findResources(String name) throws IOException { // resource is in a package of a module defined to this loader if (module.loader() == this) { - URL url = findResource(module.name(), name); // checks URL + URL url = findResource(module.name(), name); if (url != null && (name.endsWith(".class") || url.toString().endsWith("/") || isOpen(module.mref(), pn))) { - checked.add(url); + resources.add(url); } } @@ -376,17 +376,17 @@ public Enumeration findResources(String name) throws IOException { // not in a package of a module defined to this loader for (URL url : findMiscResource(name)) { if (url != null) { - checked.add(url); + resources.add(url); } } } - // class path (not checked) + // class path Enumeration e = findResourcesOnClassPath(name); - // concat the checked URLs and the (not checked) class path + // concat the URLs of the resource in the modules and the class path return new Enumeration<>() { - final Iterator iterator = checked.iterator(); + final Iterator iterator = resources.iterator(); URL next; private boolean hasNext() { if (next != null) { @@ -395,7 +395,6 @@ private boolean hasNext() { next = iterator.next(); return true; } else { - // need to check each URL while (e.hasMoreElements() && next == null) { next = e.nextElement(); } @@ -485,7 +484,7 @@ private URL findResource(ModuleReference mref, String name) throws IOException { */ private URL findResourceOnClassPath(String name) { if (hasClassPath()) { - return ucp.findResource(name, false); + return ucp.findResource(name); } else { // no class path return null; @@ -497,7 +496,7 @@ private URL findResourceOnClassPath(String name) { */ private Enumeration findResourcesOnClassPath(String name) { if (hasClassPath()) { - return ucp.findResources(name, false); + return ucp.findResources(name); } else { // no class path return Collections.emptyEnumeration(); @@ -686,7 +685,7 @@ private Class findClassInModuleOrNull(LoadedModule loadedModule, String cn) { */ private Class findClassOnClassPathOrNull(String cn) { String path = cn.replace('.', '/').concat(".class"); - Resource res = ucp.getResource(path, false); + Resource res = ucp.getResource(path); if (res != null) { try { return defineClass(cn, res); diff --git a/src/java.base/share/classes/jdk/internal/loader/URLClassPath.java b/src/java.base/share/classes/jdk/internal/loader/URLClassPath.java index 297c77bc106c7..75418111f7439 100644 --- a/src/java.base/share/classes/jdk/internal/loader/URLClassPath.java +++ b/src/java.base/share/classes/jdk/internal/loader/URLClassPath.java @@ -39,13 +39,7 @@ import java.net.URLConnection; import java.net.URLStreamHandler; import java.net.URLStreamHandlerFactory; -import java.security.AccessControlContext; -import java.security.AccessControlException; -import java.security.AccessController; import java.security.CodeSigner; -import java.security.Permission; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; import java.security.cert.Certificate; import java.util.ArrayDeque; import java.util.ArrayList; @@ -70,7 +64,6 @@ import jdk.internal.access.SharedSecrets; import sun.net.util.URLUtil; import sun.net.www.ParseUtil; -import sun.security.action.GetPropertyAction; /** * This class is used to maintain a search path of URLs for loading classes @@ -83,20 +76,16 @@ public class URLClassPath { private static final String JAVA_VERSION; private static final boolean DEBUG; private static final boolean DISABLE_JAR_CHECKING; - private static final boolean DISABLE_ACC_CHECKING; private static final boolean DISABLE_CP_URL_CHECK; private static final boolean DEBUG_CP_URL_CHECK; static { - Properties props = GetPropertyAction.privilegedGetProperties(); + Properties props = System.getProperties(); JAVA_VERSION = props.getProperty("java.version"); DEBUG = (props.getProperty("sun.misc.URLClassPath.debug") != null); String p = props.getProperty("sun.misc.URLClassPath.disableJarChecking"); DISABLE_JAR_CHECKING = p != null ? p.equals("true") || p.isEmpty() : false; - p = props.getProperty("jdk.net.URLClassPath.disableRestrictedPermissions"); - DISABLE_ACC_CHECKING = p != null ? p.equals("true") || p.isEmpty() : false; - // This property will be removed in a later release p = props.getProperty("jdk.net.URLClassPath.disableClassPathURLCheck"); DISABLE_CP_URL_CHECK = p != null ? p.equals("true") || p.isEmpty() : false; @@ -125,12 +114,6 @@ public class URLClassPath { /* Whether this URLClassLoader has been closed yet */ private boolean closed = false; - /* The context to be used when loading classes and resources. If non-null - * this is the context that was captured during the creation of the - * URLClassLoader. null implies no additional security restrictions. */ - @SuppressWarnings("removal") - private final AccessControlContext acc; - /** * Creates a new URLClassPath for the given URLs. The URLs will be * searched in the order specified for classes and resources. A URL @@ -140,12 +123,9 @@ public class URLClassPath { * @param urls the directory and JAR file URLs to search for classes * and resources * @param factory the URLStreamHandlerFactory to use when creating new URLs - * @param acc the context to be used when loading classes and resources, may - * be null */ public URLClassPath(URL[] urls, - URLStreamHandlerFactory factory, - @SuppressWarnings("removal") AccessControlContext acc) { + URLStreamHandlerFactory factory) { ArrayList path = new ArrayList<>(urls.length); ArrayDeque unopenedUrls = new ArrayDeque<>(urls.length); for (URL url : urls) { @@ -160,14 +140,10 @@ public URLClassPath(URL[] urls, } else { jarHandler = null; } - if (DISABLE_ACC_CHECKING) - this.acc = null; - else - this.acc = acc; } - public URLClassPath(URL[] urls, @SuppressWarnings("removal") AccessControlContext acc) { - this(urls, null, acc); + public URLClassPath(URL[] urls) { + this(urls, null); } /** @@ -209,7 +185,6 @@ public URLClassPath(URL[] urls, @SuppressWarnings("removal") AccessControlContex // the application class loader uses the built-in protocol handler to avoid protocol // handler lookup when opening JAR files on the class path. this.jarHandler = new sun.net.www.protocol.jar.Handler(); - this.acc = null; } public synchronized List closeLoaders() { @@ -279,17 +254,16 @@ public URL[] getURLs() { /** * Finds the resource with the specified name on the URL search path - * or null if not found or security check fails. + * or null if not found. * * @param name the name of the resource - * @param check whether to perform a security check * @return a {@code URL} for the resource, or {@code null} * if the resource could not be found. */ - public URL findResource(String name, boolean check) { + public URL findResource(String name) { Loader loader; for (int i = 0; (loader = getLoader(i)) != null; i++) { - URL url = loader.findResource(name, check); + URL url = loader.findResource(name); if (url != null) { return url; } @@ -297,29 +271,6 @@ public URL findResource(String name, boolean check) { return null; } - /** - * Finds the first Resource on the URL search path which has the specified - * name. Returns null if no Resource could be found. - * - * @param name the name of the Resource - * @param check whether to perform a security check - * @return the Resource, or null if not found - */ - public Resource getResource(String name, boolean check) { - if (DEBUG) { - System.err.println("URLClassPath.getResource(\"" + name + "\")"); - } - - Loader loader; - for (int i = 0; (loader = getLoader(i)) != null; i++) { - Resource res = loader.getResource(name, check); - if (res != null) { - return res; - } - } - return null; - } - /** * Finds all resources on the URL search path with the given name. * Returns an enumeration of the URL objects. @@ -327,8 +278,7 @@ public Resource getResource(String name, boolean check) { * @param name the resource name * @return an Enumeration of all the urls having the specified name */ - public Enumeration findResources(final String name, - final boolean check) { + public Enumeration findResources(final String name) { return new Enumeration<>() { private int index = 0; private URL url = null; @@ -339,7 +289,7 @@ private boolean next() { } else { Loader loader; while ((loader = getLoader(index++)) != null) { - url = loader.findResource(name, check); + url = loader.findResource(name); if (url != null) { return true; } @@ -363,8 +313,26 @@ public URL nextElement() { }; } + /** + * Finds the first Resource on the URL search path which has the specified + * name. Returns null if no Resource could be found. + * + * @param name the name of the Resource + * @return the Resource, or null if not found + */ public Resource getResource(String name) { - return getResource(name, true); + if (DEBUG) { + System.err.println("URLClassPath.getResource(\"" + name + "\")"); + } + + Loader loader; + for (int i = 0; (loader = getLoader(i)) != null; i++) { + Resource res = loader.getResource(name); + if (res != null) { + return res; + } + } + return null; } /** @@ -374,8 +342,7 @@ public Resource getResource(String name) { * @param name the resource name * @return an Enumeration of all the resources having the specified name */ - public Enumeration getResources(final String name, - final boolean check) { + public Enumeration getResources(final String name) { return new Enumeration<>() { private int index = 0; private Resource res = null; @@ -386,7 +353,7 @@ private boolean next() { } else { Loader loader; while ((loader = getLoader(index++)) != null) { - res = loader.getResource(name, check); + res = loader.getResource(name); if (res != null) { return true; } @@ -410,10 +377,6 @@ public Resource nextElement() { }; } - public Enumeration getResources(final String name) { - return getResources(name, true); - } - /* * Returns the Loader at the specified position in the URL search * path. The URLs are opened and expanded as needed. Returns null @@ -455,17 +418,6 @@ private synchronized Loader getLoader(int index) { closeQuietly(loader); } continue; - } catch (SecurityException se) { - // log the error and close the unusable loader (if any). - // The context, if there is one, that this URLClassPath was - // given during construction will never have permission to access the URL. - if (DEBUG) { - System.err.println("Failed to access " + url + ", " + se ); - } - if (loader != null) { - closeQuietly(loader); - } - continue; } if (loaderClassPathURLs != null) { push(loaderClassPathURLs); @@ -491,34 +443,24 @@ private static void closeQuietly(final Loader loader) { /* * Returns the Loader for the specified base URL. */ - @SuppressWarnings("removal") private Loader getLoader(final URL url) throws IOException { - try { - return AccessController.doPrivileged( - new PrivilegedExceptionAction<>() { - public Loader run() throws IOException { - String protocol = url.getProtocol(); // lower cased in URL - String file = url.getFile(); - if (file != null && file.endsWith("/")) { - if ("file".equals(protocol)) { - return new FileLoader(url); - } else if ("jar".equals(protocol) && - isDefaultJarHandler(url) && - file.endsWith("!/")) { - // extract the nested URL - @SuppressWarnings("deprecation") - URL nestedUrl = new URL(file.substring(0, file.length() - 2)); - return new JarLoader(nestedUrl, jarHandler, acc); - } else { - return new Loader(url); - } - } else { - return new JarLoader(url, jarHandler, acc); - } - } - }, acc); - } catch (PrivilegedActionException pae) { - throw (IOException)pae.getException(); + String protocol = url.getProtocol(); // lower cased in URL + String file = url.getFile(); + if (file != null && file.endsWith("/")) { + if ("file".equals(protocol)) { + return new FileLoader(url); + } else if ("jar".equals(protocol) && + isDefaultJarHandler(url) && + file.endsWith("!/")) { + // extract the nested URL + @SuppressWarnings("deprecation") + URL nestedUrl = new URL(file.substring(0, file.length() - 2)); + return new JarLoader(nestedUrl, jarHandler); + } else { + return new Loader(url); + } + } else { + return new JarLoader(url, jarHandler); } } @@ -541,59 +483,6 @@ private void push(URL[] urls) { } } - /* - * Checks whether the resource URL should be returned. - * Returns null on security check failure. - * Called by java.net.URLClassLoader. - */ - public static URL checkURL(URL url) { - if (url != null) { - try { - check(url); - } catch (Exception e) { - return null; - } - } - return url; - } - - /* - * Checks whether the resource URL should be returned. - * Throws exception on failure. - * Called internally within this file. - */ - public static void check(URL url) throws IOException { - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); - if (security != null) { - URLConnection urlConnection = url.openConnection(); - Permission perm = urlConnection.getPermission(); - if (perm != null) { - try { - security.checkPermission(perm); - } catch (SecurityException se) { - // fallback to checkRead/checkConnect for pre 1.2 - // security managers - if ((perm instanceof java.io.FilePermission) && - perm.getActions().contains("read")) { - security.checkRead(perm.getName()); - } else if ((perm instanceof - java.net.SocketPermission) && - perm.getActions().contains("connect")) { - URL locUrl = url; - if (urlConnection instanceof JarURLConnection) { - locUrl = ((JarURLConnection)urlConnection).getJarFileURL(); - } - security.checkConnect(locUrl.getHost(), - locUrl.getPort()); - } else { - throw se; - } - } - } - } - } - /** * Nested class used to represent a loader of resources and classes * from a base URL. @@ -616,7 +505,7 @@ final URL getBaseURL() { return base; } - URL findResource(final String name, boolean check) { + URL findResource(final String name) { URL url; try { @SuppressWarnings("deprecation") @@ -626,10 +515,6 @@ URL findResource(final String name, boolean check) { } try { - if (check) { - URLClassPath.check(url); - } - /* * For a HTTP connection we use the HEAD method to * check if the resource exists. @@ -653,7 +538,11 @@ URL findResource(final String name, boolean check) { } } - Resource getResource(final String name, boolean check) { + /* + * Returns the Resource for the specified name, or null if not + * found. + */ + Resource getResource(final String name) { final URL url; try { @SuppressWarnings("deprecation") @@ -663,9 +552,6 @@ Resource getResource(final String name, boolean check) { } final URLConnection uc; try { - if (check) { - URLClassPath.check(url); - } uc = url.openConnection(); if (uc instanceof JarURLConnection) { @@ -693,15 +579,6 @@ public int getContentLength() throws IOException { }; } - /* - * Returns the Resource for the specified name, or null if not - * found or the caller does not have the permission to get the - * resource. - */ - Resource getResource(final String name) { - return getResource(name, true); - } - /* * Closes this loader and release all resources. * Method overridden in sub-classes. @@ -727,8 +604,6 @@ URL[] getClassPath() throws IOException { private static class JarLoader extends Loader { private JarFile jar; private final URL csu; - @SuppressWarnings("removal") - private final AccessControlContext acc; private boolean closed = false; private static final JavaUtilZipFileAccess zipAccess = SharedSecrets.getJavaUtilZipFileAccess(); @@ -737,14 +612,11 @@ private static class JarLoader extends Loader { * Creates a new JarLoader for the specified URL referring to * a JAR file. */ - private JarLoader(URL url, URLStreamHandler jarHandler, - @SuppressWarnings("removal") AccessControlContext acc) + private JarLoader(URL url, URLStreamHandler jarHandler) throws IOException { super(newURL("jar", "", -1, url + "!/", jarHandler)); csu = url; - this.acc = acc; - ensureOpen(); } @@ -770,24 +642,13 @@ private boolean isOptimizable(URL url) { return "file".equals(url.getProtocol()); } - @SuppressWarnings("removal") private void ensureOpen() throws IOException { if (jar == null) { - try { - AccessController.doPrivileged( - new PrivilegedExceptionAction<>() { - public Void run() throws IOException { - if (DEBUG) { - System.err.println("Opening " + csu); - Thread.dumpStack(); - } - jar = getJarFile(csu); - return null; - } - }, acc); - } catch (PrivilegedActionException pae) { - throw (IOException)pae.getException(); + if (DEBUG) { + System.err.println("Opening " + csu); + Thread.dumpStack(); } + jar = getJarFile(csu); } } @@ -826,11 +687,9 @@ private JarFile getJarFile(URL url) throws IOException { } /* - * Creates the resource and if the check flag is set to true, checks if - * is its okay to return the resource. + * Creates and returns the Resource. Returns null if the Resource couldn't be created. */ - Resource checkResource(final String name, boolean check, - final JarEntry entry) { + Resource createResource(final String name, final JarEntry entry) { final URL url; try { @@ -842,10 +701,7 @@ Resource checkResource(final String name, boolean check, } @SuppressWarnings("deprecation") var _unused = url = new URL(getBaseURL(), ParseUtil.encodePath(nm, false)); - if (check) { - URLClassPath.check(url); - } - } catch (@SuppressWarnings("removal") AccessControlException | IOException e) { + } catch (IOException e) { return null; } @@ -885,8 +741,8 @@ public byte[] getBytes() throws IOException { * Returns the URL for a resource with the specified name */ @Override - URL findResource(final String name, boolean check) { - Resource rsc = getResource(name, check); + URL findResource(final String name) { + Resource rsc = getResource(name); if (rsc != null) { return rsc.getURL(); } @@ -897,17 +753,16 @@ URL findResource(final String name, boolean check) { * Returns the JAR Resource for the specified name. */ @Override - Resource getResource(final String name, boolean check) { + Resource getResource(final String name) { try { ensureOpen(); } catch (IOException e) { throw new InternalError(e); } final JarEntry entry = jar.getJarEntry(name); - if (entry != null) - return checkResource(name, check, entry); - - + if (entry != null) { + return createResource(name, entry); + } return null; } @@ -1058,8 +913,8 @@ private FileLoader(URL url) throws IOException { * Returns the URL for a resource with the specified name */ @Override - URL findResource(final String name, boolean check) { - Resource rsc = getResource(name, check); + URL findResource(final String name) { + Resource rsc = getResource(name); if (rsc != null) { return rsc.getURL(); } @@ -1067,7 +922,7 @@ URL findResource(final String name, boolean check) { } @Override - Resource getResource(final String name, boolean check) { + Resource getResource(final String name) { final URL url; try { @SuppressWarnings("deprecation") @@ -1077,10 +932,6 @@ Resource getResource(final String name, boolean check) { // requested resource had ../..'s in path return null; } - - if (check) - URLClassPath.check(url); - final File file; if (name.contains("..")) { file = (new File(dir, name.replace('/', File.separatorChar))) From 4bc826ac1ea824113a07713f6973c06361c1392e Mon Sep 17 00:00:00 2001 From: Vlad Zahorodnii Date: Wed, 20 Nov 2024 13:38:08 +0000 Subject: [PATCH 44/74] 8342785: XWindowPeer::getNewLocation() adheres to ICCCM 4.1.5 only with some WMs Reviewed-by: prr, azvegint --- .../unix/classes/sun/awt/X11/XWindowPeer.java | 28 ++++--------------- 1 file changed, 6 insertions(+), 22 deletions(-) diff --git a/src/java.desktop/unix/classes/sun/awt/X11/XWindowPeer.java b/src/java.desktop/unix/classes/sun/awt/X11/XWindowPeer.java index 1c0f8e27ffb74..267ad9349ea37 100644 --- a/src/java.desktop/unix/classes/sun/awt/X11/XWindowPeer.java +++ b/src/java.desktop/unix/classes/sun/awt/X11/XWindowPeer.java @@ -767,28 +767,12 @@ protected Point getNewLocation(XConfigureEvent xe, int leftInset, int topInset) // a window is resized but the client can not tell if the window was // moved or not. The client should consider the position as unknown // and use TranslateCoordinates to find the actual position. - // - // TODO this should be the default for every case. - switch (runningWM) { - case XWM.CDE_WM: - case XWM.KDE2_WM: - case XWM.MOTIF_WM: - case XWM.METACITY_WM: - case XWM.MUTTER_WM: - case XWM.SAWFISH_WM: - case XWM.UNITY_COMPIZ_WM: - { - Point xlocation = queryXLocation(); - if (log.isLoggable(PlatformLogger.Level.FINE)) { - log.fine("New X location: {0}", xlocation); - } - if (xlocation != null) { - newLocation = xlocation; - } - break; - } - default: - break; + Point xlocation = queryXLocation(); + if (log.isLoggable(PlatformLogger.Level.FINE)) { + log.fine("New X location: {0}", xlocation); + } + if (xlocation != null) { + newLocation = xlocation; } } return newLocation; From 21f0ed50a224f19d083ef8e3b7b02b8f3dd31cac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Volkan=20Yaz=C4=B1c=C4=B1?= Date: Wed, 20 Nov 2024 13:59:52 +0000 Subject: [PATCH 45/74] 8344215: Remove calls to SecurityManager and doPrivileged in java.net.Socket and java.net.ServerSocket after JEP 486 integration Reviewed-by: dfuchs, alanb, jpai --- .../share/classes/java/net/ServerSocket.java | 58 ++---------------- .../share/classes/java/net/Socket.java | 60 +------------------ 2 files changed, 6 insertions(+), 112 deletions(-) diff --git a/src/java.base/share/classes/java/net/ServerSocket.java b/src/java.base/share/classes/java/net/ServerSocket.java index c6560fee35aad..945693ef65ed6 100644 --- a/src/java.base/share/classes/java/net/ServerSocket.java +++ b/src/java.base/share/classes/java/net/ServerSocket.java @@ -33,7 +33,6 @@ import java.util.Set; import java.util.Collections; -import sun.security.util.SecurityConstants; import sun.net.PlatformSocketImpl; /** @@ -89,13 +88,6 @@ public class ServerSocket implements java.io.Closeable { // used to coordinate creating and closing underlying socket private final Object socketLock = new Object(); - /** - * Creates a server socket with the given {@code SocketImpl}. - */ - private ServerSocket(Void unused, SocketImpl impl) { - this.impl = Objects.requireNonNull(impl); - } - /** * Creates a server socket with a user-specified {@code SocketImpl}. * @@ -106,16 +98,7 @@ private ServerSocket(Void unused, SocketImpl impl) { * @since 12 */ protected ServerSocket(SocketImpl impl) { - this(checkPermission(), impl); - } - - private static Void checkPermission() { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPermission(SecurityConstants.SET_SOCKETIMPL_PERMISSION); - } - return null; + this.impl = Objects.requireNonNull(impl); } /** @@ -237,7 +220,7 @@ public ServerSocket(int port, int backlog, InetAddress bindAddr) throws IOExcept this.impl = createImpl(); try { bind(new InetSocketAddress(bindAddr, port), backlog); - } catch (IOException | SecurityException e) { + } catch (IOException e) { close(); throw e; } @@ -338,11 +321,6 @@ public void bind(SocketAddress endpoint, int backlog) throws IOException { if (backlog < 1) backlog = 50; - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); - if (security != null) - security.checkListen(epoint.getPort()); - // SocketImpl bind+listen throw if already bound or closed SocketImpl impl = getImpl(); impl.bind(epoint.getAddress(), epoint.getPort()); @@ -364,14 +342,7 @@ public InetAddress getInetAddress() { if (!isBound()) return null; try { - InetAddress in = getImpl().getInetAddress(); - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) - sm.checkConnect(in.getHostAddress(), -1); - return in; - } catch (SecurityException e) { - return InetAddress.getLoopbackAddress(); + return getImpl().getInetAddress(); } catch (SocketException e) { // nothing // If we're bound, the impl has been created @@ -631,17 +602,6 @@ private void implAccept(SocketImpl si) throws IOException { throw e; } - // check permission, close SocketImpl/connection if denied - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - try { - sm.checkAccept(si.getInetAddress().getHostAddress(), si.getPort()); - } catch (SecurityException se) { - si.close(); - throw se; - } - } } /** @@ -835,15 +795,10 @@ public boolean getReuseAddress() throws SocketException { * * @return a string representation of this socket. */ - @SuppressWarnings("removal") public String toString() { if (!isBound()) return "ServerSocket[unbound]"; - InetAddress in; - if (System.getSecurityManager() != null) - in = getInetAddress(); - else - in = impl.getInetAddress(); + InetAddress in = impl.getInetAddress(); return "ServerSocket[addr=" + in + ",localport=" + impl.getLocalPort() + "]"; } @@ -884,11 +839,6 @@ public static synchronized void setSocketFactory(SocketImplFactory fac) throws I if (factory != null) { throw new SocketException("factory already defined"); } - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); - if (security != null) { - security.checkSetFactory(); - } factory = fac; } diff --git a/src/java.base/share/classes/java/net/Socket.java b/src/java.base/share/classes/java/net/Socket.java index 9825457aac1d3..83c0dec682ca1 100644 --- a/src/java.base/share/classes/java/net/Socket.java +++ b/src/java.base/share/classes/java/net/Socket.java @@ -28,7 +28,6 @@ import jdk.internal.event.SocketReadEvent; import jdk.internal.event.SocketWriteEvent; import jdk.internal.invoke.MhUtil; -import sun.security.util.SecurityConstants; import java.io.InputStream; import java.io.InterruptedIOException; @@ -157,15 +156,6 @@ private static boolean isOutputShutdown(int s) { return (s & SHUT_OUT) != 0; } - /** - * Creates an unconnected socket with the given {@code SocketImpl}. - */ - private Socket(Void unused, SocketImpl impl) { - if (impl != null) { - this.impl = impl; - } - } - /** * Creates an unconnected Socket. *

@@ -212,22 +202,10 @@ public Socket(Proxy proxy) { : sun.net.ApplicationProxy.create(proxy); Proxy.Type type = p.type(); if (type == Proxy.Type.SOCKS || type == Proxy.Type.HTTP) { - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); InetSocketAddress epoint = (InetSocketAddress) p.address(); if (epoint.getAddress() != null) { checkAddress (epoint.getAddress(), "Socket"); } - if (security != null) { - if (epoint.isUnresolved()) - epoint = new InetSocketAddress(epoint.getHostName(), epoint.getPort()); - if (epoint.isUnresolved()) - security.checkConnect(epoint.getHostName(), epoint.getPort()); - else - security.checkConnect(epoint.getAddress().getHostAddress(), - epoint.getPort()); - } - // create a SOCKS or HTTP SocketImpl that delegates to a platform SocketImpl SocketImpl delegate = SocketImpl.createPlatformSocketImpl(false); impl = (type == Proxy.Type.SOCKS) ? new SocksSocketImpl(p, delegate) @@ -259,18 +237,9 @@ public Socket(Proxy proxy) { * @since 1.1 */ protected Socket(SocketImpl impl) throws SocketException { - this(checkPermission(impl), impl); - } - - private static Void checkPermission(SocketImpl impl) { if (impl != null) { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPermission(SecurityConstants.SET_SOCKETIMPL_PERMISSION); - } + this.impl = impl; } - return null; } /** @@ -497,7 +466,7 @@ private Socket(SocketAddress address, SocketAddress localAddr, boolean stream) if (localAddr != null) bind(localAddr); connect(address); - } catch (IOException | IllegalArgumentException | SecurityException e) { + } catch (IOException | IllegalArgumentException e) { try { close(); } catch (IOException ce) { @@ -684,15 +653,6 @@ public void connect(SocketAddress endpoint, int timeout) throws IOException { int port = epoint.getPort(); checkAddress(addr, "connect"); - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); - if (security != null) { - if (epoint.isUnresolved()) - security.checkConnect(epoint.getHostName(), port); - else - security.checkConnect(addr.getHostAddress(), port); - } - try { getImpl().connect(epoint, timeout); } catch (SocketTimeoutException e) { @@ -743,11 +703,6 @@ public void bind(SocketAddress bindpoint) throws IOException { InetAddress addr = epoint.getAddress(); int port = epoint.getPort(); checkAddress (addr, "bind"); - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); - if (security != null) { - security.checkListen(port); - } getImpl().bind(addr, port); getAndBitwiseOrState(BOUND); } @@ -795,15 +750,9 @@ public InetAddress getLocalAddress() { InetAddress in = null; try { in = (InetAddress) getImpl().getOption(SocketOptions.SO_BINDADDR); - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) - sm.checkConnect(in.getHostAddress(), -1); if (in.isAnyLocalAddress()) { in = InetAddress.anyLocalAddress(); } - } catch (SecurityException e) { - in = InetAddress.getLoopbackAddress(); } catch (Exception e) { in = InetAddress.anyLocalAddress(); // "0.0.0.0" } @@ -1855,11 +1804,6 @@ public static synchronized void setSocketImplFactory(SocketImplFactory fac) if (factory != null) { throw new SocketException("factory already defined"); } - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); - if (security != null) { - security.checkSetFactory(); - } factory = fac; } From e11d126a8d50e8b3dce2fd02b263aba3b38b1172 Mon Sep 17 00:00:00 2001 From: "David M. Lloyd" Date: Wed, 20 Nov 2024 14:17:28 +0000 Subject: [PATCH 46/74] 8333796: Add missing serialization functionality to sun.reflect.ReflectionFactory Reviewed-by: liach, rriggs --- .../java/io/ObjectStreamReflection.java | 177 ++++++ .../JavaObjectStreamReflectionAccess.java | 33 ++ .../jdk/internal/access/SharedSecrets.java | 16 + .../internal/reflect/ReflectionFactory.java | 68 ++- .../sun/reflect/ReflectionFactory.java | 111 ++++ .../ReflectionFactoryTest.java | 509 +++++++++++++++++- 6 files changed, 912 insertions(+), 2 deletions(-) create mode 100644 src/java.base/share/classes/java/io/ObjectStreamReflection.java create mode 100644 src/java.base/share/classes/jdk/internal/access/JavaObjectStreamReflectionAccess.java diff --git a/src/java.base/share/classes/java/io/ObjectStreamReflection.java b/src/java.base/share/classes/java/io/ObjectStreamReflection.java new file mode 100644 index 0000000000000..35c7019419cf4 --- /dev/null +++ b/src/java.base/share/classes/java/io/ObjectStreamReflection.java @@ -0,0 +1,177 @@ +/* + * Copyright (c) 2024, 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 java.io; + +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; + +import jdk.internal.access.JavaObjectStreamReflectionAccess; +import jdk.internal.access.SharedSecrets; +import jdk.internal.util.ByteArray; + +/** + * Utilities relating to serialization and deserialization of objects. + */ +final class ObjectStreamReflection { + + // todo: these could be constants + private static final MethodHandle DRO_HANDLE; + private static final MethodHandle DWO_HANDLE; + + static { + try { + MethodHandles.Lookup lookup = MethodHandles.lookup(); + MethodType droType = MethodType.methodType(void.class, ObjectStreamClass.class, Object.class, ObjectInputStream.class); + DRO_HANDLE = lookup.findStatic(ObjectStreamReflection.class, "defaultReadObject", droType); + MethodType dwoType = MethodType.methodType(void.class, ObjectStreamClass.class, Object.class, ObjectOutputStream.class); + DWO_HANDLE = lookup.findStatic(ObjectStreamReflection.class, "defaultWriteObject", dwoType); + } catch (NoSuchMethodException | IllegalAccessException e) { + throw new InternalError(e); + } + } + + /** + * Populate a serializable object from data acquired from the stream's + * {@link java.io.ObjectInputStream.GetField} object independently of + * the actual {@link ObjectInputStream} implementation which may + * arbitrarily override the {@link ObjectInputStream#readFields()} method + * in order to deserialize using a custom object format. + *

+ * The fields are populated using the mechanism defined in {@link ObjectStreamClass}, + * which requires objects and primitives to each be packed into a separate array + * whose relative field offsets are defined in the {@link ObjectStreamField} + * corresponding to each field. + * Utility methods on the {@code ObjectStreamClass} instance are then used + * to validate and perform the actual field accesses. + * + * @param streamClass the object stream class of the object (must not be {@code null}) + * @param obj the object to deserialize (must not be {@code null}) + * @param ois the object stream (must not be {@code null}) + * @throws IOException if the call to {@link ObjectInputStream#readFields} + * or one of its field accessors throws this exception type + * @throws ClassNotFoundException if the call to {@link ObjectInputStream#readFields} + * or one of its field accessors throws this exception type + */ + private static void defaultReadObject(ObjectStreamClass streamClass, Object obj, ObjectInputStream ois) + throws IOException, ClassNotFoundException { + ObjectInputStream.GetField getField = ois.readFields(); + byte[] bytes = new byte[streamClass.getPrimDataSize()]; + Object[] objs = new Object[streamClass.getNumObjFields()]; + for (ObjectStreamField field : streamClass.getFields(false)) { + int offset = field.getOffset(); + String fieldName = field.getName(); + switch (field.getTypeCode()) { + case 'B' -> bytes[offset] = getField.get(fieldName, (byte) 0); + case 'C' -> ByteArray.setChar(bytes, offset, getField.get(fieldName, (char) 0)); + case 'D' -> ByteArray.setDoubleRaw(bytes, offset, getField.get(fieldName, 0.0)); + case 'F' -> ByteArray.setFloatRaw(bytes, offset, getField.get(fieldName, 0.0f)); + case 'I' -> ByteArray.setInt(bytes, offset, getField.get(fieldName, 0)); + case 'J' -> ByteArray.setLong(bytes, offset, getField.get(fieldName, 0L)); + case 'S' -> ByteArray.setShort(bytes, offset, getField.get(fieldName, (short) 0)); + case 'Z' -> ByteArray.setBoolean(bytes, offset, getField.get(fieldName, false)); + case '[', 'L' -> objs[offset] = getField.get(fieldName, null); + default -> throw new IllegalStateException(); + } + } + streamClass.checkObjFieldValueTypes(obj, objs); + streamClass.setPrimFieldValues(obj, bytes); + streamClass.setObjFieldValues(obj, objs); + } + + /** + * Populate and write a stream's {@link java.io.ObjectOutputStream.PutField} object + * from field data acquired from a serializable object independently of + * the actual {@link ObjectOutputStream} implementation which may + * arbitrarily override the {@link ObjectOutputStream#putFields()} + * and {@link ObjectOutputStream#writeFields()} methods + * in order to deserialize using a custom object format. + *

+ * The fields are accessed using the mechanism defined in {@link ObjectStreamClass}, + * which causes objects and primitives to each be packed into a separate array + * whose relative field offsets are defined in the {@link ObjectStreamField} + * corresponding to each field. + * + * @param streamClass the object stream class of the object (must not be {@code null}) + * @param obj the object to serialize (must not be {@code null}) + * @param oos the object stream (must not be {@code null}) + * @throws IOException if the call to {@link ObjectInputStream#readFields} + * or one of its field accessors throws this exception type + */ + private static void defaultWriteObject(ObjectStreamClass streamClass, Object obj, ObjectOutputStream oos) + throws IOException { + ObjectOutputStream.PutField putField = oos.putFields(); + byte[] bytes = new byte[streamClass.getPrimDataSize()]; + Object[] objs = new Object[streamClass.getNumObjFields()]; + streamClass.getPrimFieldValues(obj, bytes); + streamClass.getObjFieldValues(obj, objs); + for (ObjectStreamField field : streamClass.getFields(false)) { + int offset = field.getOffset(); + String fieldName = field.getName(); + switch (field.getTypeCode()) { + case 'B' -> putField.put(fieldName, bytes[offset]); + case 'C' -> putField.put(fieldName, ByteArray.getChar(bytes, offset)); + case 'D' -> putField.put(fieldName, ByteArray.getDouble(bytes, offset)); + case 'F' -> putField.put(fieldName, ByteArray.getFloat(bytes, offset)); + case 'I' -> putField.put(fieldName, ByteArray.getInt(bytes, offset)); + case 'J' -> putField.put(fieldName, ByteArray.getLong(bytes, offset)); + case 'S' -> putField.put(fieldName, ByteArray.getShort(bytes, offset)); + case 'Z' -> putField.put(fieldName, ByteArray.getBoolean(bytes, offset)); + case '[', 'L' -> putField.put(fieldName, objs[offset]); + default -> throw new IllegalStateException(); + } + } + oos.writeFields(); + } + + static final class Access implements JavaObjectStreamReflectionAccess { + static { + SharedSecrets.setJavaObjectStreamReflectionAccess(new Access()); + } + + public MethodHandle defaultReadObject(Class clazz) { + return handleForClass(DRO_HANDLE, clazz, ObjectInputStream.class); + } + + public MethodHandle defaultWriteObject(Class clazz) { + return handleForClass(DWO_HANDLE, clazz, ObjectOutputStream.class); + } + + private static MethodHandle handleForClass(final MethodHandle handle, final Class clazz, final Class ioClass) { + ObjectStreamClass streamClass = ObjectStreamClass.lookup(clazz); + if (streamClass != null) { + try { + streamClass.checkDefaultSerialize(); + return handle.bindTo(streamClass) + .asType(MethodType.methodType(void.class, clazz, ioClass)); + } catch (InvalidClassException e) { + // ignore and return null + } + } + return null; + } + } +} diff --git a/src/java.base/share/classes/jdk/internal/access/JavaObjectStreamReflectionAccess.java b/src/java.base/share/classes/jdk/internal/access/JavaObjectStreamReflectionAccess.java new file mode 100644 index 0000000000000..ea3e219e8ab6f --- /dev/null +++ b/src/java.base/share/classes/jdk/internal/access/JavaObjectStreamReflectionAccess.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2024, 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 jdk.internal.access; + +import java.lang.invoke.MethodHandle; + +public interface JavaObjectStreamReflectionAccess { + MethodHandle defaultReadObject(Class clazz); + MethodHandle defaultWriteObject(Class clazz); +} diff --git a/src/java.base/share/classes/jdk/internal/access/SharedSecrets.java b/src/java.base/share/classes/jdk/internal/access/SharedSecrets.java index c29d0dd01a59d..43a1daf762c68 100644 --- a/src/java.base/share/classes/jdk/internal/access/SharedSecrets.java +++ b/src/java.base/share/classes/jdk/internal/access/SharedSecrets.java @@ -77,6 +77,7 @@ public class SharedSecrets { private static JavaObjectInputStreamReadString javaObjectInputStreamReadString; private static JavaObjectInputStreamAccess javaObjectInputStreamAccess; private static JavaObjectInputFilterAccess javaObjectInputFilterAccess; + private static JavaObjectStreamReflectionAccess javaObjectStreamReflectionAccess; private static JavaNetInetAddressAccess javaNetInetAddressAccess; private static JavaNetHttpCookieAccess javaNetHttpCookieAccess; private static JavaNetUriAccess javaNetUriAccess; @@ -431,6 +432,21 @@ public static void setJavaObjectInputFilterAccess(JavaObjectInputFilterAccess ac javaObjectInputFilterAccess = access; } + public static JavaObjectStreamReflectionAccess getJavaObjectStreamReflectionAccess() { + var access = javaObjectStreamReflectionAccess; + if (access == null) { + try { + Class.forName("java.io.ObjectStreamReflection$Access", true, null); + access = javaObjectStreamReflectionAccess; + } catch (ClassNotFoundException e) {} + } + return access; + } + + public static void setJavaObjectStreamReflectionAccess(JavaObjectStreamReflectionAccess access) { + javaObjectStreamReflectionAccess = access; + } + public static void setJavaIORandomAccessFileAccess(JavaIORandomAccessFileAccess jirafa) { javaIORandomAccessFileAccess = jirafa; } diff --git a/src/java.base/share/classes/jdk/internal/reflect/ReflectionFactory.java b/src/java.base/share/classes/jdk/internal/reflect/ReflectionFactory.java index bcaa8bacbaa7c..687e32cdf6165 100644 --- a/src/java.base/share/classes/jdk/internal/reflect/ReflectionFactory.java +++ b/src/java.base/share/classes/jdk/internal/reflect/ReflectionFactory.java @@ -29,6 +29,7 @@ import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamClass; +import java.io.ObjectStreamField; import java.io.OptionalDataException; import java.io.Serializable; import java.lang.invoke.MethodHandle; @@ -39,7 +40,10 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; +import java.lang.reflect.Proxy; import java.security.PrivilegedAction; +import java.util.Set; + import jdk.internal.access.JavaLangReflectAccess; import jdk.internal.access.SharedSecrets; import jdk.internal.misc.VM; @@ -66,6 +70,7 @@ public class ReflectionFactory { private static volatile Method hasStaticInitializerMethod; private final JavaLangReflectAccess langReflectAccess; + private ReflectionFactory() { this.langReflectAccess = SharedSecrets.getJavaLangReflectAccess(); } @@ -363,6 +368,46 @@ private final MethodHandle findReadWriteObjectForSerialization(Class cl, } } + public final MethodHandle defaultReadObjectForSerialization(Class cl) { + if (hasDefaultOrNoSerialization(cl)) { + return null; + } + + return SharedSecrets.getJavaObjectStreamReflectionAccess().defaultReadObject(cl); + } + + public final MethodHandle defaultWriteObjectForSerialization(Class cl) { + if (hasDefaultOrNoSerialization(cl)) { + return null; + } + + return SharedSecrets.getJavaObjectStreamReflectionAccess().defaultWriteObject(cl); + } + + /** + * These are specific leaf classes which appear to be Serializable, but which + * have special semantics according to the serialization specification. We + * could theoretically include array classes here, but it is easier and clearer + * to just use `Class#isArray` instead. + */ + private static final Set> nonSerializableLeafClasses = Set.of( + Class.class, + String.class, + ObjectStreamClass.class + ); + + private static boolean hasDefaultOrNoSerialization(Class cl) { + return ! Serializable.class.isAssignableFrom(cl) + || cl.isInterface() + || cl.isArray() + || Proxy.isProxyClass(cl) + || Externalizable.class.isAssignableFrom(cl) + || cl.isEnum() + || cl.isRecord() + || cl.isHidden() + || nonSerializableLeafClasses.contains(cl); + } + /** * Returns a MethodHandle for {@code writeReplace} on the serializable class * or null if no match found. @@ -468,6 +513,28 @@ public final Constructor newOptionalDataExceptionForSeria } } + public final ObjectStreamField[] serialPersistentFields(Class cl) { + if (! Serializable.class.isAssignableFrom(cl) || cl.isInterface() || cl.isEnum()) { + return null; + } + + try { + Field field = cl.getDeclaredField("serialPersistentFields"); + int mods = field.getModifiers(); + if (! (Modifier.isStatic(mods) && Modifier.isPrivate(mods) && Modifier.isFinal(mods))) { + return null; + } + if (field.getType() != ObjectStreamField[].class) { + return null; + } + field.setAccessible(true); + ObjectStreamField[] array = (ObjectStreamField[]) field.get(null); + return array != null && array.length > 0 ? array.clone() : array; + } catch (ReflectiveOperationException e) { + return null; + } + } + //-------------------------------------------------------------------------- // // Internals only below this point @@ -556,5 +623,4 @@ private static boolean packageEquals(Class cl1, Class cl2) { return cl1.getClassLoader() == cl2.getClassLoader() && cl1.getPackageName() == cl2.getPackageName(); } - } diff --git a/src/jdk.unsupported/share/classes/sun/reflect/ReflectionFactory.java b/src/jdk.unsupported/share/classes/sun/reflect/ReflectionFactory.java index b6c538c507f67..e671e1db526be 100644 --- a/src/jdk.unsupported/share/classes/sun/reflect/ReflectionFactory.java +++ b/src/jdk.unsupported/share/classes/sun/reflect/ReflectionFactory.java @@ -25,6 +25,9 @@ package sun.reflect; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.ObjectStreamField; import java.io.OptionalDataException; import java.lang.invoke.MethodHandle; import java.lang.reflect.Constructor; @@ -129,6 +132,50 @@ public final MethodHandle readObjectNoDataForSerialization(Class cl) { return delegate.readObjectNoDataForSerialization(cl); } + /** + * Generate and return a direct MethodHandle which implements + * the general default behavior for serializable class's {@code readObject}. + * The generated method behaves in accordance with the + * Java Serialization specification's rules for that method. + *

+ * The generated method will invoke {@link ObjectInputStream#readFields()} + * to acquire the stream field values. The serialization fields of the class will + * then be populated from the stream values. + *

+ * Only fields which are eligible for default serialization will be populated. + * This includes only fields which are not {@code transient} and not {@code static} + * (even if the field is {@code final} or {@code private}). + *

+ * Requesting a default serialization method for a class in a disallowed + * category is not supported; {@code null} will be returned for such classes. + * The disallowed categories include (but are not limited to): + *

    + *
  • Classes which do not implement {@code Serializable}
  • + *
  • Classes which implement {@code Externalizable}
  • + *
  • Classes which are specially handled by the Java Serialization specification, + * including record classes, enum constant classes, {@code Class}, {@code String}, + * array classes, reflection proxy classes, and hidden classes
  • + *
  • Classes which declare a valid {@code serialPersistentFields} value
  • + *
  • Any special types which may possibly be added to the JDK or the Java language + * in the future which in turn might require special handling by the + * provisions of the corresponding future version of the Java Serialization + * specification
  • + *
+ *

+ * The generated method will accept the instance as its first argument + * and the {@code ObjectInputStream} as its second argument. + * The return type of the method is {@code void}. + * + * @param cl a Serializable class + * @return a direct MethodHandle for the synthetic {@code readObject} method + * or {@code null} if the class falls in a disallowed category + * + * @since 24 + */ + public final MethodHandle defaultReadObjectForSerialization(Class cl) { + return delegate.defaultReadObjectForSerialization(cl); + } + /** * Returns a direct MethodHandle for the {@code writeObject} method on * a Serializable class. @@ -144,6 +191,53 @@ public final MethodHandle writeObjectForSerialization(Class cl) { return delegate.writeObjectForSerialization(cl); } + /** + * Generate and return a direct MethodHandle which implements + * the general default behavior for serializable class's {@code writeObject}. + * The generated method behaves in accordance with the + * Java Serialization specification's rules for that method. + *

+ * The generated method will invoke {@link ObjectOutputStream#putFields} + * to acquire the buffer for the stream field values. The buffer will + * be populated from the serialization fields of the class. The buffer + * will then be flushed to the stream using the + * {@link ObjectOutputStream#writeFields()} method. + *

+ * Only fields which are eligible for default serialization will be written + * to the buffer. + * This includes only fields which are not {@code transient} and not {@code static} + * (even if the field is {@code final} or {@code private}). + *

+ * Requesting a default serialization method for a class in a disallowed + * category is not supported; {@code null} will be returned for such classes. + * The disallowed categories include (but are not limited to): + *

    + *
  • Classes which do not implement {@code Serializable}
  • + *
  • Classes which implement {@code Externalizable}
  • + *
  • Classes which are specially handled by the Java Serialization specification, + * including record classes, enum constant classes, {@code Class}, {@code String}, + * array classes, reflection proxy classes, and hidden classes
  • + *
  • Classes which declare a valid {@code serialPersistentFields} value
  • + *
  • Any special types which may possibly be added to the JDK or the Java language + * in the future which in turn might require special handling by the + * provisions of the corresponding future version of the Java Serialization + * specification
  • + *
+ *

+ * The generated method will accept the instance as its first argument + * and the {@code ObjectOutputStream} as its second argument. + * The return type of the method is {@code void}. + * + * @param cl a Serializable class + * @return a direct MethodHandle for the synthetic {@code writeObject} method + * or {@code null} if the class falls in a disallowed category + * + * @since 24 + */ + public final MethodHandle defaultWriteObjectForSerialization(Class cl) { + return delegate.defaultWriteObjectForSerialization(cl); + } + /** * Returns a direct MethodHandle for the {@code readResolve} method on * a serializable class. @@ -197,4 +291,21 @@ public final OptionalDataException newOptionalDataExceptionForSerialization(bool throw new InternalError("unable to create OptionalDataException", ex); } } + + /** + * {@return the declared {@code serialPersistentFields} from a + * serializable class, or {@code null} if none is declared, the field + * is declared but not valid, or the class is not a valid serializable class} + * A class is a valid serializable class if it implements {@code Serializable} + * but not {@code Externalizable}. The {@code serialPersistentFields} field + * is valid if it meets the type and accessibility restrictions defined + * by the Java Serialization specification. + * + * @param cl a Serializable class + * + * @since 24 + */ + public final ObjectStreamField[] serialPersistentFields(Class cl) { + return delegate.serialPersistentFields(cl); + } } diff --git a/test/jdk/sun/reflect/ReflectionFactory/ReflectionFactoryTest.java b/test/jdk/sun/reflect/ReflectionFactory/ReflectionFactoryTest.java index 03dade05b14d5..b86ee4db0b914 100644 --- a/test/jdk/sun/reflect/ReflectionFactory/ReflectionFactoryTest.java +++ b/test/jdk/sun/reflect/ReflectionFactory/ReflectionFactoryTest.java @@ -29,12 +29,16 @@ import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; +import java.io.ObjectStreamClass; import java.io.ObjectStreamException; +import java.io.ObjectStreamField; import java.io.OptionalDataException; +import java.io.Serial; import java.io.Serializable; import java.lang.invoke.MethodHandle; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; +import java.util.Arrays; import sun.reflect.ReflectionFactory; @@ -46,7 +50,7 @@ /* * @test - * @bug 8137058 8164908 8168980 8275137 + * @bug 8137058 8164908 8168980 8275137 8333796 * @summary Basic test for the unsupported ReflectionFactory * @modules jdk.unsupported * @run testng ReflectionFactoryTest @@ -327,6 +331,509 @@ static void newOptionalDataException() { } + private static final String[] names = { + "boolean_", + "final_boolean", + "byte_", + "final_byte", + "char_", + "final_char", + "short_", + "final_short", + "int_", + "final_int", + "long_", + "final_long", + "float_", + "final_float", + "double_", + "final_double", + "str", + "final_str", + "writeFields", + }; + + // test that the generated read/write objects are working properly + @Test + static void testDefaultReadWriteObject() throws Throwable { + Ser2 ser = new Ser2((byte) 0x33, (short) 0x2244, (char) 0x5342, 0x05382716, 0xf035a73b09113bacL, 1234f, 3456.0, true, new Ser3(0x004917aa)); + ser.byte_ = (byte) 0x44; + ser.short_ = (short) 0x3355; + ser.char_ = (char) 0x6593; + ser.int_ = 0x4928a299; + ser.long_ = 0x24aa19883f4b9138L; + ser.float_ = 4321f; + ser.double_ = 6543.0; + ser.boolean_ = false; + ser.ser = new Ser3(0x70b030a0); + // first, ensure that each field gets written + MethodHandle writeObject = factory.defaultWriteObjectForSerialization(Ser2.class); + Assert.assertNotNull(writeObject, "writeObject not created"); + boolean[] called = new boolean[19]; + @SuppressWarnings("removal") + ObjectOutputStream oos = new ObjectOutputStream() { + protected void writeObjectOverride(final Object obj) throws IOException { + throw new IOException("Wrong method called"); + } + + public void defaultWriteObject() throws IOException { + throw new IOException("Wrong method called"); + } + + public void writeFields() { + called[18] = true; + } + + public PutField putFields() { + return new PutField() { + public void put(final String name, final boolean val) { + switch (name) { + case "boolean_" -> { + Assert.assertFalse(val); + called[0] = true; + } + case "final_boolean" -> { + Assert.assertTrue(val); + called[1] = true; + } + default -> throw new Error("Unexpected field " + name); + } + } + + public void put(final String name, final byte val) { + switch (name) { + case "byte_" -> { + Assert.assertEquals(val, (byte) 0x44); + called[2] = true; + } + case "final_byte" -> { + Assert.assertEquals(val, (byte) 0x33); + called[3] = true; + } + default -> throw new Error("Unexpected field " + name); + } + } + + public void put(final String name, final char val) { + switch (name) { + case "char_" -> { + Assert.assertEquals(val, (char) 0x6593); + called[4] = true; + } + case "final_char" -> { + Assert.assertEquals(val, (char) 0x5342); + called[5] = true; + } + default -> throw new Error("Unexpected field " + name); + } + } + + public void put(final String name, final short val) { + switch (name) { + case "short_" -> { + Assert.assertEquals(val, (short) 0x3355); + called[6] = true; + } + case "final_short" -> { + Assert.assertEquals(val, (short) 0x2244); + called[7] = true; + } + default -> throw new Error("Unexpected field " + name); + } + } + + public void put(final String name, final int val) { + switch (name) { + case "int_" -> { + Assert.assertEquals(val, 0x4928a299); + called[8] = true; + } + case "final_int" -> { + Assert.assertEquals(val, 0x05382716); + called[9] = true; + } + default -> throw new Error("Unexpected field " + name); + } + } + + public void put(final String name, final long val) { + switch (name) { + case "long_" -> { + Assert.assertEquals(val, 0x24aa19883f4b9138L); + called[10] = true; + } + case "final_long" -> { + Assert.assertEquals(val, 0xf035a73b09113bacL); + called[11] = true; + } + default -> throw new Error("Unexpected field " + name); + } + } + + public void put(final String name, final float val) { + switch (name) { + case "float_" -> { + Assert.assertEquals(val, 4321f); + called[12] = true; + } + case "final_float" -> { + Assert.assertEquals(val, 1234f); + called[13] = true; + } + default -> throw new Error("Unexpected field " + name); + } + } + + public void put(final String name, final double val) { + switch (name) { + case "double_" -> { + Assert.assertEquals(val, 6543.0); + called[14] = true; + } + case "final_double" -> { + Assert.assertEquals(val, 3456.0); + called[15] = true; + } + default -> throw new Error("Unexpected field " + name); + } + } + + public void put(final String name, final Object val) { + switch (name) { + case "ser" -> { + Assert.assertEquals(val, new Ser3(0x70b030a0)); + called[16] = true; + } + case "final_ser" -> { + Assert.assertEquals(val, new Ser3(0x004917aa)); + called[17] = true; + } + default -> throw new Error("Unexpected field " + name); + } + } + + @SuppressWarnings("removal") + public void write(final ObjectOutput out) throws IOException { + throw new IOException("Wrong method called"); + } + }; + } + }; + writeObject.invokeExact(ser, oos); + for (int i = 0; i < 19; i ++) { + Assert.assertTrue(called[i], names[i]); + } + // now, test the read side + MethodHandle readObject = factory.defaultReadObjectForSerialization(Ser2.class); + Assert.assertNotNull(readObject, "readObject not created"); + @SuppressWarnings("removal") + ObjectInputStream ois = new ObjectInputStream() { + protected Object readObjectOverride() throws IOException { + throw new IOException("Wrong method called"); + } + + public GetField readFields() { + return new GetField() { + public ObjectStreamClass getObjectStreamClass() { + throw new Error("Wrong method called"); + } + + public boolean defaulted(final String name) throws IOException { + throw new IOException("Wrong method called"); + } + + public boolean get(final String name, final boolean val) { + return switch (name) { + case "boolean_" -> { + called[0] = true; + yield true; + } + case "final_boolean" -> { + called[1] = true; + yield true; + } + default -> throw new Error("Unexpected field " + name); + }; + } + + public byte get(final String name, final byte val) { + return switch (name) { + case "byte_" -> { + called[2] = true; + yield (byte) 0x11; + } + case "final_byte" -> { + called[3] = true; + yield (byte) 0x9f; + } + default -> throw new Error("Unexpected field " + name); + }; + } + + public char get(final String name, final char val) { + return switch (name) { + case "char_" -> { + called[4] = true; + yield (char) 0x59a2; + } + case "final_char" -> { + called[5] = true; + yield (char) 0xe0d0; + } + default -> throw new Error("Unexpected field " + name); + }; + } + + public short get(final String name, final short val) { + return switch (name) { + case "short_" -> { + called[6] = true; + yield (short) 0x0917; + } + case "final_short" -> { + called[7] = true; + yield (short) 0x110e; + } + default -> throw new Error("Unexpected field " + name); + }; + } + + public int get(final String name, final int val) { + return switch (name) { + case "int_" -> { + called[8] = true; + yield 0xd0244e19; + } + case "final_int" -> { + called[9] = true; + yield 0x011004da; + } + default -> throw new Error("Unexpected field " + name); + }; + } + + public long get(final String name, final long val) { + return switch (name) { + case "long_" -> { + called[10] = true; + yield 0x0b8101d84aa31711L; + } + case "final_long" -> { + called[11] = true; + yield 0x30558aa7189ed821L; + } + default -> throw new Error("Unexpected field " + name); + }; + } + + public float get(final String name, final float val) { + return switch (name) { + case "float_" -> { + called[12] = true; + yield 0x5.01923ap18f; + } + case "final_float" -> { + called[13] = true; + yield 0x0.882afap1f; + } + default -> throw new Error("Unexpected field " + name); + }; + } + + public double get(final String name, final double val) { + return switch (name) { + case "double_" -> { + called[14] = true; + yield 0x9.4a8fp6; + } + case "final_double" -> { + called[15] = true; + yield 0xf.881a8p4; + } + default -> throw new Error("Unexpected field " + name); + }; + } + + public Object get(final String name, final Object val) { + return switch (name) { + case "ser" -> { + called[16] = true; + yield new Ser3(0x44cc55dd); + } + case "final_ser" -> { + called[17] = true; + yield new Ser3(0x9a8b7c6d); + } + default -> throw new Error("Unexpected field " + name); + }; + } + }; + } + }; + // all the same methods, except for `writeFields` + Arrays.fill(called, false); + Constructor ctor = factory.newConstructorForSerialization(Ser2.class, Object.class.getDeclaredConstructor()); + ser = (Ser2) ctor.newInstance(); + readObject.invokeExact(ser, ois); + // excluding "writeFields", so 18 instead of 19 + for (int i = 0; i < 18; i ++) { + Assert.assertTrue(called[i], names[i]); + } + Assert.assertEquals(ser.byte_, (byte)0x11); + Assert.assertEquals(ser.final_byte, (byte)0x9f); + Assert.assertEquals(ser.char_, (char)0x59a2); + Assert.assertEquals(ser.final_char, (char)0xe0d0); + Assert.assertEquals(ser.short_, (short)0x0917); + Assert.assertEquals(ser.final_short, (short)0x110e); + Assert.assertEquals(ser.int_, 0xd0244e19); + Assert.assertEquals(ser.final_int, 0x011004da); + Assert.assertEquals(ser.long_, 0x0b8101d84aa31711L); + Assert.assertEquals(ser.final_long, 0x30558aa7189ed821L); + Assert.assertEquals(ser.float_, 0x5.01923ap18f); + Assert.assertEquals(ser.final_float, 0x0.882afap1f); + Assert.assertEquals(ser.double_, 0x9.4a8fp6); + Assert.assertEquals(ser.final_double, 0xf.881a8p4); + Assert.assertEquals(ser.ser, new Ser3(0x44cc55dd)); + Assert.assertEquals(ser.final_ser, new Ser3(0x9a8b7c6d)); + } + + static class Ser2 implements Serializable { + @Serial + private static final long serialVersionUID = -2852896623833548574L; + + byte byte_; + short short_; + char char_; + int int_; + long long_; + float float_; + double double_; + boolean boolean_; + Ser3 ser; + + final byte final_byte; + final short final_short; + final char final_char; + final int final_int; + final long final_long; + final float final_float; + final double final_double; + final boolean final_boolean; + final Ser3 final_ser; + + Ser2(final byte final_byte, final short final_short, final char final_char, final int final_int, + final long final_long, final float final_float, final double final_double, + final boolean final_boolean, final Ser3 final_ser) { + + this.final_byte = final_byte; + this.final_short = final_short; + this.final_char = final_char; + this.final_int = final_int; + this.final_long = final_long; + this.final_float = final_float; + this.final_double = final_double; + this.final_boolean = final_boolean; + this.final_ser = final_ser; + } + } + + static class Ser3 implements Serializable { + @Serial + private static final long serialVersionUID = -1234752876749422678L; + + @Serial + private static final ObjectStreamField[] serialPersistentFields = { + new ObjectStreamField("value", int.class) + }; + + final int value; + + Ser3(final int value) { + this.value = value; + } + + public boolean equals(final Object obj) { + return obj instanceof Ser3 s && value == s.value; + } + + public int hashCode() { + return value; + } + } + + static class SerInvalidFields implements Serializable { + // this is deliberately wrong + @SuppressWarnings({"unused", "serial"}) + @Serial + private static final String serialPersistentFields = "Oops!"; + @Serial + private static final long serialVersionUID = -8090960816811629489L; + } + + static class Ext1 implements Externalizable { + + @Serial + private static final long serialVersionUID = 7109990719266285013L; + + public void writeExternal(final ObjectOutput objectOutput) { + } + + public void readExternal(final ObjectInput objectInput) { + } + } + + static class Ext2 implements Externalizable { + public void writeExternal(final ObjectOutput objectOutput) { + } + + public void readExternal(final ObjectInput objectInput) { + } + } + + record Rec1(int hello, boolean world) implements Serializable { + @Serial + private static final long serialVersionUID = 12349876L; + } + + enum Enum1 { + hello, + world, + ; + private static final long serialVersionUID = 1020304050L; + } + + interface Proxy1 { + void hello(); + } + + static class SerialPersistentFields implements Serializable { + @Serial + private static final long serialVersionUID = -4947917866973382882L; + @Serial + private static final ObjectStreamField[] serialPersistentFields = { + new ObjectStreamField("array1", Object[].class), + new ObjectStreamField("nonExistent", String.class) + }; + + private int int1; + private Object[] array1; + } + + // Check our simple accessors + @Test + static void testAccessors() { + Assert.assertEquals(factory.serialPersistentFields(Ser3.class), Ser3.serialPersistentFields); + Assert.assertNotSame(factory.serialPersistentFields(Ser3.class), Ser3.serialPersistentFields); + Assert.assertNull(factory.serialPersistentFields(SerInvalidFields.class)); + } + + // Ensure that classes with serialPersistentFields do not allow default setting/getting + @Test + static void testDisallowed() { + Assert.assertNull(factory.defaultWriteObjectForSerialization(SerialPersistentFields.class)); + Assert.assertNull(factory.defaultReadObjectForSerialization(SerialPersistentFields.class)); + } + // Main can be used to run the tests from the command line with only testng.jar. @SuppressWarnings("raw_types") @Test(enabled = false) From 75420e9314c54adc5b45f9b274a87af54dd6b5a8 Mon Sep 17 00:00:00 2001 From: Emanuel Peter Date: Wed, 20 Nov 2024 14:23:57 +0000 Subject: [PATCH 47/74] 8334431: C2 SuperWord: fix performance regression due to store-to-load-forwarding failures Reviewed-by: chagedorn, qamai --- .../cpu/aarch64/c2_globals_aarch64.hpp | 1 + src/hotspot/cpu/arm/c2_globals_arm.hpp | 1 + src/hotspot/cpu/ppc/c2_globals_ppc.hpp | 1 + src/hotspot/cpu/riscv/c2_globals_riscv.hpp | 1 + src/hotspot/cpu/s390/c2_globals_s390.hpp | 1 + src/hotspot/cpu/x86/c2_globals_x86.hpp | 1 + src/hotspot/share/opto/c2_globals.hpp | 6 + src/hotspot/share/opto/superword.cpp | 1 + src/hotspot/share/opto/vectorization.cpp | 12 +- src/hotspot/share/opto/vectorization.hpp | 1 + src/hotspot/share/opto/vtransform.cpp | 268 +++++++++++++++++ src/hotspot/share/opto/vtransform.hpp | 18 ++ .../loopopts/superword/TestAlignVector.java | 117 +++++++- .../superword/TestCyclicDependency.java | 273 ++++++++++++++++-- .../superword/TestDependencyOffsets.java | 95 ++++-- .../runner/LoopCombinedOpTest.java | 5 +- .../compiler/VectorStoreToLoadForwarding.java | 142 +++++++++ 17 files changed, 881 insertions(+), 63 deletions(-) create mode 100644 test/micro/org/openjdk/bench/vm/compiler/VectorStoreToLoadForwarding.java diff --git a/src/hotspot/cpu/aarch64/c2_globals_aarch64.hpp b/src/hotspot/cpu/aarch64/c2_globals_aarch64.hpp index 34e6e688abbca..e57dab7d1edac 100644 --- a/src/hotspot/cpu/aarch64/c2_globals_aarch64.hpp +++ b/src/hotspot/cpu/aarch64/c2_globals_aarch64.hpp @@ -66,6 +66,7 @@ define_pd_global(bool, OptoScheduling, false); define_pd_global(bool, OptoBundling, false); define_pd_global(bool, OptoRegScheduling, false); define_pd_global(bool, SuperWordLoopUnrollAnalysis, true); +define_pd_global(uint, SuperWordStoreToLoadForwardingFailureDetection, 8); define_pd_global(bool, IdealizeClearArrayNode, true); define_pd_global(intx, ReservedCodeCacheSize, 48*M); diff --git a/src/hotspot/cpu/arm/c2_globals_arm.hpp b/src/hotspot/cpu/arm/c2_globals_arm.hpp index 57ed8f11c08b1..a44a8f649aee1 100644 --- a/src/hotspot/cpu/arm/c2_globals_arm.hpp +++ b/src/hotspot/cpu/arm/c2_globals_arm.hpp @@ -64,6 +64,7 @@ define_pd_global(bool, OptoBundling, false); define_pd_global(bool, OptoScheduling, true); define_pd_global(bool, OptoRegScheduling, false); define_pd_global(bool, SuperWordLoopUnrollAnalysis, false); +define_pd_global(uint, SuperWordStoreToLoadForwardingFailureDetection, 16); define_pd_global(bool, IdealizeClearArrayNode, true); #ifdef _LP64 diff --git a/src/hotspot/cpu/ppc/c2_globals_ppc.hpp b/src/hotspot/cpu/ppc/c2_globals_ppc.hpp index 00a92ff6b6251..f45faa21f01ba 100644 --- a/src/hotspot/cpu/ppc/c2_globals_ppc.hpp +++ b/src/hotspot/cpu/ppc/c2_globals_ppc.hpp @@ -59,6 +59,7 @@ define_pd_global(bool, UseCISCSpill, false); define_pd_global(bool, OptoBundling, false); define_pd_global(bool, OptoRegScheduling, false); define_pd_global(bool, SuperWordLoopUnrollAnalysis, true); +define_pd_global(uint, SuperWordStoreToLoadForwardingFailureDetection, 16); // GL: // Detected a problem with unscaled compressed oops and // narrow_oop_use_complex_address() == false. diff --git a/src/hotspot/cpu/riscv/c2_globals_riscv.hpp b/src/hotspot/cpu/riscv/c2_globals_riscv.hpp index 53a41665f4b8e..e9947f9888a92 100644 --- a/src/hotspot/cpu/riscv/c2_globals_riscv.hpp +++ b/src/hotspot/cpu/riscv/c2_globals_riscv.hpp @@ -66,6 +66,7 @@ define_pd_global(bool, OptoScheduling, true); define_pd_global(bool, OptoBundling, false); define_pd_global(bool, OptoRegScheduling, false); define_pd_global(bool, SuperWordLoopUnrollAnalysis, true); +define_pd_global(uint, SuperWordStoreToLoadForwardingFailureDetection, 16); define_pd_global(bool, IdealizeClearArrayNode, true); define_pd_global(intx, ReservedCodeCacheSize, 48*M); diff --git a/src/hotspot/cpu/s390/c2_globals_s390.hpp b/src/hotspot/cpu/s390/c2_globals_s390.hpp index 1de38f100f627..7f780ca63a017 100644 --- a/src/hotspot/cpu/s390/c2_globals_s390.hpp +++ b/src/hotspot/cpu/s390/c2_globals_s390.hpp @@ -61,6 +61,7 @@ define_pd_global(bool, OptoBundling, false); define_pd_global(bool, OptoScheduling, false); define_pd_global(bool, OptoRegScheduling, false); define_pd_global(bool, SuperWordLoopUnrollAnalysis, true); +define_pd_global(uint, SuperWordStoreToLoadForwardingFailureDetection, 16); // On s390x, we can clear the array with a single instruction, // so don't idealize it. define_pd_global(bool, IdealizeClearArrayNode, false); diff --git a/src/hotspot/cpu/x86/c2_globals_x86.hpp b/src/hotspot/cpu/x86/c2_globals_x86.hpp index f7315011e6b19..084dde217e490 100644 --- a/src/hotspot/cpu/x86/c2_globals_x86.hpp +++ b/src/hotspot/cpu/x86/c2_globals_x86.hpp @@ -76,6 +76,7 @@ define_pd_global(bool, OptoScheduling, false); define_pd_global(bool, OptoBundling, false); define_pd_global(bool, OptoRegScheduling, true); define_pd_global(bool, SuperWordLoopUnrollAnalysis, true); +define_pd_global(uint, SuperWordStoreToLoadForwardingFailureDetection, 16); define_pd_global(bool, IdealizeClearArrayNode, true); define_pd_global(uintx, ReservedCodeCacheSize, 48*M); diff --git a/src/hotspot/share/opto/c2_globals.hpp b/src/hotspot/share/opto/c2_globals.hpp index 45a067a830ba6..d4b55ec2d8d12 100644 --- a/src/hotspot/share/opto/c2_globals.hpp +++ b/src/hotspot/share/opto/c2_globals.hpp @@ -355,6 +355,12 @@ product(bool, SuperWordReductions, true, \ "Enable reductions support in superword.") \ \ + product_pd(uint, SuperWordStoreToLoadForwardingFailureDetection, DIAGNOSTIC, \ + "if >0, auto-vectorization detects possible store-to-load " \ + "forwarding failures. The number specifies over how many " \ + "loop iterations this detection spans.") \ + range(0, 4096) \ + \ product(bool, UseCMoveUnconditionally, false, \ "Use CMove (scalar and vector) ignoring profitability test.") \ \ diff --git a/src/hotspot/share/opto/superword.cpp b/src/hotspot/share/opto/superword.cpp index 20c8dfbff1776..8000e4fd39ed0 100644 --- a/src/hotspot/share/opto/superword.cpp +++ b/src/hotspot/share/opto/superword.cpp @@ -1868,6 +1868,7 @@ bool SuperWord::schedule_and_apply() const { } if (!vtransform.schedule()) { return false; } + if (vtransform.has_store_to_load_forwarding_failure()) { return false; } vtransform.apply(); return true; } diff --git a/src/hotspot/share/opto/vectorization.cpp b/src/hotspot/share/opto/vectorization.cpp index fc4eaccff5ce5..4d152189625ea 100644 --- a/src/hotspot/share/opto/vectorization.cpp +++ b/src/hotspot/share/opto/vectorization.cpp @@ -31,7 +31,7 @@ #include "opto/vectorization.hpp" #ifndef PRODUCT -static void print_con_or_idx(const Node* n) { +void VPointer::print_con_or_idx(const Node* n) { if (n == nullptr) { tty->print("( 0)"); } else if (n->is_ConI()) { @@ -1369,12 +1369,12 @@ void VPointer::print() const { tty->print("adr: %4d, ", _adr != nullptr ? _adr->_idx : 0); tty->print(" base"); - print_con_or_idx(_base); + VPointer::print_con_or_idx(_base); tty->print(" + offset(%4d)", _offset); tty->print(" + invar"); - print_con_or_idx(_invar); + VPointer::print_con_or_idx(_invar); tty->print_cr(" + scale(%4d) * iv]", _scale); } @@ -2168,15 +2168,15 @@ void AlignmentSolver::trace_start_solve() const { // iv = init + pre_iter * pre_stride + main_iter * main_stride tty->print(" iv = init"); - print_con_or_idx(_init_node); + VPointer::print_con_or_idx(_init_node); tty->print_cr(" + pre_iter * pre_stride(%d) + main_iter * main_stride(%d)", _pre_stride, _main_stride); // adr = base + offset + invar + scale * iv tty->print(" adr = base"); - print_con_or_idx(_base); + VPointer::print_con_or_idx(_base); tty->print(" + offset(%d) + invar", _offset); - print_con_or_idx(_invar); + VPointer::print_con_or_idx(_invar); tty->print_cr(" + scale(%d) * iv", _scale); } } diff --git a/src/hotspot/share/opto/vectorization.hpp b/src/hotspot/share/opto/vectorization.hpp index b084edd44b339..98aa3336dedf2 100644 --- a/src/hotspot/share/opto/vectorization.hpp +++ b/src/hotspot/share/opto/vectorization.hpp @@ -870,6 +870,7 @@ class VPointer : public ArenaObj { static int cmp_for_sort(const VPointer** p1, const VPointer** p2); NOT_PRODUCT( void print() const; ) + NOT_PRODUCT( static void print_con_or_idx(const Node* n); ) #ifndef PRODUCT class Tracer { diff --git a/src/hotspot/share/opto/vtransform.cpp b/src/hotspot/share/opto/vtransform.cpp index 7c7aca3b90e7c..d09a4c899f685 100644 --- a/src/hotspot/share/opto/vtransform.cpp +++ b/src/hotspot/share/opto/vtransform.cpp @@ -144,6 +144,274 @@ void VTransformApplyResult::trace(VTransformNode* vtnode) const { } #endif +// We use two comparisons, because a subtraction could underflow. +#define RETURN_CMP_VALUE_IF_NOT_EQUAL(a, b) \ + if (a < b) { return -1; } \ + if (a > b) { return 1; } + +// Helper-class for VTransformGraph::has_store_to_load_forwarding_failure. +// It represents a memory region: [ptr, ptr + memory_size) +class VMemoryRegion : public StackObj { +private: + Node* _base; // ptr = base + offset + invar + scale * iv + int _scale; + Node* _invar; + int _offset; + uint _memory_size; + bool _is_load; // load or store? + uint _schedule_order; + +public: + VMemoryRegion() {} // empty constructor for GrowableArray + VMemoryRegion(const VPointer& vpointer, int iv_offset, int vector_length, uint schedule_order) : + _base(vpointer.base()), + _scale(vpointer.scale_in_bytes()), + _invar(vpointer.invar()), + _offset(vpointer.offset_in_bytes() + _scale * iv_offset), + _memory_size(vpointer.memory_size() * vector_length), + _is_load(vpointer.mem()->is_Load()), + _schedule_order(schedule_order) {} + + Node* base() const { return _base; } + int scale() const { return _scale; } + Node* invar() const { return _invar; } + int offset() const { return _offset; } + uint memory_size() const { return _memory_size; } + bool is_load() const { return _is_load; } + uint schedule_order() const { return _schedule_order; } + + static int cmp_for_sort_by_group(VMemoryRegion* r1, VMemoryRegion* r2) { + RETURN_CMP_VALUE_IF_NOT_EQUAL(r1->base()->_idx, r2->base()->_idx); + RETURN_CMP_VALUE_IF_NOT_EQUAL(r1->scale(), r2->scale()); + int r1_invar_idx = r1->invar() == nullptr ? 0 : r1->invar()->_idx; + int r2_invar_idx = r2->invar() == nullptr ? 0 : r2->invar()->_idx; + RETURN_CMP_VALUE_IF_NOT_EQUAL(r1_invar_idx, r2_invar_idx); + return 0; // equal + } + + static int cmp_for_sort(VMemoryRegion* r1, VMemoryRegion* r2) { + int cmp_group = cmp_for_sort_by_group(r1, r2); + if (cmp_group != 0) { return cmp_group; } + + RETURN_CMP_VALUE_IF_NOT_EQUAL(r1->offset(), r2->offset()); + return 0; // equal + } + + enum Aliasing { DIFFERENT_GROUP, BEFORE, EXACT_OVERLAP, PARTIAL_OVERLAP, AFTER }; + + Aliasing aliasing(VMemoryRegion& other) { + VMemoryRegion* p1 = this; + VMemoryRegion* p2 = &other; + if (cmp_for_sort_by_group(p1, p2) != 0) { return DIFFERENT_GROUP; } + + jlong offset1 = p1->offset(); + jlong offset2 = p2->offset(); + jlong memory_size1 = p1->memory_size(); + jlong memory_size2 = p2->memory_size(); + + if (offset1 >= offset2 + memory_size2) { return AFTER; } + if (offset2 >= offset1 + memory_size1) { return BEFORE; } + if (offset1 == offset2 && memory_size1 == memory_size2) { return EXACT_OVERLAP; } + return PARTIAL_OVERLAP; + } + +#ifndef PRODUCT + void print() const { + tty->print("VMemoryRegion[%s %dbytes, schedule_order(%4d), base", + _is_load ? "load " : "store", _memory_size, _schedule_order); + VPointer::print_con_or_idx(_base); + tty->print(" + offset(%4d)", _offset); + tty->print(" + invar"); + VPointer::print_con_or_idx(_invar); + tty->print_cr(" + scale(%4d) * iv]", _scale); + } +#endif +}; + +// Store-to-load-forwarding is a CPU memory optimization, where a load can directly fetch +// its value from the store-buffer, rather than from the L1 cache. This is many CPU cycles +// faster. However, this optimization comes with some restrictions, depending on the CPU. +// Generally, store-to-load-forwarding works if the load and store memory regions match +// exactly (same start and width). Generally problematic are partial overlaps - though +// some CPU's can handle even some subsets of these cases. We conservatively assume that +// all such partial overlaps lead to a store-to-load-forwarding failures, which means the +// load has to stall until the store goes from the store-buffer into the L1 cache, incurring +// a penalty of many CPU cycles. +// +// Example (with "iteration distance" 2): +// for (int i = 10; i < SIZE; i++) { +// aI[i] = aI[i - 2] + 1; +// } +// +// load_4_bytes( ptr + -8) +// store_4_bytes(ptr + 0) * +// load_4_bytes( ptr + -4) | +// store_4_bytes(ptr + 4) | * +// load_4_bytes( ptr + 0) <-+ | +// store_4_bytes(ptr + 8) | +// load_4_bytes( ptr + 4) <---+ +// store_4_bytes(ptr + 12) +// ... +// +// In the scalar loop, we can forward the stores from 2 iterations back. +// +// Assume we have 2-element vectors (2*4 = 8 bytes), with the "iteration distance" 2 +// example. This gives us this machine code: +// load_8_bytes( ptr + -8) +// store_8_bytes(ptr + 0) | +// load_8_bytes( ptr + 0) v +// store_8_bytes(ptr + 8) | +// load_8_bytes( ptr + 8) v +// store_8_bytes(ptr + 16) +// ... +// +// We packed 2 iterations, and the stores can perfectly forward to the loads of +// the next 2 iterations. +// +// Example (with "iteration distance" 3): +// for (int i = 10; i < SIZE; i++) { +// aI[i] = aI[i - 3] + 1; +// } +// +// load_4_bytes( ptr + -12) +// store_4_bytes(ptr + 0) * +// load_4_bytes( ptr + -8) | +// store_4_bytes(ptr + 4) | +// load_4_bytes( ptr + -4) | +// store_4_bytes(ptr + 8) | +// load_4_bytes( ptr + 0) <-+ +// store_4_bytes(ptr + 12) +// ... +// +// In the scalar loop, we can forward the stores from 3 iterations back. +// +// Unfortunately, vectorization can introduce such store-to-load-forwarding failures. +// Assume we have 2-element vectors (2*4 = 8 bytes), with the "iteration distance" 3 +// example. This gives us this machine code: +// load_8_bytes( ptr + -12) +// store_8_bytes(ptr + 0) | | +// load_8_bytes( ptr + -4) x | +// store_8_bytes(ptr + 8) || +// load_8_bytes( ptr + 4) xx <-- partial overlap with 2 stores +// store_8_bytes(ptr + 16) +// ... +// +// We see that eventually all loads are dependent on earlier stores, but the values cannot +// be forwarded because there is some partial overlap. +// +// Preferably, we would have some latency-based cost-model that accounts for such forwarding +// failures, and decide if vectorization with forwarding failures is still profitable. For +// now we go with a simpler heuristic: we simply forbid vectorization if we can PROVE that +// there will be a forwarding failure. This approach has at least 2 possible weaknesses: +// +// (1) There may be forwarding failures in cases where we cannot prove it. +// Example: +// for (int i = 10; i < SIZE; i++) { +// bI[i] = aI[i - 3] + 1; +// } +// +// We do not know if aI and bI refer to the same array or not. However, it is reasonable +// to assume that if we have two different array references, that they most likely refer +// to different arrays (i.e. no aliasing), where we would have no forwarding failures. +// (2) There could be some loops where vectorization introduces forwarding failures, and thus +// the latency of the loop body is high, but this does not matter because it is dominated +// by other latency/throughput based costs in the loop body. +// +// Performance measurements with the JMH benchmark StoreToLoadForwarding.java have indicated +// that there is some iteration threshold: if the failure happens between a store and load that +// have an iteration distance below this threshold, the latency is the limiting factor, and we +// should not vectorize to avoid the latency penalty of store-to-load-forwarding failures. If +// the iteration distance is larger than this threshold, the throughput is the limiting factor, +// and we should vectorize in these cases to improve throughput. +// +bool VTransformGraph::has_store_to_load_forwarding_failure(const VLoopAnalyzer& vloop_analyzer) const { + if (SuperWordStoreToLoadForwardingFailureDetection == 0) { return false; } + + // Collect all pointers for scalar and vector loads/stores. + ResourceMark rm; + GrowableArray memory_regions; + + // To detect store-to-load-forwarding failures at the iteration threshold or below, we + // simulate a super-unrolling to reach SuperWordStoreToLoadForwardingFailureDetection + // iterations at least. This is a heuristic, and we are not trying to be very precise + // with the iteration distance. If we have already unrolled more than the iteration + // threshold, i.e. if "SuperWordStoreToLoadForwardingFailureDetection < unrolled_count", + // then we simply check if there are any store-to-load-forwarding failures in the unrolled + // loop body, which may be at larger distance than the desired threshold. We cannot do any + // more fine-grained analysis, because the unrolling has lost the information about the + // iteration distance. + int simulated_unrolling_count = SuperWordStoreToLoadForwardingFailureDetection; + int unrolled_count = vloop_analyzer.vloop().cl()->unrolled_count(); + uint simulated_super_unrolling_count = MAX2(1, simulated_unrolling_count / unrolled_count); + int iv_stride = vloop_analyzer.vloop().iv_stride(); + int schedule_order = 0; + for (uint k = 0; k < simulated_super_unrolling_count; k++) { + int iv_offset = k * iv_stride; // virtual super-unrolling + for (int i = 0; i < _schedule.length(); i++) { + VTransformNode* vtn = _schedule.at(i); + if (vtn->is_load_or_store_in_loop()) { + const VPointer& p = vtn->vpointer(vloop_analyzer); + if (p.valid()) { + VTransformVectorNode* vector = vtn->isa_Vector(); + uint vector_length = vector != nullptr ? vector->nodes().length() : 1; + memory_regions.push(VMemoryRegion(p, iv_offset, vector_length, schedule_order++)); + } + } + } + } + + // Sort the pointers by group (same base, invar and stride), and then by offset. + memory_regions.sort(VMemoryRegion::cmp_for_sort); + +#ifndef PRODUCT + if (_trace._verbose) { + tty->print_cr("VTransformGraph::has_store_to_load_forwarding_failure:"); + tty->print_cr(" simulated_unrolling_count = %d", simulated_unrolling_count); + tty->print_cr(" simulated_super_unrolling_count = %d", simulated_super_unrolling_count); + for (int i = 0; i < memory_regions.length(); i++) { + VMemoryRegion& region = memory_regions.at(i); + region.print(); + } + } +#endif + + // For all pairs of pointers in the same group, check if they have a partial overlap. + for (int i = 0; i < memory_regions.length(); i++) { + VMemoryRegion& region1 = memory_regions.at(i); + + for (int j = i + 1; j < memory_regions.length(); j++) { + VMemoryRegion& region2 = memory_regions.at(j); + + const VMemoryRegion::Aliasing aliasing = region1.aliasing(region2); + if (aliasing == VMemoryRegion::Aliasing::DIFFERENT_GROUP || + aliasing == VMemoryRegion::Aliasing::BEFORE) { + break; // We have reached the next group or pointers that are always after. + } else if (aliasing == VMemoryRegion::Aliasing::EXACT_OVERLAP) { + continue; + } else { + assert(aliasing == VMemoryRegion::Aliasing::PARTIAL_OVERLAP, "no other case can happen"); + if ((region1.is_load() && !region2.is_load() && region1.schedule_order() > region2.schedule_order()) || + (!region1.is_load() && region2.is_load() && region1.schedule_order() < region2.schedule_order())) { + // We predict that this leads to a store-to-load-forwarding failure penalty. +#ifndef PRODUCT + if (_trace._rejections) { + tty->print_cr("VTransformGraph::has_store_to_load_forwarding_failure:"); + tty->print_cr(" Partial overlap of store->load. We predict that this leads to"); + tty->print_cr(" a store-to-load-forwarding failure penalty which makes"); + tty->print_cr(" vectorization unprofitable. These are the two pointers:"); + region1.print(); + region2.print(); + } +#endif + return true; + } + } + } + } + + return false; +} + Node* VTransformNode::find_transformed_input(int i, const GrowableArray& vnode_idx_to_transformed_node) const { Node* n = vnode_idx_to_transformed_node.at(in(i)->_idx); assert(n != nullptr, "must find input IR node"); diff --git a/src/hotspot/share/opto/vtransform.hpp b/src/hotspot/share/opto/vtransform.hpp index ee298e7fe723f..8ceca318f4ae1 100644 --- a/src/hotspot/share/opto/vtransform.hpp +++ b/src/hotspot/share/opto/vtransform.hpp @@ -66,6 +66,8 @@ class VTransformVectorNode; class VTransformElementWiseVectorNode; class VTransformBoolVectorNode; class VTransformReductionVectorNode; +class VTransformLoadVectorNode; +class VTransformStoreVectorNode; // Result from VTransformNode::apply class VTransformApplyResult { @@ -157,6 +159,7 @@ class VTransformGraph : public StackObj { const GrowableArray& vtnodes() const { return _vtnodes; } bool schedule(); + bool has_store_to_load_forwarding_failure(const VLoopAnalyzer& vloop_analyzer) const; void apply_memops_reordering_with_schedule() const; void apply_vectorization_for_each_vtnode(uint& max_vector_length, uint& max_vector_width) const; @@ -221,6 +224,7 @@ class VTransform : public StackObj { VTransformGraph& graph() { return _graph; } bool schedule() { return _graph.schedule(); } + bool has_store_to_load_forwarding_failure() const { return _graph.has_store_to_load_forwarding_failure(_vloop_analyzer); } void apply(); private: @@ -310,6 +314,11 @@ class VTransformNode : public ArenaObj { virtual VTransformElementWiseVectorNode* isa_ElementWiseVector() { return nullptr; } virtual VTransformBoolVectorNode* isa_BoolVector() { return nullptr; } virtual VTransformReductionVectorNode* isa_ReductionVector() { return nullptr; } + virtual VTransformLoadVectorNode* isa_LoadVector() { return nullptr; } + virtual VTransformStoreVectorNode* isa_StoreVector() { return nullptr; } + + virtual bool is_load_or_store_in_loop() const { return false; } + virtual const VPointer& vpointer(const VLoopAnalyzer& vloop_analyzer) const { ShouldNotReachHere(); } virtual VTransformApplyResult apply(const VLoopAnalyzer& vloop_analyzer, const GrowableArray& vnode_idx_to_transformed_node) const = 0; @@ -333,6 +342,8 @@ class VTransformScalarNode : public VTransformNode { VTransformNode(vtransform, n->req()), _node(n) {} Node* node() const { return _node; } virtual VTransformScalarNode* isa_Scalar() override { return this; } + virtual bool is_load_or_store_in_loop() const override { return _node->is_Load() || _node->is_Store(); } + virtual const VPointer& vpointer(const VLoopAnalyzer& vloop_analyzer) const override { return vloop_analyzer.vpointers().vpointer(node()->as_Mem()); } virtual VTransformApplyResult apply(const VLoopAnalyzer& vloop_analyzer, const GrowableArray& vnode_idx_to_transformed_node) const override; NOT_PRODUCT(virtual const char* name() const override { return "Scalar"; };) @@ -347,6 +358,7 @@ class VTransformInputScalarNode : public VTransformScalarNode { VTransformInputScalarNode(VTransform& vtransform, Node* n) : VTransformScalarNode(vtransform, n) {} virtual VTransformInputScalarNode* isa_InputScalar() override { return this; } + virtual bool is_load_or_store_in_loop() const override { return false; } NOT_PRODUCT(virtual const char* name() const override { return "InputScalar"; };) }; @@ -472,6 +484,9 @@ class VTransformLoadVectorNode : public VTransformVectorNode { VTransformLoadVectorNode(VTransform& vtransform, uint number_of_nodes) : VTransformVectorNode(vtransform, 3, number_of_nodes) {} LoadNode::ControlDependency control_dependency() const; + virtual VTransformLoadVectorNode* isa_LoadVector() override { return this; } + virtual bool is_load_or_store_in_loop() const override { return true; } + virtual const VPointer& vpointer(const VLoopAnalyzer& vloop_analyzer) const override { return vloop_analyzer.vpointers().vpointer(nodes().at(0)->as_Mem()); } virtual VTransformApplyResult apply(const VLoopAnalyzer& vloop_analyzer, const GrowableArray& vnode_idx_to_transformed_node) const override; NOT_PRODUCT(virtual const char* name() const override { return "LoadVector"; };) @@ -482,6 +497,9 @@ class VTransformStoreVectorNode : public VTransformVectorNode { // req = 4 -> [ctrl, mem, adr, val] VTransformStoreVectorNode(VTransform& vtransform, uint number_of_nodes) : VTransformVectorNode(vtransform, 4, number_of_nodes) {} + virtual VTransformStoreVectorNode* isa_StoreVector() override { return this; } + virtual bool is_load_or_store_in_loop() const override { return true; } + virtual const VPointer& vpointer(const VLoopAnalyzer& vloop_analyzer) const override { return vloop_analyzer.vpointers().vpointer(nodes().at(0)->as_Mem()); } virtual VTransformApplyResult apply(const VLoopAnalyzer& vloop_analyzer, const GrowableArray& vnode_idx_to_transformed_node) const override; NOT_PRODUCT(virtual const char* name() const override { return "StoreVector"; };) diff --git a/test/hotspot/jtreg/compiler/loopopts/superword/TestAlignVector.java b/test/hotspot/jtreg/compiler/loopopts/superword/TestAlignVector.java index efd328dc5cce9..60d753ee75f6b 100644 --- a/test/hotspot/jtreg/compiler/loopopts/superword/TestAlignVector.java +++ b/test/hotspot/jtreg/compiler/loopopts/superword/TestAlignVector.java @@ -168,6 +168,9 @@ public TestAlignVector() { tests.put("test14aB", () -> { return test14aB(aB.clone()); }); tests.put("test14bB", () -> { return test14bB(aB.clone()); }); tests.put("test14cB", () -> { return test14cB(aB.clone()); }); + tests.put("test14dB", () -> { return test14dB(aB.clone()); }); + tests.put("test14eB", () -> { return test14eB(aB.clone()); }); + tests.put("test14fB", () -> { return test14fB(aB.clone()); }); tests.put("test15aB", () -> { return test15aB(aB.clone()); }); tests.put("test15bB", () -> { return test15bB(aB.clone()); }); @@ -239,6 +242,9 @@ public TestAlignVector() { "test14aB", "test14bB", "test14cB", + "test14dB", + "test14eB", + "test14fB", "test15aB", "test15bB", "test15cB", @@ -1128,9 +1134,9 @@ static Object[] test13bBSIL(byte[] a, short[] b, int[] c, long[] d) { } @Test - @IR(counts = {IRNode.LOAD_VECTOR_B, "> 0", - IRNode.ADD_VB, "> 0", - IRNode.STORE_VECTOR, "> 0"}, + @IR(counts = {IRNode.LOAD_VECTOR_B, "= 0", + IRNode.ADD_VB, "= 0", + IRNode.STORE_VECTOR, "= 0"}, applyIfCPUFeatureOr = {"sse4.1", "true", "asimd", "true"}, applyIfPlatform = {"64-bit", "true"}, applyIf = {"AlignVector", "false"}) @@ -1143,6 +1149,9 @@ static Object[] test13bBSIL(byte[] a, short[] b, int[] c, long[] d) { static Object[] test14aB(byte[] a) { // non-power-of-2 stride for (int i = 0; i < RANGE-20; i+=9) { + // Since the stride is shorter than the vector length, there will be always + // partial overlap of loads with previous stores, this leads to failure in + // store-to-load-forwarding -> vectorization not profitable. a[i+0]++; a[i+1]++; a[i+2]++; @@ -1164,9 +1173,9 @@ static Object[] test14aB(byte[] a) { } @Test - @IR(counts = {IRNode.LOAD_VECTOR_B, "> 0", - IRNode.ADD_VB, "> 0", - IRNode.STORE_VECTOR, "> 0"}, + @IR(counts = {IRNode.LOAD_VECTOR_B, "= 0", + IRNode.ADD_VB, "= 0", + IRNode.STORE_VECTOR, "= 0"}, applyIfCPUFeatureOr = {"sse4.1", "true", "asimd", "true"}, applyIfPlatform = {"64-bit", "true"}, applyIf = {"AlignVector", "false"}) @@ -1179,6 +1188,9 @@ static Object[] test14aB(byte[] a) { static Object[] test14bB(byte[] a) { // non-power-of-2 stride for (int i = 0; i < RANGE-20; i+=3) { + // Since the stride is shorter than the vector length, there will be always + // partial overlap of loads with previous stores, this leads to failure in + // store-to-load-forwarding -> vectorization not profitable. a[i+0]++; a[i+1]++; a[i+2]++; @@ -1200,9 +1212,9 @@ static Object[] test14bB(byte[] a) { } @Test - @IR(counts = {IRNode.LOAD_VECTOR_B, "> 0", - IRNode.ADD_VB, "> 0", - IRNode.STORE_VECTOR, "> 0"}, + @IR(counts = {IRNode.LOAD_VECTOR_B, "= 0", + IRNode.ADD_VB, "= 0", + IRNode.STORE_VECTOR, "= 0"}, applyIfCPUFeatureOr = {"sse4.1", "true", "asimd", "true"}, applyIfPlatform = {"64-bit", "true"}, applyIf = {"AlignVector", "false"}) @@ -1215,6 +1227,9 @@ static Object[] test14bB(byte[] a) { static Object[] test14cB(byte[] a) { // non-power-of-2 stride for (int i = 0; i < RANGE-20; i+=5) { + // Since the stride is shorter than the vector length, there will be always + // partial overlap of loads with previous stores, this leads to failure in + // store-to-load-forwarding -> vectorization not profitable. a[i+0]++; a[i+1]++; a[i+2]++; @@ -1235,6 +1250,90 @@ static Object[] test14cB(byte[] a) { return new Object[]{ a }; } + @Test + @IR(counts = {IRNode.LOAD_VECTOR_B, IRNode.VECTOR_SIZE + "min(max_byte, 8)", "> 0", + IRNode.ADD_VB, IRNode.VECTOR_SIZE + "min(max_byte, 8)", "> 0", + IRNode.STORE_VECTOR, "> 0"}, + applyIfCPUFeatureOr = {"sse4.1", "true", "asimd", "true"}, + applyIfPlatform = {"64-bit", "true"}, + applyIf = {"AlignVector", "false"}) + @IR(counts = {IRNode.LOAD_VECTOR_B, "= 0", + IRNode.ADD_VB, "= 0", + IRNode.STORE_VECTOR, "= 0"}, + applyIfCPUFeatureOr = {"sse4.1", "true", "asimd", "true"}, + applyIfPlatform = {"64-bit", "true"}, + applyIf = {"AlignVector", "true"}) + static Object[] test14dB(byte[] a) { + // non-power-of-2 stride + for (int i = 0; i < RANGE-20; i+=9) { + a[i+0]++; + a[i+1]++; + a[i+2]++; + a[i+3]++; + a[i+4]++; + a[i+5]++; + a[i+6]++; + a[i+7]++; + } + return new Object[]{ a }; + } + + @Test + @IR(counts = {IRNode.LOAD_VECTOR_B, IRNode.VECTOR_SIZE + "min(max_byte, 8)", "> 0", + IRNode.ADD_VB, IRNode.VECTOR_SIZE + "min(max_byte, 8)", "> 0", + IRNode.STORE_VECTOR, "> 0"}, + applyIfCPUFeatureOr = {"sse4.1", "true", "asimd", "true"}, + applyIfPlatform = {"64-bit", "true"}, + applyIf = {"AlignVector", "false"}) + @IR(counts = {IRNode.LOAD_VECTOR_B, "= 0", + IRNode.ADD_VB, "= 0", + IRNode.STORE_VECTOR, "= 0"}, + applyIfCPUFeatureOr = {"sse4.1", "true", "asimd", "true"}, + applyIfPlatform = {"64-bit", "true"}, + applyIf = {"AlignVector", "true"}) + static Object[] test14eB(byte[] a) { + // non-power-of-2 stride + for (int i = 0; i < RANGE-32; i+=11) { + a[i+0]++; + a[i+1]++; + a[i+2]++; + a[i+3]++; + a[i+4]++; + a[i+5]++; + a[i+6]++; + a[i+7]++; + } + return new Object[]{ a }; + } + + @Test + @IR(counts = {IRNode.LOAD_VECTOR_B, IRNode.VECTOR_SIZE + "min(max_byte, 8)", "> 0", + IRNode.ADD_VB, IRNode.VECTOR_SIZE + "min(max_byte, 8)", "> 0", + IRNode.STORE_VECTOR, "> 0"}, + applyIfCPUFeatureOr = {"sse4.1", "true", "asimd", "true"}, + applyIfPlatform = {"64-bit", "true"}, + applyIf = {"AlignVector", "false"}) + @IR(counts = {IRNode.LOAD_VECTOR_B, "= 0", + IRNode.ADD_VB, "= 0", + IRNode.STORE_VECTOR, "= 0"}, + applyIfCPUFeatureOr = {"sse4.1", "true", "asimd", "true"}, + applyIfPlatform = {"64-bit", "true"}, + applyIf = {"AlignVector", "true"}) + static Object[] test14fB(byte[] a) { + // non-power-of-2 stride + for (int i = 0; i < RANGE-40; i+=12) { + a[i+0]++; + a[i+1]++; + a[i+2]++; + a[i+3]++; + a[i+4]++; + a[i+5]++; + a[i+6]++; + a[i+7]++; + } + return new Object[]{ a }; + } + @Test // IR rules difficult because of modulo wrapping with offset after peeling. static Object[] test15aB(byte[] a) { diff --git a/test/hotspot/jtreg/compiler/loopopts/superword/TestCyclicDependency.java b/test/hotspot/jtreg/compiler/loopopts/superword/TestCyclicDependency.java index 3849f1b05cf27..7c6b7c92c379d 100644 --- a/test/hotspot/jtreg/compiler/loopopts/superword/TestCyclicDependency.java +++ b/test/hotspot/jtreg/compiler/loopopts/superword/TestCyclicDependency.java @@ -24,7 +24,7 @@ /* * @test - * @bug 8298935 + * @bug 8298935 8334431 * @summary Writing forward on array creates cyclic dependency * which leads to wrong result, when ignored. * @library /test/lib / @@ -55,15 +55,30 @@ public class TestCyclicDependency { float[] goldF6a = new float[RANGE]; int[] goldI6b = new int[RANGE]; float[] goldF6b = new float[RANGE]; - int[] goldI7 = new int[RANGE]; - float[] goldF7 = new float[RANGE]; - int[] goldI8 = new int[RANGE]; - float[] goldF8 = new float[RANGE]; + int[] goldI7a = new int[RANGE]; + float[] goldF7a = new float[RANGE]; + int[] goldI7b = new int[RANGE]; + float[] goldF7b = new float[RANGE]; + float[] goldF7b_2 = new float[RANGE]; + int[] goldI7c = new int[RANGE]; + float[] goldF7c = new float[RANGE]; + int[] goldI8a = new int[RANGE]; + float[] goldF8a = new float[RANGE]; + int[] goldI8b = new int[RANGE]; + int[] goldI8b_2 = new int[RANGE]; + float[] goldF8b = new float[RANGE]; + int[] goldI8c = new int[RANGE]; + float[] goldF8c = new float[RANGE]; int[] goldI9 = new int[RANGE]; float[] goldF9 = new float[RANGE]; public static void main(String args[]) { - TestFramework.runWithFlags("-XX:CompileCommand=compileonly,TestCyclicDependency::test*"); + TestFramework.runWithFlags("-XX:CompileCommand=compileonly,TestCyclicDependency::test*", + "-XX:+IgnoreUnrecognizedVMOptions", "-XX:-AlignVector", "-XX:-VerifyAlignVector"); + TestFramework.runWithFlags("-XX:CompileCommand=compileonly,TestCyclicDependency::test*", + "-XX:+IgnoreUnrecognizedVMOptions", "-XX:+AlignVector", "-XX:-VerifyAlignVector"); + TestFramework.runWithFlags("-XX:CompileCommand=compileonly,TestCyclicDependency::test*", + "-XX:+IgnoreUnrecognizedVMOptions", "-XX:+AlignVector", "-XX:+VerifyAlignVector"); } TestCyclicDependency() { @@ -95,12 +110,24 @@ public static void main(String args[]) { // test6b init(goldI6b, goldF6b); test6b(goldI6b, goldF6b); - // test7 - init(goldI7, goldF7); - test7(goldI7, goldF7); - // test8 - init(goldI8, goldF8); - test8(goldI8, goldF8); + // test7a + init(goldI7a, goldF7a); + test7a(goldI7a, goldF7a); + // test7b + init(goldI7b, goldF7b, goldF7b_2); + test7b(goldI7b, goldF7b, goldF7b_2); + // test7c + init(goldI7c, goldF7c); + test7c(goldI7c, goldF7c, goldF7c); + // test8a + init(goldI8a, goldF8a); + test8a(goldI8a, goldF8a); + // test8b + init(goldI8b, goldI8b_2, goldF8b); + test8b(goldI8b, goldI8b_2, goldF8b); + // test8c + init(goldI8c, goldF8c); + test8c(goldI8c, goldI8c, goldF8c); // test9 init(goldI9, goldF9); test9(goldI9, goldF9); @@ -205,26 +232,74 @@ public void runTest6b() { verifyF("test6b", dataF, goldF6b); } - @Run(test = "test7") + @Run(test = "test7a") @Warmup(100) - public void runTest7() { + public void runTest7a() { int[] dataI = new int[RANGE]; float[] dataF = new float[RANGE]; init(dataI, dataF); - test7(dataI, dataF); - verifyI("test7", dataI, goldI7); - verifyF("test7", dataF, goldF7); + test7a(dataI, dataF); + verifyI("test7a", dataI, goldI7a); + verifyF("test7a", dataF, goldF7a); } - @Run(test = "test8") + @Run(test = "test7b") @Warmup(100) - public void runTest8() { + public void runTest7b() { + int[] dataI = new int[RANGE]; + float[] dataF = new float[RANGE]; + float[] dataF_2 = new float[RANGE]; + init(dataI, dataF, dataF_2); + test7b(dataI, dataF, dataF_2); + verifyI("test7b", dataI, goldI7b); + verifyF("test7b", dataF, goldF7b); + verifyF("test7b", dataF_2, goldF7b_2); + } + + @Run(test = "test7c") + @Warmup(100) + public void runTest7c() { + int[] dataI = new int[RANGE]; + float[] dataF = new float[RANGE]; + init(dataI, dataF); + test7c(dataI, dataF, dataF); + verifyI("test7c", dataI, goldI7c); + verifyF("test7c", dataF, goldF7c); + } + + @Run(test = "test8a") + @Warmup(100) + public void runTest8a() { + int[] dataI = new int[RANGE]; + float[] dataF = new float[RANGE]; + init(dataI, dataF); + test8a(dataI, dataF); + verifyI("test8a", dataI, goldI8a); + verifyF("test8a", dataF, goldF8a); + } + + @Run(test = "test8b") + @Warmup(100) + public void runTest8b() { + int[] dataI = new int[RANGE]; + int[] dataI_2 = new int[RANGE]; + float[] dataF = new float[RANGE]; + init(dataI, dataI_2, dataF); + test8b(dataI, dataI_2, dataF); + verifyI("test8b", dataI, goldI8b); + verifyI("test8b", dataI_2, goldI8b_2); + verifyF("test8b", dataF, goldF8b); + } + + @Run(test = "test8c") + @Warmup(100) + public void runTest8c() { int[] dataI = new int[RANGE]; float[] dataF = new float[RANGE]; init(dataI, dataF); - test8(dataI, dataF); - verifyI("test8", dataI, goldI8); - verifyF("test8", dataF, goldF8); + test8c(dataI, dataI, dataF); + verifyI("test8c", dataI, goldI8c); + verifyF("test8c", dataF, goldF8c); } @Run(test = "test9") @@ -328,34 +403,156 @@ static void test6b(int[] dataI, float[] dataF) { } @Test - @IR(counts = {IRNode.ADD_VI, "> 0"}, + @IR(counts = {IRNode.ADD_VI, "= 0", + IRNode.ADD_VF, "= 0"}, applyIf = {"AlignVector", "false"}, applyIfCPUFeatureOr = {"sse4.1", "true", "asimd", "true"}) + @IR(counts = {IRNode.ADD_VI, "> 0", + IRNode.ADD_VF, "= 0"}, + applyIf = {"AlignVector", "true"}, + applyIfCPUFeatureOr = {"sse4.1", "true", "asimd", "true"}) // Some aarch64 machines have AlignVector == true, like ThunderX2 - static void test7(int[] dataI, float[] dataF) { + static void test7a(int[] dataI, float[] dataF) { for (int i = 0; i < RANGE - 32; i++) { // write forward 32 -> more than vector size -> can vectorize - // write forward 3 -> cannot vectorize - // separate types should make decision separately if they vectorize or not int v = dataI[i]; dataI[i + 32] = v + 5; + // write forward 3: + // AlignVector=true -> cannot vectorize because load and store cannot be both aligned + // AlignVector=false -> could vectorize, but would get 2-element vectors where + // store-to-load-forwarding fails, because we have store-load + // dependencies that have partial overlap. + // -> all vectorization cancled. float f = dataF[i]; dataF[i + 3] = f + 3.5f; } } @Test - @IR(counts = {IRNode.ADD_VF, IRNode.VECTOR_SIZE + "min(max_int, max_float)", "> 0"}, + @IR(counts = {IRNode.ADD_VI, "> 0", + IRNode.ADD_VF, IRNode.VECTOR_SIZE + "2", "> 0"}, + applyIf = {"AlignVector", "false"}, + applyIfCPUFeatureOr = {"sse4.1", "true", "asimd", "true"}) + @IR(counts = {IRNode.ADD_VI, "> 0", + IRNode.ADD_VF, "= 0"}, + applyIf = {"AlignVector", "true"}, + applyIfCPUFeatureOr = {"sse4.1", "true", "asimd", "true"}) + // Some aarch64 machines have AlignVector == true, like ThunderX2 + static void test7b(int[] dataI, float[] dataF, float[] dataF_2) { + for (int i = 0; i < RANGE - 32; i++) { + // write forward 32 -> more than vector size -> can vectorize + int v = dataI[i]; + dataI[i + 32] = v + 5; + // write forward 3 to different array reference: + // AlignVector=true -> cannot vectorize because load and store cannot be both aligned + // AlignVector=false -> vectorizes because we cannot prove store-to-load forwarding + // failure. But we can only have 2-element vectors in case + // the two float-arrays reference the same array. + // Note: at runtime the float-arrays are always different. + float f = dataF[i]; + dataF_2[i + 3] = f + 3.5f; + } + } + + @Test + @IR(counts = {IRNode.ADD_VI, "> 0", + IRNode.ADD_VF, IRNode.VECTOR_SIZE + "2", "> 0"}, applyIf = {"AlignVector", "false"}, applyIfCPUFeatureOr = {"sse4.1", "true", "asimd", "true"}) + @IR(counts = {IRNode.ADD_VI, "> 0", + IRNode.ADD_VF, "= 0"}, + applyIf = {"AlignVector", "true"}, + applyIfCPUFeatureOr = {"sse4.1", "true", "asimd", "true"}) // Some aarch64 machines have AlignVector == true, like ThunderX2 - static void test8(int[] dataI, float[] dataF) { + static void test7c(int[] dataI, float[] dataF, float[] dataF_2) { for (int i = 0; i < RANGE - 32; i++) { // write forward 32 -> more than vector size -> can vectorize - // write forward 3 -> cannot vectorize - // separate types should make decision separately if they vectorize or not + int v = dataI[i]; + dataI[i + 32] = v + 5; + // write forward 3 to different array reference: + // AlignVector=true -> cannot vectorize because load and store cannot be both aligned + // AlignVector=false -> vectorizes because we cannot prove store-to-load forwarding + // failure. But we can only have 2-element vectors in case + // the two float-arrays reference the same array. + // Note: at runtime the float-arrays are always the same. + float f = dataF[i]; + dataF_2[i + 3] = f + 3.5f; + } + } + + @Test + @IR(counts = {IRNode.ADD_VI, "= 0", + IRNode.ADD_VF, "= 0"}, + applyIf = {"AlignVector", "false"}, + applyIfCPUFeatureOr = {"sse4.1", "true", "asimd", "true"}) + @IR(counts = {IRNode.ADD_VI, "= 0", + IRNode.ADD_VF, IRNode.VECTOR_SIZE + "min(max_int, max_float)", "> 0"}, + applyIf = {"AlignVector", "true"}, + applyIfCPUFeatureOr = {"sse4.1", "true", "asimd", "true"}) + // Some aarch64 machines have AlignVector == true, like ThunderX2 + static void test8a(int[] dataI, float[] dataF) { + for (int i = 0; i < RANGE - 32; i++) { + // write forward 3: + // AlignVector=true -> cannot vectorize because load and store cannot be both aligned + // AlignVector=false -> could vectorize, but would get 2-element vectors where + // store-to-load-forwarding fails, because we have store-load + // dependencies that have partial overlap. + // -> all vectorization cancled. int v = dataI[i]; dataI[i + 3] = v + 5; + // write forward 32 -> more than vector size -> can vectorize + float f = dataF[i]; + dataF[i + 32] = f + 3.5f; + } + } + + @Test + @IR(counts = {IRNode.ADD_VI, IRNode.VECTOR_SIZE + "2", "> 0", + IRNode.ADD_VF, IRNode.VECTOR_SIZE + "min(max_int, max_float)", "> 0"}, + applyIf = {"AlignVector", "false"}, + applyIfCPUFeatureOr = {"sse4.1", "true", "asimd", "true"}) + @IR(counts = {IRNode.ADD_VI, "= 0", + IRNode.ADD_VF, IRNode.VECTOR_SIZE + "min(max_int, max_float)", "> 0"}, + applyIf = {"AlignVector", "true"}, + applyIfCPUFeatureOr = {"sse4.1", "true", "asimd", "true"}) + // Some aarch64 machines have AlignVector == true, like ThunderX2 + static void test8b(int[] dataI, int[] dataI_2, float[] dataF) { + for (int i = 0; i < RANGE - 32; i++) { + // write forward 3 to different array reference: + // AlignVector=true -> cannot vectorize because load and store cannot be both aligned + // AlignVector=false -> vectorizes because we cannot prove store-to-load forwarding + // failure. But we can only have 2-element vectors in case + // the two float-arrays reference the same array. + // Note: at runtime the float-arrays are always different. + int v = dataI[i]; + dataI_2[i + 3] = v + 5; + // write forward 32 -> more than vector size -> can vectorize + float f = dataF[i]; + dataF[i + 32] = f + 3.5f; + } + } + + @Test + @IR(counts = {IRNode.ADD_VI, IRNode.VECTOR_SIZE + "2", "> 0", + IRNode.ADD_VF, IRNode.VECTOR_SIZE + "min(max_int, max_float)", "> 0"}, + applyIf = {"AlignVector", "false"}, + applyIfCPUFeatureOr = {"sse4.1", "true", "asimd", "true"}) + @IR(counts = {IRNode.ADD_VI, "= 0", + IRNode.ADD_VF, IRNode.VECTOR_SIZE + "min(max_int, max_float)", "> 0"}, + applyIf = {"AlignVector", "true"}, + applyIfCPUFeatureOr = {"sse4.1", "true", "asimd", "true"}) + // Some aarch64 machines have AlignVector == true, like ThunderX2 + static void test8c(int[] dataI, int[] dataI_2, float[] dataF) { + for (int i = 0; i < RANGE - 32; i++) { + // write forward 3 to different array reference: + // AlignVector=true -> cannot vectorize because load and store cannot be both aligned + // AlignVector=false -> vectorizes because we cannot prove store-to-load forwarding + // failure. But we can only have 2-element vectors in case + // the two float-arrays reference the same array. + // Note: at runtime the float-arrays are always the same. + int v = dataI[i]; + dataI_2[i + 3] = v + 5; + // write forward 32 -> more than vector size -> can vectorize float f = dataF[i]; dataF[i + 32] = f + 3.5f; } @@ -380,6 +577,22 @@ public static void init(int[] dataI, float[] dataF) { } } + public static void init(int[] dataI, float[] dataF, float[] dataF_2) { + for (int j = 0; j < RANGE; j++) { + dataI[j] = j; + dataF[j] = j * 0.5f; + dataF_2[j] = j * 0.3f; + } + } + + public static void init(int[] dataI, int[] dataI_2, float[] dataF) { + for (int j = 0; j < RANGE; j++) { + dataI[j] = j; + dataI_2[j] = 3*j - 42; + dataF[j] = j * 0.5f; + } + } + static void verifyI(String name, int[] data, int[] gold) { for (int i = 0; i < RANGE; i++) { if (data[i] != gold[i]) { diff --git a/test/hotspot/jtreg/compiler/loopopts/superword/TestDependencyOffsets.java b/test/hotspot/jtreg/compiler/loopopts/superword/TestDependencyOffsets.java index 8e5ac88a27da4..cfa19ce385a80 100644 --- a/test/hotspot/jtreg/compiler/loopopts/superword/TestDependencyOffsets.java +++ b/test/hotspot/jtreg/compiler/loopopts/superword/TestDependencyOffsets.java @@ -643,6 +643,12 @@ static List getOffsets() { return new ArrayList(set); } + enum ExpectVectorization { + ALWAYS, // -> positive "count" IR rule + UNKNOWN, // -> disable IR rule + NEVER // -> negative "failOn" IR rule + }; + static record TestDefinition (int id, Type type, int offset) { /* @@ -656,18 +662,22 @@ String generate() { String aliasingComment; String secondArgument; String loadFrom; + boolean isSingleArray; switch (RANDOM.nextInt(3)) { case 0: // a[i + offset] = a[i] + isSingleArray = true; aliasingComment = "single-array"; secondArgument = "a"; loadFrom = "a"; break; case 1: // a[i + offset] = b[i], but a and b alias, i.e. at runtime a == b. + isSingleArray = false; aliasingComment = "aliasing"; secondArgument = "a"; loadFrom = "b"; break; case 2: // a[i + offset] = b[i], and a and b do not alias, i.e. at runtime a != b. + isSingleArray = false; aliasingComment = "non-aliasing"; secondArgument = "b"; loadFrom = "b"; @@ -712,7 +722,7 @@ String generate() { type.name, id, type.name, id, id, id, id, secondArgument, id, // IR rules - generateIRRules(), + generateIRRules(isSingleArray), // test id, type.name, type.name, start, end, @@ -726,7 +736,7 @@ String generate() { * expect depends on AlignVector and MaxVectorSize, as well as the byteOffset between the load and * store. */ - String generateIRRules() { + String generateIRRules(boolean isSingleArray) { StringBuilder builder = new StringBuilder(); for (CPUMinVectorWidth cm : getCPUMinVectorWidth(type.name)) { @@ -744,29 +754,75 @@ String generateIRRules() { // power of two. int infinity = 256; // No vector size is ever larger than this. int maxVectorWidth = infinity; // no constraint by default + int log2 = 31 - Integer.numberOfLeadingZeros(offset); + int floorPow2Offset = 1 << log2; if (0 < byteOffset && byteOffset < maxVectorWidth) { - int log2 = 31 - Integer.numberOfLeadingZeros(offset); - int floorPow2 = 1 << log2; - maxVectorWidth = Math.min(maxVectorWidth, floorPow2 * type.size); - builder.append(" // Vectors must have at most " + floorPow2 + + maxVectorWidth = Math.min(maxVectorWidth, floorPow2Offset * type.size); + builder.append(" // Vectors must have at most " + floorPow2Offset + " elements: maxVectorWidth = " + maxVectorWidth + " to avoid cyclic dependency.\n"); } + ExpectVectorization expectVectorization = ExpectVectorization.ALWAYS; + if (isSingleArray && 0 < offset && offset < 64) { + // In a store-forward case at iteration distances below a certain threshold, and not there + // is some partial overlap between the expected vector store and some vector load in a later + // iteration, we avoid vectorization to avoid the latency penalties of store-to-load + // forwarding failure. We only detect these failures in single-array cases. + // + // Note: we currently never detect store-to-load-forwarding failures beyond 64 iterations, + // And so if the offset >= 64, we always expect vectorization. + // + // The condition for partial overlap: + // offset % #elements != 0 + // + // But we do not know #elements exactly, only a range from min/maxVectorWidth. + + int maxElements = maxVectorWidth / type.size; + int minElements = minVectorWidth / type.size; + boolean sometimesPartialOverlap = offset % maxElements != 0; + // If offset % minElements != 0, then it does also not hold for any larger vector. + boolean alwaysPartialOverlap = offset % minElements != 0; + + if (alwaysPartialOverlap) { + // It is a little tricky to know the exact threshold. On all platforms and in all + // unrolling cases, it is between 8 and 64. Hence, we have these 3 cases: + if (offset <= 8) { + builder.append(" // We always detect store-to-load-forwarding failures -> never vectorize.\n"); + expectVectorization = ExpectVectorization.NEVER; + } else if (offset <= 64) { + builder.append(" // Unknown if detect store-to-load-forwarding failures -> maybe disable IR rules.\n"); + expectVectorization = ExpectVectorization.UNKNOWN; + } else { + // offset > 64 -> offset too large, expect no store-to-load-failure detection + throw new RuntimeException("impossible"); + } + } else if (sometimesPartialOverlap && !alwaysPartialOverlap) { + builder.append(" // Partial overlap condition true: sometimes but not always -> maybe disable IR rules.\n"); + expectVectorization = ExpectVectorization.UNKNOWN; + } else { + builder.append(" // Partial overlap never happens -> expect vectorization.\n"); + expectVectorization = ExpectVectorization.ALWAYS; + } + } + // Rule 1: No strict alignment: -XX:-AlignVector + ExpectVectorization expectVectorization1 = expectVectorization; IRRule r1 = new IRRule(type, type.irNode, applyIfCPUFeature); r1.addApplyIf("\"AlignVector\", \"false\""); r1.addApplyIf("\"MaxVectorSize\", \">=" + minVectorWidth + "\""); if (maxVectorWidth < minVectorWidth) { builder.append(" // maxVectorWidth < minVectorWidth -> expect no vectorization.\n"); - r1.setNegative(); + expectVectorization1 = ExpectVectorization.NEVER; } else if (maxVectorWidth < infinity) { r1.setSize("min(" + (maxVectorWidth / type.size) + ",max_" + type.name + ")"); } + r1.setExpectVectVectorization(expectVectorization1); r1.generate(builder); // Rule 2: strict alignment: -XX:+AlignVector + ExpectVectorization expectVectorization2 = expectVectorization; IRRule r2 = new IRRule(type, type.irNode, applyIfCPUFeature); r2.addApplyIf("\"AlignVector\", \"true\""); r2.addApplyIf("\"MaxVectorSize\", \">=" + minVectorWidth + "\""); @@ -791,18 +847,23 @@ String generateIRRules() { builder.append(" // byteOffset % awMax == 0 -> always trivially aligned\n"); } else if (byteOffset % awMin != 0) { builder.append(" // byteOffset % awMin != 0 -> can never align -> expect no vectorization.\n"); - r2.setNegative(); + expectVectorization2 = ExpectVectorization.NEVER; } else { - builder.append(" // Alignment unknown -> disable IR rule.\n"); - r2.disable(); + if (expectVectorization2 != ExpectVectorization.NEVER) { + builder.append(" // Alignment unknown -> disable IR rule.\n"); + expectVectorization2 = ExpectVectorization.UNKNOWN; + } else { + builder.append(" // Alignment unknown -> but already proved no vectorization above.\n"); + } } if (maxVectorWidth < minVectorWidth) { builder.append(" // Not at least 2 elements or 4 bytes -> expect no vectorization.\n"); - r2.setNegative(); + expectVectorization2 = ExpectVectorization.NEVER; } else if (maxVectorWidth < infinity) { r2.setSize("min(" + (maxVectorWidth / type.size) + ",max_" + type.name + ")"); } + r2.setExpectVectVectorization(expectVectorization2); r2.generate(builder); } return builder.toString(); @@ -846,12 +907,12 @@ void setSize(String size) { this.size = size; } - void setNegative() { - this.isPositiveRule = false; - } - - void disable() { - this.isEnabled = false; + void setExpectVectVectorization(ExpectVectorization expectVectorization) { + switch(expectVectorization) { + case ExpectVectorization.NEVER -> { this.isPositiveRule = false; } + case ExpectVectorization.UNKNOWN -> { this.isEnabled = false; } + case ExpectVectorization.ALWAYS -> {} + } } void addApplyIf(String constraint) { diff --git a/test/hotspot/jtreg/compiler/vectorization/runner/LoopCombinedOpTest.java b/test/hotspot/jtreg/compiler/vectorization/runner/LoopCombinedOpTest.java index 16d04102082b3..8a0715eadfe88 100644 --- a/test/hotspot/jtreg/compiler/vectorization/runner/LoopCombinedOpTest.java +++ b/test/hotspot/jtreg/compiler/vectorization/runner/LoopCombinedOpTest.java @@ -138,8 +138,11 @@ public int[] multipleOpsWithMultipleConstants() { } @Test - @IR(applyIfCPUFeatureOr = {"asimd", "true", "sse2", "true"}, + @IR(applyIfCPUFeatureOr = {"asimd", "true", "sse4.1", "true"}, counts = {IRNode.STORE_VECTOR, ">0"}) + // With sse2, the MulI does not vectorize. This means we have vectorized stores + // to res1, but scalar loads from res1. The store-to-load-forwarding failure + // detection catches this and rejects vectorization. public int[] multipleStores() { int[] res1 = new int[SIZE]; int[] res2 = new int[SIZE]; diff --git a/test/micro/org/openjdk/bench/vm/compiler/VectorStoreToLoadForwarding.java b/test/micro/org/openjdk/bench/vm/compiler/VectorStoreToLoadForwarding.java new file mode 100644 index 0000000000000..ac8940ec67510 --- /dev/null +++ b/test/micro/org/openjdk/bench/vm/compiler/VectorStoreToLoadForwarding.java @@ -0,0 +1,142 @@ +/* + * Copyright (c) 2024, 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. + * + * 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 org.openjdk.bench.vm.compiler; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.infra.*; + +import java.lang.invoke.*; + +import java.util.concurrent.TimeUnit; +import java.util.Random; + +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.NANOSECONDS) +@State(Scope.Thread) +@Warmup(iterations = 2, time = 1, timeUnit = TimeUnit.SECONDS) +@Measurement(iterations = 3, time = 1, timeUnit = TimeUnit.SECONDS) +@Fork(value = 1) +public abstract class VectorStoreToLoadForwarding { + @Param({"10000"}) + public int SIZE; + + @Param({ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", + "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", + "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", + "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", + "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", + "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", + "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", + "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", + "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", + "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", + "100", "101", "102", "103", "104", "105", "106", "107", "108", "109", + "110", "111", "112", "113", "114", "115", "116", "117", "118", "119", + "120", "121", "122", "123", "124", "125", "126", "127", "128", "129"}) + public int OFFSET; + + // To get compile-time constants for OFFSET + static final MutableCallSite MUTABLE_CONSTANT = new MutableCallSite(MethodType.methodType(int.class)); + static final MethodHandle MUTABLE_CONSTANT_HANDLE = MUTABLE_CONSTANT.dynamicInvoker(); + + public int START = 1000; + + private byte[] aB; + private short[] aS; + private int[] aI; + private long[] aL; + + @Param("0") + private int seed; + private Random r = new Random(seed); + + @Setup + public void init() throws Throwable { + aB = new byte[SIZE]; + aS = new short[SIZE]; + aI = new int[SIZE]; + aL = new long[SIZE]; + + for (int i = START; i < SIZE; i++) { + aB[i] = (byte)r.nextInt(); + aS[i] = (short)r.nextInt(); + aI[i] = r.nextInt(); + aL[i] = r.nextLong(); + } + + MethodHandle constant = MethodHandles.constant(int.class, OFFSET); + MUTABLE_CONSTANT.setTarget(constant); + } + + @CompilerControl(CompilerControl.Mode.INLINE) + private int offset_con() throws Throwable { + return (int) MUTABLE_CONSTANT_HANDLE.invokeExact(); + } + + @Benchmark + public void bytes() throws Throwable { + int offset = offset_con(); + for (int i = START; i < SIZE; i++) { + aB[i] = (byte)(aB[i - offset] + 1); + } + } + + @Benchmark + public void shorts() throws Throwable { + int offset = offset_con(); + for (int i = START; i < SIZE; i++) { + aS[i] = (short)(aS[i - offset] + 1); + } + } + + @Benchmark + public void ints() throws Throwable { + int offset = offset_con(); + for (int i = START; i < SIZE; i++) { + aI[i] = aI[i - offset] + 1; + } + } + + @Benchmark + public void longs() throws Throwable { + int offset = offset_con(); + for (int i = START; i < SIZE; i++) { + aL[i] = (long)(aL[i - offset] + 1); + } + } + + @Fork(value = 1, jvmArgs = { + "-XX:+UseSuperWord" + }) + public static class Default extends VectorStoreToLoadForwarding {} + + @Fork(value = 1, jvmArgs = { + "-XX:-UseSuperWord" + }) + public static class NoVectorization extends VectorStoreToLoadForwarding {} + + @Fork(value = 1, jvmArgs = { + "-XX:+UseSuperWord", "-XX:+UnlockDiagnosticVMOptions", "-XX:SuperWordStoreToLoadForwardingFailureDetection=0" + }) + public static class NoStoreToLoadForwardFailureDetection extends VectorStoreToLoadForwarding {} +} From 7d4c3fd0915cfa8b279f42494625ec6afda338af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Lund=C3=A9n?= Date: Wed, 20 Nov 2024 15:37:43 +0000 Subject: [PATCH 48/74] 8331295: C2: Do not clone address computations that are indirect memory input to at least one load/store MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Roberto Castañeda Lozano Reviewed-by: thartmann, chagedorn --- src/hotspot/cpu/aarch64/aarch64.ad | 17 ++ .../jtreg/compiler/c2/TestFindNode.java | 4 +- .../compiler/codegen/TestMatcherClone.java | 232 ++++++++++++++++++ .../TestDeepGraphVerifyIterativeGVN.java | 1 - 4 files changed, 251 insertions(+), 3 deletions(-) create mode 100644 test/hotspot/jtreg/compiler/codegen/TestMatcherClone.java diff --git a/src/hotspot/cpu/aarch64/aarch64.ad b/src/hotspot/cpu/aarch64/aarch64.ad index 1015b63164329..017dc0ed85fb1 100644 --- a/src/hotspot/cpu/aarch64/aarch64.ad +++ b/src/hotspot/cpu/aarch64/aarch64.ad @@ -2632,6 +2632,23 @@ bool Matcher::pd_clone_node(Node* n, Node* m, Matcher::MStack& mstack) { // to be subsumed into complex addressing expressions or compute them // into registers? bool Matcher::pd_clone_address_expressions(AddPNode* m, Matcher::MStack& mstack, VectorSet& address_visited) { + + // Loads and stores with indirect memory input (e.g., volatile loads and + // stores) do not subsume the input into complex addressing expressions. If + // the addressing expression is input to at least one such load or store, do + // not clone the addressing expression. Query needs_acquiring_load and + // needs_releasing_store as a proxy for indirect memory input, as it is not + // possible to directly query for indirect memory input at this stage. + for (DUIterator_Fast imax, i = m->fast_outs(imax); i < imax; i++) { + Node* n = m->fast_out(i); + if (n->is_Load() && needs_acquiring_load(n)) { + return false; + } + if (n->is_Store() && needs_releasing_store(n)) { + return false; + } + } + if (clone_base_plus_offset_address(m, mstack, address_visited)) { return true; } diff --git a/test/hotspot/jtreg/compiler/c2/TestFindNode.java b/test/hotspot/jtreg/compiler/c2/TestFindNode.java index ea7649c713ac7..fa545da7e5895 100644 --- a/test/hotspot/jtreg/compiler/c2/TestFindNode.java +++ b/test/hotspot/jtreg/compiler/c2/TestFindNode.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2024, 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 @@ -27,7 +27,7 @@ * @requires vm.debug == true & vm.flavor == "server" * @summary Test which uses some special flags in order to test Node::find() in debug builds which could result in an endless loop or a stack overflow crash. * - * @run main/othervm -Xbatch -XX:CompileCommand=option,*::*,bool,Vectorize,true -XX:CompileCommand=memlimit,compiler.c2.TestFindNode::*,0 + * @run main/othervm -Xbatch -XX:CompileCommand=option,*::*,bool,Vectorize,true * -XX:+PrintOpto -XX:+TraceLoopOpts compiler.c2.TestFindNode */ package compiler.c2; diff --git a/test/hotspot/jtreg/compiler/codegen/TestMatcherClone.java b/test/hotspot/jtreg/compiler/codegen/TestMatcherClone.java new file mode 100644 index 0000000000000..e062cc2053814 --- /dev/null +++ b/test/hotspot/jtreg/compiler/codegen/TestMatcherClone.java @@ -0,0 +1,232 @@ +/* + * Copyright (c) 2024, 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. + * + * 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. + */ + +/* + * @test + * @bug 8331295 + * @requires os.simpleArch == "aarch64" + * @summary Check that the matcher does not needlessly clone an addressing + * expression that will in any case not be subsumed into complex + * loads and stores. + * @library /test/lib / + * @run driver compiler.codegen.TestMatcherClone + */ + +package compiler.codegen; + +import compiler.lib.ir_framework.*; + +public class TestMatcherClone { + static volatile int[] iArr; + static volatile int x; + static int[] iArr2 = new int[100]; + static int[] iArr3 = new int[100]; + + public static void main(String[] args) { + TestFramework.run(); + } + + @Test(compLevel = CompLevel.C2) + @IR(counts = {IRNode.ADD_P_OF, "reg_imm", "<200"}, + phase = CompilePhase.MATCHING) + public void test() { + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + iArr = new int[] {x % 2}; + + for (int i = 0; i < 50; i++) { + iArr2[i] = iArr3[i]; + } + } +} diff --git a/test/hotspot/jtreg/compiler/loopopts/TestDeepGraphVerifyIterativeGVN.java b/test/hotspot/jtreg/compiler/loopopts/TestDeepGraphVerifyIterativeGVN.java index bcb4a21136814..d5ddc0487024f 100644 --- a/test/hotspot/jtreg/compiler/loopopts/TestDeepGraphVerifyIterativeGVN.java +++ b/test/hotspot/jtreg/compiler/loopopts/TestDeepGraphVerifyIterativeGVN.java @@ -28,7 +28,6 @@ * @summary Test which causes a stack overflow segmentation fault with -XX:VerifyIterativeGVN=1 due to a too deep recursion in Node::verify_recur(). * * @run main/othervm/timeout=600 -Xcomp -XX:VerifyIterativeGVN=1 -XX:CompileCommand=compileonly,compiler.loopopts.TestDeepGraphVerifyIterativeGVN::* - * -XX:CompileCommand=memlimit,compiler.loopopts.TestDeepGraphVerifyIterativeGVN::*,0 * compiler.loopopts.TestDeepGraphVerifyIterativeGVN */ From 9be8ac6fbcf1a91e5eee9d3a3430dc356b89283e Mon Sep 17 00:00:00 2001 From: Calvin Cheung Date: Wed, 20 Nov 2024 15:41:26 +0000 Subject: [PATCH 49/74] 8344239: runtime/cds/appcds/jigsaw/addmods/AddmodsOption.java fails on x64 with -Xmixed Reviewed-by: iklam --- .../jtreg/runtime/cds/appcds/jigsaw/addmods/AddmodsOption.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/hotspot/jtreg/runtime/cds/appcds/jigsaw/addmods/AddmodsOption.java b/test/hotspot/jtreg/runtime/cds/appcds/jigsaw/addmods/AddmodsOption.java index 114dd6b9f3ac6..9328cc865691d 100644 --- a/test/hotspot/jtreg/runtime/cds/appcds/jigsaw/addmods/AddmodsOption.java +++ b/test/hotspot/jtreg/runtime/cds/appcds/jigsaw/addmods/AddmodsOption.java @@ -39,7 +39,7 @@ public class AddmodsOption { private static final WhiteBox WB = WhiteBox.getWhiteBox(); - private static final boolean isJVMCISupported = (WB.getBooleanVMFlag("EnableJVMCI") != null); + private static final boolean isJVMCISupported = WB.getBooleanVMFlag("EnableJVMCI"); public static void main(String[] args) throws Exception { final String moduleOption = "jdk.httpserver/sun.net.httpserver.simpleserver.Main"; From c4c6b1fe0629d313e7b7bd6b7dc92f8c7d18ec8f Mon Sep 17 00:00:00 2001 From: Brian Burkhalter Date: Wed, 20 Nov 2024 16:01:01 +0000 Subject: [PATCH 50/74] 8344562: Remove security manager dependency from module jdk.jdi Reviewed-by: kevinw, lmesnik, cjplummer --- .../com/sun/tools/jdi/VirtualMachineManagerImpl.java | 7 ------- 1 file changed, 7 deletions(-) diff --git a/src/jdk.jdi/share/classes/com/sun/tools/jdi/VirtualMachineManagerImpl.java b/src/jdk.jdi/share/classes/com/sun/tools/jdi/VirtualMachineManagerImpl.java index c17c46237b6cb..d49e718db60d4 100644 --- a/src/jdk.jdi/share/classes/com/sun/tools/jdi/VirtualMachineManagerImpl.java +++ b/src/jdk.jdi/share/classes/com/sun/tools/jdi/VirtualMachineManagerImpl.java @@ -59,13 +59,6 @@ public class VirtualMachineManagerImpl implements VirtualMachineManagerService { private static VirtualMachineManagerImpl vmm; public static VirtualMachineManager virtualMachineManager() { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - JDIPermission vmmPermission = - new JDIPermission("virtualMachineManager"); - sm.checkPermission(vmmPermission); - } synchronized (lock) { if (vmm == null) { vmm = new VirtualMachineManagerImpl(); From 080f1cc8cd0500c254debec3198dc187bd41c3e8 Mon Sep 17 00:00:00 2001 From: Alexey Semenyuk Date: Wed, 20 Nov 2024 16:54:51 +0000 Subject: [PATCH 51/74] 8289771: jpackage: ResourceEditor error when path is overly long on Windows Reviewed-by: almatvee --- .../internal/ExecutableRebrander.java | 20 ++- .../jdk/jpackage/internal/ShortPathUtils.java | 93 ++++++++++ .../jdk/jpackage/internal/WinMsiBundler.java | 18 +- .../jpackage/internal/WixFragmentBuilder.java | 2 +- .../jdk/jpackage/internal/WixPipeline.java | 159 ++++++++++++------ .../internal/WixUiFragmentBuilder.java | 4 +- .../resources/WinResources.properties | 1 + .../resources/WinResources_de.properties | 1 + .../resources/WinResources_ja.properties | 1 + .../resources/WinResources_zh_CN.properties | 1 + .../windows/native/common/WinFileUtils.cpp | 21 ++- .../windows/native/common/WinFileUtils.h | 4 +- .../windows/native/libjpackage/jpackage.cpp | 23 +++ .../helpers/jdk/jpackage/test/Executor.java | 10 +- .../helpers/jdk/jpackage/test/HelloApp.java | 21 ++- .../jdk/jpackage/test/WindowsHelper.java | 85 +++++++++- .../tools/jpackage/windows/WinL10nTest.java | 46 ++--- .../jpackage/windows/WinLongPathTest.java | 87 ++++++++++ 18 files changed, 500 insertions(+), 97 deletions(-) create mode 100644 src/jdk.jpackage/windows/classes/jdk/jpackage/internal/ShortPathUtils.java create mode 100644 test/jdk/tools/jpackage/windows/WinLongPathTest.java diff --git a/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/ExecutableRebrander.java b/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/ExecutableRebrander.java index a297f507da84a..166675b5893d0 100644 --- a/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/ExecutableRebrander.java +++ b/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/ExecutableRebrander.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2024, 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 @@ -30,6 +30,7 @@ import java.io.InputStreamReader; import java.io.Reader; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.nio.file.Path; import java.text.MessageFormat; import java.util.ArrayList; @@ -40,6 +41,7 @@ import java.util.ResourceBundle; import java.util.function.Supplier; import static jdk.jpackage.internal.OverridableResource.createResource; +import static jdk.jpackage.internal.ShortPathUtils.adjustPath; import static jdk.jpackage.internal.StandardBundlerParam.APP_NAME; import static jdk.jpackage.internal.StandardBundlerParam.COPYRIGHT; import static jdk.jpackage.internal.StandardBundlerParam.DESCRIPTION; @@ -112,7 +114,7 @@ ExecutableRebrander addAction(UpdateResourceAction action) { } private void rebrandExecutable(Map params, - Path target, UpdateResourceAction action) throws IOException { + final Path target, UpdateResourceAction action) throws IOException { try { String tempDirectory = TEMP_ROOT.fetchFrom(params) .toAbsolutePath().toString(); @@ -125,10 +127,11 @@ private void rebrandExecutable(Map params, target.toFile().setWritable(true, true); - long resourceLock = lockResource(target.toString()); + var shortTargetPath = ShortPathUtils.toShortPath(target); + long resourceLock = lockResource(shortTargetPath.orElse(target).toString()); if (resourceLock == 0) { throw new RuntimeException(MessageFormat.format( - I18N.getString("error.lock-resource"), target)); + I18N.getString("error.lock-resource"), shortTargetPath.orElse(target))); } final boolean resourceUnlockedSuccess; @@ -144,6 +147,14 @@ private void rebrandExecutable(Map params, resourceUnlockedSuccess = true; } else { resourceUnlockedSuccess = unlockResource(resourceLock); + if (shortTargetPath.isPresent()) { + // Windows will rename the excuatble in the unlock operation. + // Should restore executable's name. + var tmpPath = target.getParent().resolve( + target.getFileName().toString() + ".restore"); + Files.move(shortTargetPath.get(), tmpPath); + Files.move(tmpPath, target); + } } } @@ -236,6 +247,7 @@ private static void validateValueAndPut( private static void iconSwapWrapper(long resourceLock, String iconTarget) { + iconTarget = adjustPath(iconTarget); if (iconSwap(resourceLock, iconTarget) != 0) { throw new RuntimeException(MessageFormat.format(I18N.getString( "error.icon-swap"), iconTarget)); diff --git a/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/ShortPathUtils.java b/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/ShortPathUtils.java new file mode 100644 index 0000000000000..21dc2a1c3fffc --- /dev/null +++ b/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/ShortPathUtils.java @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2024, 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 jdk.jpackage.internal; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.text.MessageFormat; +import java.util.Objects; +import java.util.Optional; + + +@SuppressWarnings("restricted") +final class ShortPathUtils { + static String adjustPath(String path) { + return toShortPath(path).orElse(path); + } + + static Path adjustPath(Path path) { + return toShortPath(path).orElse(path); + } + + static Optional toShortPath(String path) { + Objects.requireNonNull(path); + return toShortPath(Path.of(path)).map(Path::toString); + } + + static Optional toShortPath(Path path) { + if (!Files.exists(path)) { + throw new IllegalArgumentException(String.format("[%s] path does not exist", path)); + } + + var normPath = path.normalize().toAbsolutePath().toString(); + if (normPath.length() > MAX_PATH) { + return Optional.of(Path.of(getShortPathWrapper(normPath))); + } else { + return Optional.empty(); + } + } + + private static String getShortPathWrapper(final String longPath) { + String effectivePath; + if (!longPath.startsWith(LONG_PATH_PREFIX)) { + effectivePath = LONG_PATH_PREFIX + longPath; + } else { + effectivePath = longPath; + } + + return Optional.ofNullable(getShortPath(effectivePath)).orElseThrow( + () -> new ShortPathException(MessageFormat.format(I18N.getString( + "error.short-path-conv-fail"), effectivePath))); + } + + static final class ShortPathException extends RuntimeException { + + ShortPathException(String msg) { + super(msg); + } + + private static final long serialVersionUID = 1L; + } + + private static native String getShortPath(String longPath); + + private static final int MAX_PATH = 240; + // See https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getshortpathnamew + private static final String LONG_PATH_PREFIX = "\\\\?\\"; + + static { + System.loadLibrary("jpackage"); + } +} diff --git a/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WinMsiBundler.java b/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WinMsiBundler.java index f6b0fb4be2074..f724e08fc8901 100644 --- a/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WinMsiBundler.java +++ b/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WinMsiBundler.java @@ -526,9 +526,10 @@ private Path buildMSI(Map params, "message.preparing-msi-config"), msiOut.toAbsolutePath() .toString())); - WixPipeline wixPipeline = new WixPipeline() - .setToolset(wixToolset) - .setWixObjDir(TEMP_ROOT.fetchFrom(params).resolve("wixobj")) + var wixObjDir = TEMP_ROOT.fetchFrom(params).resolve("wixobj"); + + var wixPipeline = WixPipeline.build() + .setWixObjDir(wixObjDir) .setWorkDir(WIN_APP_IMAGE.fetchFrom(params)) .addSource(CONFIG_ROOT.fetchFrom(params).resolve("main.wxs"), wixVars); @@ -605,13 +606,13 @@ private Path buildMSI(Map params, // Cultures from custom files and a single primary Culture are // included into "-cultures" list for (var wxl : primaryWxlFiles) { - wixPipeline.addLightOptions("-loc", wxl.toAbsolutePath().normalize().toString()); + wixPipeline.addLightOptions("-loc", wxl.toString()); } List cultures = new ArrayList<>(); for (var wxl : customWxlFiles) { wxl = configDir.resolve(wxl.getFileName()); - wixPipeline.addLightOptions("-loc", wxl.toAbsolutePath().normalize().toString()); + wixPipeline.addLightOptions("-loc", wxl.toString()); cultures.add(getCultureFromWxlFile(wxl)); } @@ -638,7 +639,8 @@ private Path buildMSI(Map params, } } - wixPipeline.buildMsi(msiOut.toAbsolutePath()); + Files.createDirectories(wixObjDir); + wixPipeline.create(wixToolset).buildMsi(msiOut.toAbsolutePath()); return msiOut; } @@ -678,14 +680,14 @@ private static String getCultureFromWxlFile(Path wxlPath) throws IOException { if (nodes.getLength() != 1) { throw new IOException(MessageFormat.format(I18N.getString( "error.extract-culture-from-wix-l10n-file"), - wxlPath.toAbsolutePath())); + wxlPath.toAbsolutePath().normalize())); } return nodes.item(0).getNodeValue(); } catch (XPathExpressionException | ParserConfigurationException | SAXException ex) { throw new IOException(MessageFormat.format(I18N.getString( - "error.read-wix-l10n-file"), wxlPath.toAbsolutePath()), ex); + "error.read-wix-l10n-file"), wxlPath.toAbsolutePath().normalize()), ex); } } diff --git a/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WixFragmentBuilder.java b/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WixFragmentBuilder.java index f0a5840eb6fc3..48a1d04f8dc4d 100644 --- a/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WixFragmentBuilder.java +++ b/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WixFragmentBuilder.java @@ -74,7 +74,7 @@ List getLoggableWixFeatures() { return List.of(); } - void configureWixPipeline(WixPipeline wixPipeline) { + void configureWixPipeline(WixPipeline.Builder wixPipeline) { wixPipeline.addSource(configRoot.resolve(outputFileName), Optional.ofNullable(wixVariables).map(WixVariables::getValues).orElse( null)); diff --git a/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WixPipeline.java b/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WixPipeline.java index 5b626c8a565f5..d7c1b54a48cf3 100644 --- a/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WixPipeline.java +++ b/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WixPipeline.java @@ -29,65 +29,130 @@ import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.Set; import java.util.function.Function; +import java.util.function.UnaryOperator; import java.util.stream.Collectors; import java.util.stream.Stream; +import static jdk.jpackage.internal.ShortPathUtils.adjustPath; import jdk.jpackage.internal.util.PathUtils; /** * WiX pipeline. Compiles and links WiX sources. */ -public class WixPipeline { - WixPipeline() { - sources = new ArrayList<>(); - lightOptions = new ArrayList<>(); - } +final class WixPipeline { - WixPipeline setToolset(WixToolset v) { - toolset = v; - return this; - } + static final class Builder { + Builder() { + } - WixPipeline setWixVariables(Map v) { - wixVariables = v; - return this; - } + WixPipeline create(WixToolset toolset) { + Objects.requireNonNull(toolset); + Objects.requireNonNull(workDir); + Objects.requireNonNull(wixObjDir); + if (sources.isEmpty()) { + throw new IllegalArgumentException("no sources"); + } - WixPipeline setWixObjDir(Path v) { - wixObjDir = v; - return this; - } + final var absWorkDir = workDir.normalize().toAbsolutePath(); + + final UnaryOperator normalizePath = path -> { + return path.normalize().toAbsolutePath(); + }; + + final var absObjWorkDir = normalizePath.apply(wixObjDir); + + var relSources = sources.stream().map(source -> { + return source.overridePath(normalizePath.apply(source.path)); + }).toList(); + + return new WixPipeline(toolset, adjustPath(absWorkDir), absObjWorkDir, + wixVariables, mapLightOptions(normalizePath), relSources); + } + + Builder setWixObjDir(Path v) { + wixObjDir = v; + return this; + } + + Builder setWorkDir(Path v) { + workDir = v; + return this; + } + + Builder setWixVariables(Map v) { + wixVariables.clear(); + wixVariables.putAll(v); + return this; + } + + Builder addSource(Path source, Map wixVariables) { + sources.add(new WixSource(source, wixVariables)); + return this; + } + + Builder addLightOptions(String ... v) { + lightOptions.addAll(List.of(v)); + return this; + } - WixPipeline setWorkDir(Path v) { - workDir = v; - return this; + private List mapLightOptions(UnaryOperator normalizePath) { + var pathOptions = Set.of("-b", "-loc"); + List reply = new ArrayList<>(); + boolean convPath = false; + for (var opt : lightOptions) { + if (convPath) { + opt = normalizePath.apply(Path.of(opt)).toString(); + convPath = false; + } else if (pathOptions.contains(opt)) { + convPath = true; + } + reply.add(opt); + } + return reply; + } + + private Path workDir; + private Path wixObjDir; + private final Map wixVariables = new HashMap<>(); + private final List lightOptions = new ArrayList<>(); + private final List sources = new ArrayList<>(); } - WixPipeline addSource(Path source, Map wixVariables) { - WixSource entry = new WixSource(); - entry.source = source; - entry.variables = wixVariables; - sources.add(entry); - return this; + static Builder build() { + return new Builder(); } - WixPipeline addLightOptions(String ... v) { - lightOptions.addAll(List.of(v)); - return this; + private WixPipeline(WixToolset toolset, Path workDir, Path wixObjDir, + Map wixVariables, List lightOptions, + List sources) { + this.toolset = toolset; + this.workDir = workDir; + this.wixObjDir = wixObjDir; + this.wixVariables = wixVariables; + this.lightOptions = lightOptions; + this.sources = sources; } void buildMsi(Path msi) throws IOException { Objects.requireNonNull(workDir); + // Use short path to the output msi to workaround + // WiX limitations of handling long paths. + var transientMsi = wixObjDir.resolve("a.msi"); + switch (toolset.getType()) { - case Wix3 -> buildMsiWix3(msi); - case Wix4 -> buildMsiWix4(msi); + case Wix3 -> buildMsiWix3(transientMsi); + case Wix4 -> buildMsiWix4(transientMsi); default -> throw new IllegalArgumentException(); } + + IOUtils.copyFile(workDir.resolve(transientMsi), msi); } private void addWixVariblesToCommandLine( @@ -141,7 +206,7 @@ private void buildMsiWix4(Path msi) throws IOException { "build", "-nologo", "-pdbtype", "none", - "-intermediatefolder", wixObjDir.toAbsolutePath().toString(), + "-intermediatefolder", wixObjDir.toString(), "-ext", "WixToolset.Util.wixext", "-arch", WixFragmentBuilder.is64Bit() ? "x64" : "x86" )); @@ -151,7 +216,7 @@ private void buildMsiWix4(Path msi) throws IOException { addWixVariblesToCommandLine(mergedSrcWixVars, cmdline); cmdline.addAll(sources.stream().map(wixSource -> { - return wixSource.source.toAbsolutePath().toString(); + return wixSource.path.toString(); }).toList()); cmdline.addAll(List.of("-out", msi.toString())); @@ -182,15 +247,15 @@ private void buildMsiWix3(Path msi) throws IOException { private Path compileWix3(WixSource wixSource) throws IOException { Path wixObj = wixObjDir.toAbsolutePath().resolve(PathUtils.replaceSuffix( - IOUtils.getFileName(wixSource.source), ".wixobj")); + wixSource.path.getFileName(), ".wixobj")); List cmdline = new ArrayList<>(List.of( toolset.getToolPath(WixTool.Candle3).toString(), "-nologo", - wixSource.source.toAbsolutePath().toString(), + wixSource.path.toString(), "-ext", "WixUtilExtension", "-arch", WixFragmentBuilder.is64Bit() ? "x64" : "x86", - "-out", wixObj.toAbsolutePath().toString() + "-out", wixObj.toString() )); addWixVariblesToCommandLine(wixSource.variables, cmdline); @@ -201,19 +266,19 @@ private Path compileWix3(WixSource wixSource) throws IOException { } private void execute(List cmdline) throws IOException { - Executor.of(new ProcessBuilder(cmdline).directory(workDir.toFile())). - executeExpectSuccess(); + Executor.of(new ProcessBuilder(cmdline).directory(workDir.toFile())).executeExpectSuccess(); } - private static final class WixSource { - Path source; - Map variables; + private record WixSource(Path path, Map variables) { + WixSource overridePath(Path path) { + return new WixSource(path, variables); + } } - private WixToolset toolset; - private Map wixVariables; - private List lightOptions; - private Path wixObjDir; - private Path workDir; - private List sources; + private final WixToolset toolset; + private final Map wixVariables; + private final List lightOptions; + private final Path wixObjDir; + private final Path workDir; + private final List sources; } diff --git a/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WixUiFragmentBuilder.java b/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WixUiFragmentBuilder.java index 5eb23fc58c4e3..25db6e6ab0b50 100644 --- a/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WixUiFragmentBuilder.java +++ b/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/WixUiFragmentBuilder.java @@ -97,7 +97,7 @@ void initFromParams(Map params) { } @Override - void configureWixPipeline(WixPipeline wixPipeline) { + void configureWixPipeline(WixPipeline.Builder wixPipeline) { super.configureWixPipeline(wixPipeline); if (withShortcutPromptDlg || withInstallDirChooserDlg || withLicenseDlg) { @@ -518,7 +518,7 @@ private final class CustomDialog { wxsFileName), wxsFileName); } - void addToWixPipeline(WixPipeline wixPipeline) { + void addToWixPipeline(WixPipeline.Builder wixPipeline) { wixPipeline.addSource(getConfigRoot().toAbsolutePath().resolve( wxsFileName), wixVariables.getValues()); } diff --git a/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/resources/WinResources.properties b/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/resources/WinResources.properties index 9e7504364d35a..584342397a6df 100644 --- a/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/resources/WinResources.properties +++ b/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/resources/WinResources.properties @@ -56,6 +56,7 @@ error.lock-resource=Failed to lock: {0} error.unlock-resource=Failed to unlock: {0} error.read-wix-l10n-file=Failed to parse {0} file error.extract-culture-from-wix-l10n-file=Failed to read value of culture from {0} file +error.short-path-conv-fail=Failed to get short version of "{0}" path message.icon-not-ico=The specified icon "{0}" is not an ICO file and will not be used. The default icon will be used in it's place. message.potential.windows.defender.issue=Warning: Windows Defender may prevent jpackage from functioning. If there is an issue, it can be addressed by either disabling realtime monitoring, or adding an exclusion for the directory "{0}". diff --git a/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/resources/WinResources_de.properties b/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/resources/WinResources_de.properties index a7212d9640a7a..dce8ca6176d57 100644 --- a/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/resources/WinResources_de.properties +++ b/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/resources/WinResources_de.properties @@ -56,6 +56,7 @@ error.lock-resource=Sperren nicht erfolgreich: {0} error.unlock-resource=Aufheben der Sperre nicht erfolgreich: {0} error.read-wix-l10n-file=Datei {0} konnte nicht geparst werden error.extract-culture-from-wix-l10n-file=Kulturwert konnte nicht aus Datei {0} gelesen werden +error.short-path-conv-fail=Failed to get short version of "{0}" path message.icon-not-ico=Das angegebene Symbol "{0}" ist keine ICO-Datei und wird nicht verwendet. Stattdessen wird das Standardsymbol verwendet. message.potential.windows.defender.issue=Warnung: Windows Defender verhindert eventuell die korrekte Ausführung von jpackage. Wenn ein Problem auftritt, deaktivieren Sie das Echtzeitmonitoring, oder fügen Sie einen Ausschluss für das Verzeichnis "{0}" hinzu. diff --git a/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/resources/WinResources_ja.properties b/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/resources/WinResources_ja.properties index 352aab7a4934b..47e5b585869a7 100644 --- a/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/resources/WinResources_ja.properties +++ b/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/resources/WinResources_ja.properties @@ -56,6 +56,7 @@ error.lock-resource=ロックに失敗しました: {0} error.unlock-resource=ロック解除に失敗しました: {0} error.read-wix-l10n-file={0}ファイルの解析に失敗しました error.extract-culture-from-wix-l10n-file={0}ファイルからのカルチャの値の読取りに失敗しました +error.short-path-conv-fail=Failed to get short version of "{0}" path message.icon-not-ico=指定したアイコン"{0}"はICOファイルではなく、使用されません。デフォルト・アイコンがその位置に使用されます。 message.potential.windows.defender.issue=警告: Windows Defenderが原因でjpackageが機能しないことがあります。問題が発生した場合は、リアルタイム・モニタリングを無効にするか、ディレクトリ"{0}"の除外を追加することにより、問題に対処できます。 diff --git a/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/resources/WinResources_zh_CN.properties b/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/resources/WinResources_zh_CN.properties index a8d4a4471d6d0..abd3d13a66739 100644 --- a/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/resources/WinResources_zh_CN.properties +++ b/src/jdk.jpackage/windows/classes/jdk/jpackage/internal/resources/WinResources_zh_CN.properties @@ -56,6 +56,7 @@ error.lock-resource=无法锁定:{0} error.unlock-resource=无法解锁:{0} error.read-wix-l10n-file=无法解析 {0} 文件 error.extract-culture-from-wix-l10n-file=无法从 {0} 文件读取文化值 +error.short-path-conv-fail=Failed to get short version of "{0}" path message.icon-not-ico=指定的图标 "{0}" 不是 ICO 文件, 不会使用。将使用默认图标代替。 message.potential.windows.defender.issue=警告:Windows Defender 可能会阻止 jpackage 正常工作。如果存在问题,可以通过禁用实时监视或者为目录 "{0}" 添加排除项来解决。 diff --git a/src/jdk.jpackage/windows/native/common/WinFileUtils.cpp b/src/jdk.jpackage/windows/native/common/WinFileUtils.cpp index 993aed8bb131f..f801009ed94a9 100644 --- a/src/jdk.jpackage/windows/native/common/WinFileUtils.cpp +++ b/src/jdk.jpackage/windows/native/common/WinFileUtils.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2024, 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 @@ -668,4 +668,23 @@ tstring stripExeSuffix(const tstring& path) { return path.substr(0, pos); } +tstring toShortPath(const tstring& path) { + const DWORD len = GetShortPathName(path.c_str(), nullptr, 0); + if (0 == len) { + JP_THROW(SysError(tstrings::any() << "GetShortPathName(" + << path << ") failed", GetShortPathName)); + } + + std::vector buf; + buf.resize(len); + const DWORD copied = GetShortPathName(path.c_str(), buf.data(), + static_cast(buf.size())); + if (copied != buf.size() - 1) { + JP_THROW(SysError(tstrings::any() << "GetShortPathName(" + << path << ") failed", GetShortPathName)); + } + + return tstring(buf.data(), buf.size() - 1); +} + } // namespace FileUtils diff --git a/src/jdk.jpackage/windows/native/common/WinFileUtils.h b/src/jdk.jpackage/windows/native/common/WinFileUtils.h index 2dfb32fa08849..ba07efec78e8c 100644 --- a/src/jdk.jpackage/windows/native/common/WinFileUtils.h +++ b/src/jdk.jpackage/windows/native/common/WinFileUtils.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2024, 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 @@ -315,6 +315,8 @@ namespace FileUtils { std::ofstream tmp; tstring dstPath; }; + + tstring toShortPath(const tstring& path); } // FileUtils #endif // WINFILEUTILS_H diff --git a/src/jdk.jpackage/windows/native/libjpackage/jpackage.cpp b/src/jdk.jpackage/windows/native/libjpackage/jpackage.cpp index 6317842787e52..66fa92e35637b 100644 --- a/src/jdk.jpackage/windows/native/libjpackage/jpackage.cpp +++ b/src/jdk.jpackage/windows/native/libjpackage/jpackage.cpp @@ -25,6 +25,8 @@ #include "ResourceEditor.h" #include "ErrorHandling.h" +#include "FileUtils.h" +#include "WinFileUtils.h" #include "IconSwap.h" #include "VersionInfo.h" #include "JniUtils.h" @@ -162,4 +164,25 @@ extern "C" { return 1; } + /* + * Class: jdk_jpackage_internal_ShortPathUtils + * Method: getShortPath + * Signature: (Ljava/lang/String;)Ljava/lang/String; + */ + JNIEXPORT jstring JNICALL + Java_jdk_jpackage_internal_ShortPathUtils_getShortPath( + JNIEnv *pEnv, jclass c, jstring jLongPath) { + + JP_TRY; + + const std::wstring longPath = jni::toUnicodeString(pEnv, jLongPath); + std::wstring shortPath = FileUtils::toShortPath(longPath); + + return jni::toJString(pEnv, shortPath); + + JP_CATCH_ALL; + + return NULL; + } + } // extern "C" \ No newline at end of file diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/Executor.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/Executor.java index f182f4f7f7dc4..00f6ab5263ca5 100644 --- a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/Executor.java +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/Executor.java @@ -53,7 +53,7 @@ public static Executor of(String... cmdline) { public Executor() { saveOutputType = new HashSet<>(Set.of(SaveOutputType.NONE)); - removePath = false; + removePathEnvVar = false; } public Executor setExecutable(String v) { @@ -85,8 +85,8 @@ public Executor setExecutable(JavaTool v) { return setExecutable(v.getPath()); } - public Executor setRemovePath(boolean value) { - removePath = value; + public Executor setRemovePathEnvVar(boolean value) { + removePathEnvVar = value; return this; } @@ -348,7 +348,7 @@ private Result runExecutable() throws IOException, InterruptedException { builder.directory(directory.toFile()); sb.append(String.format("; in directory [%s]", directory)); } - if (removePath) { + if (removePathEnvVar) { // run this with cleared Path in Environment TKit.trace("Clearing PATH in environment"); builder.environment().remove("PATH"); @@ -478,7 +478,7 @@ private static void trace(String msg) { private Path executable; private Set saveOutputType; private Path directory; - private boolean removePath; + private boolean removePathEnvVar; private String winTmpDir = null; private static enum SaveOutputType { diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/HelloApp.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/HelloApp.java index bc35912bcbb6c..0c7476e863dc4 100644 --- a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/HelloApp.java +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/HelloApp.java @@ -354,12 +354,12 @@ public static final class AppOutputVerifier { if (TKit.isWindows()) { // When running app launchers on Windows, clear users environment (JDK-8254920) - removePath(true); + removePathEnvVar(true); } } - public AppOutputVerifier removePath(boolean v) { - removePath = v; + public AppOutputVerifier removePathEnvVar(boolean v) { + removePathEnvVar = v; return this; } @@ -455,7 +455,7 @@ private Executor getExecutor(String...args) { Path outputFile = TKit.workDir().resolve(OUTPUT_FILENAME); ThrowingFunction.toFunction(Files::deleteIfExists).apply(outputFile); - final Path executablePath; + Path executablePath; if (launcherPath.isAbsolute()) { executablePath = launcherPath; } else { @@ -463,18 +463,27 @@ private Executor getExecutor(String...args) { executablePath = Path.of(".").resolve(launcherPath.normalize()); } + if (TKit.isWindows()) { + var absExecutablePath = executablePath.toAbsolutePath().normalize(); + var shortPath = WindowsHelper.toShortPath(absExecutablePath); + if (shortPath.isPresent()) { + TKit.trace(String.format("Will run [%s] as [%s]", executablePath, shortPath.get())); + executablePath = shortPath.get(); + } + } + final List launcherArgs = List.of(args); return new Executor() .setDirectory(outputFile.getParent()) .saveOutput(saveOutput) .dumpOutput() - .setRemovePath(removePath) + .setRemovePathEnvVar(removePathEnvVar) .setExecutable(executablePath) .addArguments(launcherArgs); } private boolean launcherNoExit; - private boolean removePath; + private boolean removePathEnvVar; private boolean saveOutput; private final Path launcherPath; private Path outputFilePath; diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/WindowsHelper.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/WindowsHelper.java index 42ea9e3e9a74f..4fb937864aa6e 100644 --- a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/WindowsHelper.java +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/WindowsHelper.java @@ -23,6 +23,7 @@ package jdk.jpackage.test; import java.io.IOException; +import java.lang.reflect.Method; import java.nio.file.Files; import java.nio.file.Path; import java.util.HashMap; @@ -36,7 +37,9 @@ import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; +import static jdk.jpackage.internal.util.function.ExceptionBox.rethrowUnchecked; import jdk.jpackage.internal.util.function.ThrowingRunnable; +import static jdk.jpackage.internal.util.function.ThrowingSupplier.toSupplier; import jdk.jpackage.test.PackageTest.PackageHandlers; public class WindowsHelper { @@ -94,8 +97,9 @@ private static void runMsiexecWithRetries(Executor misexec) { static PackageHandlers createMsiPackageHandlers() { BiConsumer installMsi = (cmd, install) -> { cmd.verifyIsOfType(PackageType.WIN_MSI); + var msiPath = TransientMsi.create(cmd).path(); runMsiexecWithRetries(Executor.of("msiexec", "/qn", "/norestart", - install ? "/i" : "/x").addArgument(cmd.outputBundle().normalize())); + install ? "/i" : "/x").addArgument(msiPath)); }; PackageHandlers msi = new PackageHandlers(); @@ -112,6 +116,8 @@ static PackageHandlers createMsiPackageHandlers() { TKit.removeRootFromAbsolutePath( getInstallationRootDirectory(cmd))); + final Path msiPath = TransientMsi.create(cmd).path(); + // Put msiexec in .bat file because can't pass value of TARGETDIR // property containing spaces through ProcessBuilder properly. // Set folder permissions to allow msiexec unpack msi bundle. @@ -121,7 +127,7 @@ static PackageHandlers createMsiPackageHandlers() { String.join(" ", List.of( "msiexec", "/a", - String.format("\"%s\"", cmd.outputBundle().normalize()), + String.format("\"%s\"", msiPath), "/qn", String.format("TARGETDIR=\"%s\"", unpackDir.toAbsolutePath().normalize()))))); @@ -155,6 +161,49 @@ static PackageHandlers createMsiPackageHandlers() { return msi; } + record TransientMsi(Path path) { + static TransientMsi create(JPackageCommand cmd) { + var outputMsiPath = cmd.outputBundle().normalize(); + if (isPathTooLong(outputMsiPath)) { + return toSupplier(() -> { + var transientMsiPath = TKit.createTempDirectory("msi-copy").resolve("a.msi").normalize(); + TKit.trace(String.format("Copy [%s] to [%s]", outputMsiPath, transientMsiPath)); + Files.copy(outputMsiPath, transientMsiPath); + return new TransientMsi(transientMsiPath); + }).get(); + } else { + return new TransientMsi(outputMsiPath); + } + } + } + + public enum WixType { + WIX3, + WIX4 + } + + public static WixType getWixTypeFromVerboseJPackageOutput(Executor.Result result) { + return result.getOutput().stream().map(str -> { + if (str.contains("[light.exe]")) { + return WixType.WIX3; + } else if (str.contains("[wix.exe]")) { + return WixType.WIX4; + } else { + return null; + } + }).filter(Objects::nonNull).reduce((a, b) -> { + throw new IllegalArgumentException("Invalid input: multiple invocations of WiX tools"); + }).orElseThrow(() -> new IllegalArgumentException("Invalid input: no invocations of WiX tools")); + } + + static Optional toShortPath(Path path) { + if (isPathTooLong(path)) { + return Optional.of(ShortPathUtils.toShortPath(path)); + } else { + return Optional.empty(); + } + } + static PackageHandlers createExePackageHandlers() { BiConsumer installExe = (cmd, install) -> { cmd.verifyIsOfType(PackageType.WIN_EXE); @@ -303,6 +352,10 @@ private static boolean isUserLocalInstall(JPackageCommand cmd) { return cmd.hasArgument("--win-per-user-install"); } + private static boolean isPathTooLong(Path path) { + return path.toString().length() > WIN_MAX_PATH; + } + private static class DesktopIntegrationVerifier { DesktopIntegrationVerifier(JPackageCommand cmd, String launcherName) { @@ -525,6 +578,32 @@ private static String queryRegistryValueCache(String keyPath, return value; } + private static final class ShortPathUtils { + private ShortPathUtils() { + try { + var shortPathUtilsClass = Class.forName("jdk.jpackage.internal.ShortPathUtils"); + + getShortPathWrapper = shortPathUtilsClass.getDeclaredMethod( + "getShortPathWrapper", String.class); + // Note: this reflection call requires + // --add-opens jdk.jpackage/jdk.jpackage.internal=ALL-UNNAMED + getShortPathWrapper.setAccessible(true); + } catch (ClassNotFoundException | NoSuchMethodException + | SecurityException ex) { + throw rethrowUnchecked(ex); + } + } + + static Path toShortPath(Path path) { + return Path.of(toSupplier(() -> (String) INSTANCE.getShortPathWrapper.invoke( + null, path.toString())).get()); + } + + private final Method getShortPathWrapper; + + private static final ShortPathUtils INSTANCE = new ShortPathUtils(); + } + static final Set CRITICAL_RUNTIME_FILES = Set.of(Path.of( "bin\\server\\jvm.dll")); @@ -540,4 +619,6 @@ private static String queryRegistryValueCache(String keyPath, private static final String USER_SHELL_FOLDERS_REGKEY = "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders"; private static final Map REGISTRY_VALUES = new HashMap<>(); + + private static final int WIN_MAX_PATH = 260; } diff --git a/test/jdk/tools/jpackage/windows/WinL10nTest.java b/test/jdk/tools/jpackage/windows/WinL10nTest.java index 814b6401f471b..dee1e42267d91 100644 --- a/test/jdk/tools/jpackage/windows/WinL10nTest.java +++ b/test/jdk/tools/jpackage/windows/WinL10nTest.java @@ -35,6 +35,8 @@ import java.util.stream.Collectors; import java.util.stream.Stream; import jdk.jpackage.test.Executor; +import static jdk.jpackage.test.WindowsHelper.WixType.WIX3; +import static jdk.jpackage.test.WindowsHelper.getWixTypeFromVerboseJPackageOutput; /* * @test @@ -109,13 +111,13 @@ public static List data() { }); } - private static Stream getBuildCommandLine(Executor.Result result) { + private static Stream getWixCommandLine(Executor.Result result) { return result.getOutput().stream().filter(createToolCommandLinePredicate("light").or( createToolCommandLinePredicate("wix"))); } private static boolean isWix3(Executor.Result result) { - return result.getOutput().stream().anyMatch(createToolCommandLinePredicate("light")); + return getWixTypeFromVerboseJPackageOutput(result) == WIX3; } private final static Predicate createToolCommandLinePredicate(String wixToolName) { @@ -127,10 +129,10 @@ private final static Predicate createToolCommandLinePredicate(String wix }; } - private static List createDefaultL10nFilesLocVerifiers(Path tempDir) { + private static List createDefaultL10nFilesLocVerifiers(Path wixSrcDir) { return Arrays.stream(DEFAULT_L10N_FILES).map(loc -> - TKit.assertTextStream("-loc " + tempDir.resolve( - String.format("config/MsiInstallerStrings_%s.wxl", loc)).normalize())) + TKit.assertTextStream("-loc " + wixSrcDir.resolve( + String.format("MsiInstallerStrings_%s.wxl", loc)))) .toList(); } @@ -183,16 +185,20 @@ public void test() throws IOException { cmd.addArguments("--temp", tempDir); }) .addBundleVerifier((cmd, result) -> { + final List wixCmdline = getWixCommandLine(result).toList(); + + final var isWix3 = isWix3(result); + if (expectedCultures != null) { String expected; - if (isWix3(result)) { + if (isWix3) { expected = "-cultures:" + String.join(";", expectedCultures); } else { expected = Stream.of(expectedCultures).map(culture -> { return String.join(" ", "-culture", culture); }).collect(Collectors.joining(" ")); } - TKit.assertTextStream(expected).apply(getBuildCommandLine(result)); + TKit.assertTextStream(expected).apply(wixCmdline.stream()); } if (expectedErrorMessage != null) { @@ -201,25 +207,27 @@ public void test() throws IOException { } if (wxlFileInitializers != null) { - var wixSrcDir = Path.of(cmd.getArgumentValue("--temp")).resolve("config"); + var wixSrcDir = Path.of(cmd.getArgumentValue("--temp")).resolve( + "config").normalize().toAbsolutePath(); if (allWxlFilesValid) { for (var v : wxlFileInitializers) { if (!v.name.startsWith("MsiInstallerStrings_")) { - v.createCmdOutputVerifier(wixSrcDir).apply(getBuildCommandLine(result)); + v.createCmdOutputVerifier(wixSrcDir).apply(wixCmdline.stream()); } } - var tempDir = Path.of(cmd.getArgumentValue("--temp")).toAbsolutePath(); - for (var v : createDefaultL10nFilesLocVerifiers(tempDir)) { - v.apply(getBuildCommandLine(result)); + + for (var v : createDefaultL10nFilesLocVerifiers(wixSrcDir)) { + v.apply(wixCmdline.stream()); } } else { Stream.of(wxlFileInitializers) .filter(Predicate.not(WixFileInitializer::isValid)) .forEach(v -> v.createCmdOutputVerifier( wixSrcDir).apply(result.getOutput().stream())); - TKit.assertFalse(getBuildCommandLine(result).findAny().isPresent(), - "Check light.exe was not invoked"); + TKit.assertTrue(wixCmdline.stream().findAny().isEmpty(), + String.format("Check %s.exe was not invoked", + isWix3 ? "light" : "wix")); } } }); @@ -276,10 +284,9 @@ boolean isValid() { } @Override - TKit.TextStreamVerifier createCmdOutputVerifier(Path root) { + TKit.TextStreamVerifier createCmdOutputVerifier(Path wixSrcDir) { return TKit.assertTextStream(String.format( - "Failed to parse %s file", - root.resolve("b.wxl").toAbsolutePath())); + "Failed to parse %s file", wixSrcDir.resolve("b.wxl"))); } }; } @@ -297,9 +304,8 @@ void apply(Path root) throws IOException { + "\" xmlns=\"http://schemas.microsoft.com/wix/2006/localization\" Codepage=\"1252\"/>")); } - TKit.TextStreamVerifier createCmdOutputVerifier(Path root) { - return TKit.assertTextStream( - "-loc " + root.resolve(name).toAbsolutePath().normalize()); + TKit.TextStreamVerifier createCmdOutputVerifier(Path wixSrcDir) { + return TKit.assertTextStream("-loc " + wixSrcDir.resolve(name)); } boolean isValid() { diff --git a/test/jdk/tools/jpackage/windows/WinLongPathTest.java b/test/jdk/tools/jpackage/windows/WinLongPathTest.java new file mode 100644 index 0000000000000..e9e5ef8ce038e --- /dev/null +++ b/test/jdk/tools/jpackage/windows/WinLongPathTest.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2024, 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. + * + * 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. + */ + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import jdk.jpackage.test.Annotations.Parameters; +import jdk.jpackage.test.PackageTest; +import jdk.jpackage.test.PackageType; +import jdk.jpackage.test.Annotations.Test; +import jdk.jpackage.test.JPackageCommand; +import jdk.jpackage.test.RunnablePackageTest.Action; +import jdk.jpackage.test.TKit; + +/* +/* @test + * @bug 8289771 + * @summary jpackage with long paths on windows + * @library /test/jdk/tools/jpackage/helpers + * @key jpackagePlatformPackage + * @build jdk.jpackage.test.* + * @requires (os.family == "windows") + * @compile WinLongPathTest.java + * @run main/othervm/timeout=540 -Xmx512m jdk.jpackage.test.Main + * --jpt-space-subst=* + * --jpt-exclude=WinLongPathTest(false,*--temp) + * --jpt-run=WinLongPathTest + */ + +public record WinLongPathTest(Boolean appImage, String optionName) { + + @Parameters + public static List input() { + List data = new ArrayList<>(); + for (var appImage : List.of(Boolean.TRUE, Boolean.FALSE)) { + for (var option : List.of("--dest", "--temp")) { + data.add(new Object[]{appImage, option}); + } + } + return data; + } + + @Test + public void test() throws IOException { + if (appImage) { + var cmd = JPackageCommand.helloAppImage(); + setOptionLongPath(cmd, optionName); + cmd.executeAndAssertHelloAppImageCreated(); + } else { + new PackageTest() + .forTypes(PackageType.WINDOWS) + .configureHelloApp() + .addInitializer(cmd -> setOptionLongPath(cmd, optionName)) + .run(Action.CREATE_AND_UNPACK); + } + } + + private static void setOptionLongPath(JPackageCommand cmd, String option) throws IOException { + var root = TKit.createTempDirectory("long-path"); + // 261 characters in total, which alone is above the 260 threshold + var longPath = root.resolve(Path.of("a".repeat(80), "b".repeat(90), "c".repeat(91))); + Files.createDirectories(longPath); + cmd.setArgumentValue(option, longPath); + } +} From 27fda0ea1f7e230a1b8a8413efc2d4314b600a82 Mon Sep 17 00:00:00 2001 From: Phil Race Date: Wed, 20 Nov 2024 18:38:08 +0000 Subject: [PATCH 52/74] 8344578: Clean up left over java.security and sun.security imports in Swing classes Reviewed-by: psadhukhan --- .../share/classes/javax/swing/RepaintManager.java | 6 ------ .../classes/javax/swing/SwingPaintEventDispatcher.java | 1 - .../classes/javax/swing/plaf/basic/BasicOptionPaneUI.java | 4 ---- .../classes/javax/swing/plaf/metal/MetalLookAndFeel.java | 1 - 4 files changed, 12 deletions(-) diff --git a/src/java.desktop/share/classes/javax/swing/RepaintManager.java b/src/java.desktop/share/classes/javax/swing/RepaintManager.java index 2636c81be075f..4799472d44fb5 100644 --- a/src/java.desktop/share/classes/javax/swing/RepaintManager.java +++ b/src/java.desktop/share/classes/javax/swing/RepaintManager.java @@ -32,14 +32,11 @@ import java.util.concurrent.atomic.AtomicInteger; import java.applet.*; -import jdk.internal.access.JavaSecurityAccess; -import jdk.internal.access.SharedSecrets; import sun.awt.AWTAccessor; import sun.awt.AppContext; import sun.awt.DisplayChangedListener; import sun.awt.SunToolkit; import sun.java2d.SunGraphicsEnvironment; -import sun.security.action.GetPropertyAction; import com.sun.java.swing.SwingUtilities3; import java.awt.geom.AffineTransform; @@ -185,9 +182,6 @@ public class RepaintManager */ private final ProcessingRunnable processingRunnable; - private static final JavaSecurityAccess javaSecurityAccess = - SharedSecrets.getJavaSecurityAccess(); - /** * Listener installed to detect display changes. When display changes, * schedules a callback to notify all RepaintManagers of the display diff --git a/src/java.desktop/share/classes/javax/swing/SwingPaintEventDispatcher.java b/src/java.desktop/share/classes/javax/swing/SwingPaintEventDispatcher.java index 4bada6e8bc726..1cabf129db13e 100644 --- a/src/java.desktop/share/classes/javax/swing/SwingPaintEventDispatcher.java +++ b/src/java.desktop/share/classes/javax/swing/SwingPaintEventDispatcher.java @@ -28,7 +28,6 @@ import java.awt.Container; import java.awt.Rectangle; import java.awt.event.PaintEvent; -import java.security.AccessController; import sun.awt.AppContext; import sun.awt.SunToolkit; import sun.awt.event.IgnorePaintEvent; diff --git a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicOptionPaneUI.java b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicOptionPaneUI.java index 2e61967031ce6..07036eedbf6ea 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicOptionPaneUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicOptionPaneUI.java @@ -39,10 +39,6 @@ import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.Locale; -import java.security.AccessController; - -import sun.security.action.GetPropertyAction; - /** * Provides the basic look and feel for a JOptionPane. diff --git a/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalLookAndFeel.java b/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalLookAndFeel.java index 18547fcbbf94b..41d90d31dd4f1 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalLookAndFeel.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalLookAndFeel.java @@ -64,7 +64,6 @@ import sun.awt.AppContext; import sun.awt.OSInfo; import sun.awt.SunToolkit; -import sun.security.action.GetPropertyAction; import sun.swing.DefaultLayoutStyle; import sun.swing.SwingAccessor; import sun.swing.SwingUtilities2; From 22a39dc858a27cecfb0a8a8ef42e2cf5f7444545 Mon Sep 17 00:00:00 2001 From: Phil Race Date: Wed, 20 Nov 2024 18:45:49 +0000 Subject: [PATCH 53/74] 8344064: Remove doPrivileged calls from print/imageio/media classes in the java.desktop module Reviewed-by: kizune --- .../imageio/plugins/bmp/BMPImageReader.java | 12 +--- .../imageio/plugins/jpeg/JPEGImageReader.java | 11 +--- .../imageio/plugins/jpeg/JPEGImageWriter.java | 11 +--- .../com/sun/imageio/stream/StreamCloser.java | 29 ++++----- .../com/sun/java/swing/plaf/gtk/Metacity.java | 38 +++-------- .../sun/media/sound/JARSoundbankReader.java | 6 +- .../com/sun/media/sound/JDK13Services.java | 6 +- .../sun/media/sound/JSSecurityManager.java | 47 +++----------- .../classes/com/sun/media/sound/Platform.java | 9 +-- .../classes/com/sun/media/sound/Printer.java | 5 +- .../com/sun/media/sound/SoftSynthesizer.java | 64 +++++++++---------- .../share/classes/javax/imageio/ImageIO.java | 4 +- .../javax/imageio/metadata/IIOMetadata.java | 7 +- .../javax/imageio/spi/IIORegistry.java | 34 +++------- .../imageio/spi/ImageReaderWriterSpi.java | 7 +- .../javax/imageio/spi/ServiceRegistry.java | 20 +----- .../share/classes/javax/print/DocFlavor.java | 5 +- .../javax/print/PrintServiceLookup.java | 30 ++------- .../print/StreamPrintServiceFactory.java | 46 ++++--------- 19 files changed, 102 insertions(+), 289 deletions(-) diff --git a/src/java.desktop/share/classes/com/sun/imageio/plugins/bmp/BMPImageReader.java b/src/java.desktop/share/classes/com/sun/imageio/plugins/bmp/BMPImageReader.java index 9eab27031d4f9..06af183b37c9b 100644 --- a/src/java.desktop/share/classes/com/sun/imageio/plugins/bmp/BMPImageReader.java +++ b/src/java.desktop/share/classes/com/sun/imageio/plugins/bmp/BMPImageReader.java @@ -48,8 +48,6 @@ import java.io.ByteArrayInputStream; import java.io.IOException; import java.nio.ByteOrder; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Iterator; import java.util.List; @@ -2039,17 +2037,9 @@ public void readAborted(ImageReader src) {} private static Boolean isLinkedProfileAllowed = null; - @SuppressWarnings("removal") private static boolean isLinkedProfileAllowed() { if (isLinkedProfileAllowed == null) { - PrivilegedAction a = new PrivilegedAction() { - @Override - public Boolean run() { - return Boolean. - getBoolean("sun.imageio.bmp.enableLinkedProfiles"); - } - }; - isLinkedProfileAllowed = AccessController.doPrivileged(a); + isLinkedProfileAllowed = Boolean.getBoolean("sun.imageio.bmp.enableLinkedProfiles"); } return isLinkedProfileAllowed; } diff --git a/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageReader.java b/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageReader.java index c28759058c086..24013fb68add0 100644 --- a/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageReader.java +++ b/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageReader.java @@ -90,16 +90,9 @@ public class JPEGImageReader extends ImageReader { initStatic(); } - @SuppressWarnings({"removal", "restricted"}) + @SuppressWarnings("restricted") private static void initStatic() { - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - @Override - public Void run() { - System.loadLibrary("javajpeg"); - return null; - } - }); + System.loadLibrary("javajpeg"); initReaderIDs(ImageInputStream.class, JPEGQTable.class, JPEGHuffmanTable.class); diff --git a/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageWriter.java b/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageWriter.java index 39189130be356..f263d47f6c9a1 100644 --- a/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageWriter.java +++ b/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageWriter.java @@ -175,16 +175,9 @@ public class JPEGImageWriter extends ImageWriter { initStatic(); } - @SuppressWarnings({"removal", "restricted"}) + @SuppressWarnings("restricted") private static void initStatic() { - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - @Override - public Void run() { - System.loadLibrary("javajpeg"); - return null; - } - }); + System.loadLibrary("javajpeg"); initWriterIDs(JPEGQTable.class, JPEGHuffmanTable.class); } diff --git a/src/java.desktop/share/classes/com/sun/imageio/stream/StreamCloser.java b/src/java.desktop/share/classes/com/sun/imageio/stream/StreamCloser.java index 3dabca71ffb4f..b40c53ead3d95 100644 --- a/src/java.desktop/share/classes/com/sun/imageio/stream/StreamCloser.java +++ b/src/java.desktop/share/classes/com/sun/imageio/stream/StreamCloser.java @@ -28,8 +28,6 @@ import sun.awt.util.ThreadGroupUtils; import java.io.IOException; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.Set; import java.util.WeakHashMap; import javax.imageio.stream.ImageInputStream; @@ -86,21 +84,18 @@ public void run() { } }; - AccessController.doPrivileged((PrivilegedAction) () -> { - /* The thread must be a member of a thread group - * which will not get GCed before VM exit. - * Make its parent the top-level thread group. - */ - ThreadGroup tg = ThreadGroupUtils.getRootThreadGroup(); - streamCloser = new Thread(tg, streamCloserRunnable, - "StreamCloser", 0, false); - /* Set context class loader to null in order to avoid - * keeping a strong reference to an application classloader. - */ - streamCloser.setContextClassLoader(null); - Runtime.getRuntime().addShutdownHook(streamCloser); - return null; - }); + /* The thread must be a member of a thread group + * which will not get GCed before VM exit. + * Make its parent the top-level thread group. + */ + ThreadGroup tg = ThreadGroupUtils.getRootThreadGroup(); + streamCloser = new Thread(tg, streamCloserRunnable, + "StreamCloser", 0, false); + /* Set context class loader to null in order to avoid + * keeping a strong reference to an application classloader. + */ + streamCloser.setContextClassLoader(null); + Runtime.getRuntime().addShutdownHook(streamCloser); } } } diff --git a/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java b/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java index 295e474579bd7..629b107f163c9 100644 --- a/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java +++ b/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java @@ -60,8 +60,6 @@ import java.io.Reader; import java.net.MalformedURLException; import java.net.URL; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; @@ -506,21 +504,12 @@ void paintFrameBorder(SynthContext context, Graphics g, int x0, int y0, int widt - private static class Privileged implements PrivilegedAction { + private static class ThemeGetter { private static int GET_THEME_DIR = 0; private static int GET_USER_THEME = 1; private static int GET_IMAGE = 2; - private int type; - private Object arg; - @SuppressWarnings("removal") - public Object doPrivileged(int type, Object arg) { - this.type = type; - this.arg = arg; - return AccessController.doPrivileged(this); - } - - public Object run() { + public Object getThemeItem(int type, Object arg) { if (type == GET_THEME_DIR) { String sep = File.separator; String[] dirs = new String[] { @@ -618,11 +607,11 @@ public Object run() { } private static URL getThemeDir(String themeName) { - return (URL)new Privileged().doPrivileged(Privileged.GET_THEME_DIR, themeName); + return (URL)new ThemeGetter().getThemeItem(ThemeGetter.GET_THEME_DIR, themeName); } private static String getUserTheme() { - return (String)new Privileged().doPrivileged(Privileged.GET_USER_THEME, null); + return (String)new ThemeGetter().getThemeItem(ThemeGetter.GET_USER_THEME, null); } protected void tileImage(Graphics g, Image image, int x0, int y0, int w, int h, float[] alphas) { @@ -673,7 +662,7 @@ protected Image getImage(String key) { try { @SuppressWarnings("deprecation") URL url = new URL(themeDir, key); - image = (Image)new Privileged().doPrivileged(Privileged.GET_IMAGE, url); + image = (Image)new ThemeGetter().getThemeItem(ThemeGetter.GET_IMAGE, url); } catch (MalformedURLException ex) { //log("Bad image url: "+ themeDir + "/" + key); } @@ -1587,18 +1576,11 @@ protected static Document getXMLDoc(final URL xmlFile) documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); } - @SuppressWarnings("removal") - InputStream inputStream = - AccessController.doPrivileged(new PrivilegedAction() { - public InputStream run() { - try { - return new BufferedInputStream(xmlFile.openStream()); - } catch (IOException ex) { - return null; - } - } - }); - + InputStream inputStream = null; + try { + inputStream = new BufferedInputStream(xmlFile.openStream()); + } catch (IOException ex) { + } Document doc = null; if (inputStream != null) { doc = documentBuilder.parse(inputStream); diff --git a/src/java.desktop/share/classes/com/sun/media/sound/JARSoundbankReader.java b/src/java.desktop/share/classes/com/sun/media/sound/JARSoundbankReader.java index 6447e654f600e..4ff72c7040a8e 100644 --- a/src/java.desktop/share/classes/com/sun/media/sound/JARSoundbankReader.java +++ b/src/java.desktop/share/classes/com/sun/media/sound/JARSoundbankReader.java @@ -32,7 +32,6 @@ import java.io.InputStreamReader; import java.net.URL; import java.net.URLClassLoader; -import java.security.AccessController; import java.util.ArrayList; import java.util.Objects; @@ -55,10 +54,7 @@ public final class JARSoundbankReader extends SoundbankReader { * {@code true} if jar sound bank is allowed to be loaded default is * {@code false}. */ - @SuppressWarnings("removal") - private static final boolean JAR_SOUNDBANK_ENABLED = - AccessController.doPrivileged( - new GetBooleanAction("jdk.sound.jarsoundbank")); + private static final boolean JAR_SOUNDBANK_ENABLED = Boolean.getBoolean("jdk.sound.jarsoundbank"); private static boolean isZIP(URL url) { boolean ok = false; diff --git a/src/java.desktop/share/classes/com/sun/media/sound/JDK13Services.java b/src/java.desktop/share/classes/com/sun/media/sound/JDK13Services.java index 0d8f34ca225dd..4ed79db13b55f 100644 --- a/src/java.desktop/share/classes/com/sun/media/sound/JDK13Services.java +++ b/src/java.desktop/share/classes/com/sun/media/sound/JDK13Services.java @@ -25,8 +25,6 @@ package com.sun.media.sound; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -170,9 +168,7 @@ private static synchronized String getDefaultProvider(Class typeClass) { return null; } String name = typeClass.getName(); - @SuppressWarnings("removal") - String value = AccessController.doPrivileged( - (PrivilegedAction) () -> System.getProperty(name)); + String value = System.getProperty(name); if (value == null) { value = getProperties().getProperty(name); } diff --git a/src/java.desktop/share/classes/com/sun/media/sound/JSSecurityManager.java b/src/java.desktop/share/classes/com/sun/media/sound/JSSecurityManager.java index 51482b24aeaae..e9b99ac1a1097 100644 --- a/src/java.desktop/share/classes/com/sun/media/sound/JSSecurityManager.java +++ b/src/java.desktop/share/classes/com/sun/media/sound/JSSecurityManager.java @@ -29,8 +29,6 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Iterator; import java.util.List; @@ -41,7 +39,7 @@ /** Managing security in the Java Sound implementation. * This class contains all code that uses and is used by - * SecurityManager.doPrivileged(). + * SecurityManager * * @author Matthias Pfisterer */ @@ -74,24 +72,18 @@ static void checkRecordPermission() throws SecurityException { * @param properties the properties bundle to store the values of the * properties file */ - @SuppressWarnings("removal") static void loadProperties(final Properties properties) { - final String customFile = AccessController.doPrivileged( - (PrivilegedAction) () -> System.getProperty( - "javax.sound.config.file")); + final String customFile = System.getProperty("javax.sound.config.file"); if (customFile != null) { if (loadPropertiesImpl(properties, customFile)) { return; } } - AccessController.doPrivileged((PrivilegedAction) () -> { - final String home = System.getProperty("java.home"); - if (home == null) { - throw new Error("Can't find java.home ??"); - } - loadPropertiesImpl(properties, home, "conf", "sound.properties"); - return null; - }); + final String home = System.getProperty("java.home"); + if (home == null) { + throw new Error("Can't find java.home ??"); + } + loadPropertiesImpl(properties, home, "conf", "sound.properties"); } private static boolean loadPropertiesImpl(final Properties properties, @@ -124,32 +116,11 @@ static Thread createThread(final Runnable runnable, return thread; } - @SuppressWarnings("removal") static synchronized List getProviders(final Class providerClass) { List p = new ArrayList<>(7); - // ServiceLoader creates "lazy" iterator instance, but it ensures that - // next/hasNext run with permissions that are restricted by whatever - // creates the ServiceLoader instance, so it requires to be called from - // privileged section - final PrivilegedAction> psAction = - new PrivilegedAction>() { - @Override - public Iterator run() { - return ServiceLoader.load(providerClass).iterator(); - } - }; - final Iterator ps = AccessController.doPrivileged(psAction); - - // the iterator's hasNext() method looks through classpath for - // the provider class names, so it requires read permissions - PrivilegedAction hasNextAction = new PrivilegedAction() { - @Override - public Boolean run() { - return ps.hasNext(); - } - }; + final Iterator ps = ServiceLoader.load(providerClass).iterator(); - while (AccessController.doPrivileged(hasNextAction)) { + while (ps.hasNext()) { try { // the iterator's next() method creates instances of the // providers and it should be called in the current security diff --git a/src/java.desktop/share/classes/com/sun/media/sound/Platform.java b/src/java.desktop/share/classes/com/sun/media/sound/Platform.java index 727718c6ca90f..ded8a6496f540 100644 --- a/src/java.desktop/share/classes/com/sun/media/sound/Platform.java +++ b/src/java.desktop/share/classes/com/sun/media/sound/Platform.java @@ -25,8 +25,6 @@ package com.sun.media.sound; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.StringTokenizer; /** @@ -74,15 +72,12 @@ static boolean isBigEndian() { /** * Load the native library or libraries. */ - @SuppressWarnings({"removal", "restricted"}) + @SuppressWarnings("restricted") private static void loadLibraries() { // load the native library isNativeLibLoaded = true; try { - AccessController.doPrivileged((PrivilegedAction) () -> { - System.loadLibrary(libName); - return null; - }); + System.loadLibrary(libName); } catch (Throwable t) { if (Printer.err) Printer.err("Couldn't load library "+libName+": "+t.toString()); isNativeLibLoaded = false; diff --git a/src/java.desktop/share/classes/com/sun/media/sound/Printer.java b/src/java.desktop/share/classes/com/sun/media/sound/Printer.java index c67ca92f57458..40e179b1bd84b 100644 --- a/src/java.desktop/share/classes/com/sun/media/sound/Printer.java +++ b/src/java.desktop/share/classes/com/sun/media/sound/Printer.java @@ -25,7 +25,6 @@ package com.sun.media.sound; -import java.security.AccessController; import sun.security.action.GetPropertyAction; @@ -66,9 +65,7 @@ public static void err(String str) { * Returns {@code true} if the build of the current jdk is "internal". */ private static boolean isBuildInternal() { - @SuppressWarnings("removal") - String javaVersion = AccessController.doPrivileged( - new GetPropertyAction("java.version")); + String javaVersion = System.getProperty("java.version"); return javaVersion != null && javaVersion.contains("internal"); } diff --git a/src/java.desktop/share/classes/com/sun/media/sound/SoftSynthesizer.java b/src/java.desktop/share/classes/com/sun/media/sound/SoftSynthesizer.java index e951a6a657882..4c33416e4709a 100644 --- a/src/java.desktop/share/classes/com/sun/media/sound/SoftSynthesizer.java +++ b/src/java.desktop/share/classes/com/sun/media/sound/SoftSynthesizer.java @@ -36,8 +36,6 @@ import java.io.InputStream; import java.io.OutputStream; import java.lang.ref.WeakReference; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -634,15 +632,19 @@ public boolean remapInstrument(Instrument from, Instrument to) { } } + static interface RunnableAction { + T run(); + } + @Override public Soundbank getDefaultSoundbank() { synchronized (SoftSynthesizer.class) { if (defaultSoundBank != null) return defaultSoundBank; - List> actions = new ArrayList<>(); + List> actions = new ArrayList<>(); - actions.add(new PrivilegedAction() { + actions.add(new RunnableAction() { @Override public InputStream run() { File javahome = new File(System.getProperties() @@ -678,7 +680,7 @@ public InputStream run() { } }); - actions.add(new PrivilegedAction() { + actions.add(new RunnableAction() { @Override public InputStream run() { if (OSInfo.getOSType() == OSInfo.OSType.LINUX) { @@ -712,7 +714,7 @@ public InputStream run() { } }); - actions.add(new PrivilegedAction() { + actions.add(new RunnableAction() { @Override public InputStream run() { if (OSInfo.getOSType() == OSInfo.OSType.WINDOWS) { @@ -729,7 +731,7 @@ public InputStream run() { } }); - actions.add(new PrivilegedAction() { + actions.add(new RunnableAction() { @Override public InputStream run() { /* @@ -749,10 +751,9 @@ public InputStream run() { } }); - for (PrivilegedAction action : actions) { + for (RunnableAction action : actions) { try { - @SuppressWarnings("removal") - InputStream is = AccessController.doPrivileged(action); + InputStream is = action.run(); if(is == null) continue; Soundbank sbk; try (is) { @@ -778,9 +779,8 @@ public InputStream run() { /* * Save generated soundbank to disk for faster future use. */ - @SuppressWarnings("removal") - OutputStream out = AccessController - .doPrivileged((PrivilegedAction) () -> { + OutputStream out = + ((RunnableAction) () -> { try { File userhome = new File(System .getProperty("user.home"), ".gervill"); @@ -798,7 +798,7 @@ public InputStream run() { } catch (final FileNotFoundException ignored) { } return null; - }); + }).run(); if (out != null) { try (out) { ((SF2Soundbank) defaultSoundBank).save(out); @@ -897,28 +897,24 @@ public MidiDevice.Info getDeviceInfo() { return info; } - @SuppressWarnings("removal") private Properties getStoredProperties() { - return AccessController - .doPrivileged((PrivilegedAction) () -> { - Properties p = new Properties(); - String notePath = "/com/sun/media/sound/softsynthesizer"; - try { - Preferences prefroot = Preferences.userRoot(); - if (prefroot.nodeExists(notePath)) { - Preferences prefs = prefroot.node(notePath); - String[] prefs_keys = prefs.keys(); - for (String prefs_key : prefs_keys) { - String val = prefs.get(prefs_key, null); - if (val != null) { - p.setProperty(prefs_key, val); - } - } - } - } catch (final BackingStoreException ignored) { + Properties p = new Properties(); + String notePath = "/com/sun/media/sound/softsynthesizer"; + try { + Preferences prefroot = Preferences.userRoot(); + if (prefroot.nodeExists(notePath)) { + Preferences prefs = prefroot.node(notePath); + String[] prefs_keys = prefs.keys(); + for (String prefs_key : prefs_keys) { + String val = prefs.get(prefs_key, null); + if (val != null) { + p.setProperty(prefs_key, val); } - return p; - }); + } + } + } catch (final BackingStoreException ignored) { + } + return p; } @Override diff --git a/src/java.desktop/share/classes/javax/imageio/ImageIO.java b/src/java.desktop/share/classes/javax/imageio/ImageIO.java index b11641c82caf3..316a74a22ea1b 100644 --- a/src/java.desktop/share/classes/javax/imageio/ImageIO.java +++ b/src/java.desktop/share/classes/javax/imageio/ImageIO.java @@ -165,10 +165,8 @@ private static synchronized CacheInfo getCacheInfo() { * Returns the default temporary (cache) directory as defined by the * java.io.tmpdir system property. */ - @SuppressWarnings("removal") private static String getTempDir() { - GetPropertyAction a = new GetPropertyAction("java.io.tmpdir"); - return AccessController.doPrivileged(a); + return System.getProperty("java.io.tmpdir"); } /** diff --git a/src/java.desktop/share/classes/javax/imageio/metadata/IIOMetadata.java b/src/java.desktop/share/classes/javax/imageio/metadata/IIOMetadata.java index 3954f886f47f7..b94d6a85a0267 100644 --- a/src/java.desktop/share/classes/javax/imageio/metadata/IIOMetadata.java +++ b/src/java.desktop/share/classes/javax/imageio/metadata/IIOMetadata.java @@ -28,8 +28,6 @@ import org.w3c.dom.Node; import java.lang.reflect.Method; -import java.security.AccessController; -import java.security.PrivilegedAction; /** * An abstract class to be extended by objects that represent metadata @@ -398,12 +396,9 @@ public IIOMetadataFormat getMetadataFormat(String formatName) { throw new IllegalArgumentException("Unsupported format name"); } try { - final String className = formatClassName; // Try to load from the module of the IIOMetadata implementation // for this plugin since the IIOMetadataImpl is part of the plugin - PrivilegedAction> pa = () -> { return getMetadataFormatClass(className); }; - @SuppressWarnings("removal") - Class cls = AccessController.doPrivileged(pa); + Class cls = getMetadataFormatClass(formatClassName); Method meth = cls.getMethod("getInstance"); return (IIOMetadataFormat) meth.invoke(null); } catch (Exception e) { diff --git a/src/java.desktop/share/classes/javax/imageio/spi/IIORegistry.java b/src/java.desktop/share/classes/javax/imageio/spi/IIORegistry.java index b80e6370293d8..1ea7146ae4ae3 100644 --- a/src/java.desktop/share/classes/javax/imageio/spi/IIORegistry.java +++ b/src/java.desktop/share/classes/javax/imageio/spi/IIORegistry.java @@ -25,8 +25,6 @@ package javax.imageio.spi; -import java.security.PrivilegedAction; -import java.security.AccessController; import java.util.Iterator; import com.sun.imageio.spi.FileImageInputStreamSpi; import com.sun.imageio.spi.FileImageOutputStreamSpi; @@ -197,30 +195,14 @@ public void registerApplicationClasspathSpis() { } } - @SuppressWarnings("removal") private void registerInstalledProviders() { - /* - We need to load installed providers - in the privileged mode in order to - be able read corresponding jar files even if - file read capability is restricted (like the - applet context case). - */ - PrivilegedAction doRegistration = - new PrivilegedAction() { - public Object run() { - Iterator> categories = getCategories(); - while (categories.hasNext()) { - @SuppressWarnings("unchecked") - Class c = (Class)categories.next(); - for (IIOServiceProvider p : ServiceLoader.loadInstalled(c)) { - registerServiceProvider(p); - } - } - return this; - } - }; - - AccessController.doPrivileged(doRegistration); + Iterator> categories = getCategories(); + while (categories.hasNext()) { + @SuppressWarnings("unchecked") + Class c = (Class)categories.next(); + for (IIOServiceProvider p : ServiceLoader.loadInstalled(c)) { + registerServiceProvider(p); + } + } } } diff --git a/src/java.desktop/share/classes/javax/imageio/spi/ImageReaderWriterSpi.java b/src/java.desktop/share/classes/javax/imageio/spi/ImageReaderWriterSpi.java index 7abefdd9431a4..f74415a8a38e8 100644 --- a/src/java.desktop/share/classes/javax/imageio/spi/ImageReaderWriterSpi.java +++ b/src/java.desktop/share/classes/javax/imageio/spi/ImageReaderWriterSpi.java @@ -26,8 +26,6 @@ package javax.imageio.spi; import java.lang.reflect.Method; -import java.security.AccessController; -import java.security.PrivilegedAction; import javax.imageio.metadata.IIOMetadata; import javax.imageio.metadata.IIOMetadataFormat; import javax.imageio.metadata.IIOMetadataFormatImpl; @@ -584,10 +582,7 @@ private IIOMetadataFormat getMetadataFormat(String formatName, } try { // Try to load from the same location as the module of the SPI - final String className = formatClassName; - PrivilegedAction> pa = () -> { return getMetadataFormatClass(className); }; - @SuppressWarnings("removal") - Class cls = AccessController.doPrivileged(pa); + Class cls = getMetadataFormatClass(formatClassName); Method meth = cls.getMethod("getInstance"); return (IIOMetadataFormat) meth.invoke(null); } catch (Exception e) { diff --git a/src/java.desktop/share/classes/javax/imageio/spi/ServiceRegistry.java b/src/java.desktop/share/classes/javax/imageio/spi/ServiceRegistry.java index 3e0bc06b36165..0ba532b0b8363 100644 --- a/src/java.desktop/share/classes/javax/imageio/spi/ServiceRegistry.java +++ b/src/java.desktop/share/classes/javax/imageio/spi/ServiceRegistry.java @@ -25,9 +25,6 @@ package javax.imageio.spi; -import java.security.AccessControlContext; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; @@ -731,8 +728,6 @@ class SubRegistry { // No way to express heterogeneous map, we want // Map, T>, where T is ? final Map, Object> map = new HashMap<>(); - @SuppressWarnings("removal") - final Map, AccessControlContext> accMap = new HashMap<>(); public SubRegistry(ServiceRegistry registry, Class category) { this.registry = registry; @@ -748,7 +743,6 @@ public synchronized boolean registerServiceProvider(Object provider) { deregisterServiceProvider(oprovider); } map.put(provider.getClass(), provider); - accMap.put(provider.getClass(), AccessController.getContext()); poset.add(provider); if (provider instanceof RegisterableService) { RegisterableService rs = (RegisterableService)provider; @@ -773,7 +767,6 @@ public synchronized boolean deregisterServiceProvider(Object provider) { if (provider == oprovider) { map.remove(provider.getClass()); - accMap.remove(provider.getClass()); poset.remove(provider); if (provider instanceof RegisterableService) { RegisterableService rs = (RegisterableService)provider; @@ -815,26 +808,17 @@ public synchronized boolean unsetOrdering(Object firstProvider, return (T)map.get(providerClass); } - @SuppressWarnings("removal") public synchronized void clear() { Iterator iter = map.values().iterator(); while (iter.hasNext()) { Object provider = iter.next(); iter.remove(); - if (provider instanceof RegisterableService) { - RegisterableService rs = (RegisterableService)provider; - AccessControlContext acc = accMap.get(provider.getClass()); - if (acc != null || System.getSecurityManager() == null) { - AccessController.doPrivileged((PrivilegedAction) () -> { - rs.onDeregistration(registry, category); - return null; - }, acc); - } + if (provider instanceof RegisterableService rs) { + rs.onDeregistration(registry, category); } } poset.clear(); - accMap.clear(); } @SuppressWarnings("removal") diff --git a/src/java.desktop/share/classes/javax/print/DocFlavor.java b/src/java.desktop/share/classes/javax/print/DocFlavor.java index 448cc78d9e1d9..9db970cc779fe 100644 --- a/src/java.desktop/share/classes/javax/print/DocFlavor.java +++ b/src/java.desktop/share/classes/javax/print/DocFlavor.java @@ -410,10 +410,7 @@ public class DocFlavor implements Serializable, Cloneable { * @spec https://www.rfc-editor.org/info/rfc2278 * RFC 2278: IANA Charset Registration Procedures */ - @SuppressWarnings("removal") - public static final String hostEncoding = - java.security.AccessController.doPrivileged( - new sun.security.action.GetPropertyAction("file.encoding")); + public static final String hostEncoding = System.getProperty("file.encoding"); /** * MIME type. diff --git a/src/java.desktop/share/classes/javax/print/PrintServiceLookup.java b/src/java.desktop/share/classes/javax/print/PrintServiceLookup.java index 2931a1cbae0c7..29c7b420f7c51 100644 --- a/src/java.desktop/share/classes/javax/print/PrintServiceLookup.java +++ b/src/java.desktop/share/classes/javax/print/PrintServiceLookup.java @@ -335,7 +335,6 @@ public abstract PrintService[] getPrintServices(DocFlavor flavor, * * @return all lookup services for this environment */ - @SuppressWarnings("removal") private static ArrayList getAllLookupServices() { synchronized (PrintServiceLookup.class) { ArrayList listOfLookupServices = getListOfLookupServices(); @@ -344,32 +343,11 @@ private static ArrayList getAllLookupServices() { } else { listOfLookupServices = initListOfLookupServices(); } - try { - java.security.AccessController.doPrivileged( - new java.security.PrivilegedExceptionAction() { - public Object run() { - Iterator iterator = - ServiceLoader.load(PrintServiceLookup.class). - iterator(); - ArrayList los = getListOfLookupServices(); - while (iterator.hasNext()) { - try { - los.add(iterator.next()); - } catch (ServiceConfigurationError err) { - /* In the applet case, we continue */ - if (System.getSecurityManager() != null) { - err.printStackTrace(); - } else { - throw err; - } - } - } - return null; - } - }); - } catch (java.security.PrivilegedActionException e) { + Iterator iterator = ServiceLoader.load(PrintServiceLookup.class).iterator(); + ArrayList los = getListOfLookupServices(); + while (iterator.hasNext()) { + los.add(iterator.next()); } - return listOfLookupServices; } } diff --git a/src/java.desktop/share/classes/javax/print/StreamPrintServiceFactory.java b/src/java.desktop/share/classes/javax/print/StreamPrintServiceFactory.java index 29033cb7147c4..5247d4ef86182 100644 --- a/src/java.desktop/share/classes/javax/print/StreamPrintServiceFactory.java +++ b/src/java.desktop/share/classes/javax/print/StreamPrintServiceFactory.java @@ -183,43 +183,23 @@ private static ArrayList initListOfFactories() { * * @return all factories */ - @SuppressWarnings("removal") private static ArrayList getAllFactories() { synchronized (StreamPrintServiceFactory.class) { - ArrayList listOfFactories = getListOfFactories(); - if (listOfFactories != null) { - return listOfFactories; - } else { - listOfFactories = initListOfFactories(); - } + ArrayList listOfFactories = getListOfFactories(); + if (listOfFactories != null) { + return listOfFactories; + } else { + listOfFactories = initListOfFactories(); + } - try { - java.security.AccessController.doPrivileged( - new java.security.PrivilegedExceptionAction() { - public Object run() { - Iterator iterator = - ServiceLoader.load - (StreamPrintServiceFactory.class).iterator(); - ArrayList lof = getListOfFactories(); - while (iterator.hasNext()) { - try { - lof.add(iterator.next()); - } catch (ServiceConfigurationError err) { - /* In the applet case, we continue */ - if (System.getSecurityManager() != null) { - err.printStackTrace(); - } else { - throw err; - } - } - } - return null; - } - }); - } catch (java.security.PrivilegedActionException e) { - } - return listOfFactories; + Iterator iterator = + ServiceLoader.load(StreamPrintServiceFactory.class).iterator(); + ArrayList lof = getListOfFactories(); + while (iterator.hasNext()) { + lof.add(iterator.next()); + } + return listOfFactories; } } From da2d7a09f92df547661587348f768f69f0e5a23b Mon Sep 17 00:00:00 2001 From: "Dr Heinz M. Kabutz" Date: Wed, 20 Nov 2024 20:01:37 +0000 Subject: [PATCH 54/74] 8344595: State transitions in internal VirtualThread comment needs to be updated Reviewed-by: alanb --- .../share/classes/java/lang/VirtualThread.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/java.base/share/classes/java/lang/VirtualThread.java b/src/java.base/share/classes/java/lang/VirtualThread.java index 1bf4367bed4c7..1f8e1941c1d90 100644 --- a/src/java.base/share/classes/java/lang/VirtualThread.java +++ b/src/java.base/share/classes/java/lang/VirtualThread.java @@ -108,14 +108,14 @@ final class VirtualThread extends BaseVirtualThread { * UNBLOCKED -> RUNNING // continue execution after blocked on monitor enter * * RUNNING -> WAITING // transitional state during wait on monitor - * WAITING -> WAITED // waiting on monitor - * WAITED -> BLOCKED // notified, waiting to be unblocked by monitor owner - * WAITED -> UNBLOCKED // timed-out/interrupted + * WAITING -> WAIT // waiting on monitor + * WAIT -> BLOCKED // notified, waiting to be unblocked by monitor owner + * WAIT -> UNBLOCKED // timed-out/interrupted * * RUNNING -> TIMED_WAITING // transition state during timed-waiting on monitor - * TIMED_WAITING -> TIMED_WAITED // timed-waiting on monitor - * TIMED_WAITED -> BLOCKED // notified, waiting to be unblocked by monitor owner - * TIMED_WAITED -> UNBLOCKED // timed-out/interrupted + * TIMED_WAITING -> TIMED_WAIT // timed-waiting on monitor + * TIMED_WAIT -> BLOCKED // notified, waiting to be unblocked by monitor owner + * TIMED_WAIT -> UNBLOCKED // timed-out/interrupted * * RUNNING -> YIELDING // Thread.yield * YIELDING -> YIELDED // cont.yield successful, may be scheduled to continue From b9bf447209db5d7f6bb16a0310421dbe4170500c Mon Sep 17 00:00:00 2001 From: Harshitha Onkar Date: Wed, 20 Nov 2024 20:28:12 +0000 Subject: [PATCH 55/74] 8344057: Remove doPrivileged calls from unix platform sources in the java.desktop module Reviewed-by: prr --- .../classes/sun/awt/PlatformGraphicsInfo.java | 32 ++- .../unix/classes/sun/awt/UNIXToolkit.java | 40 +--- .../unix/classes/sun/awt/X11/InfoWindow.java | 14 +- .../unix/classes/sun/awt/X11/Native.java | 10 +- .../unix/classes/sun/awt/X11/XClipboard.java | 8 +- .../classes/sun/awt/X11/XEmbedCanvasPeer.java | 6 +- .../sun/awt/X11/XErrorHandlerUtil.java | 6 +- .../classes/sun/awt/X11/XFileDialogPeer.java | 11 +- .../unix/classes/sun/awt/X11/XRobotPeer.java | 14 +- .../classes/sun/awt/X11/XTaskbarPeer.java | 12 +- .../unix/classes/sun/awt/X11/XToolkit.java | 83 +++----- .../classes/sun/awt/X11/XTrayIconPeer.java | 10 +- .../unix/classes/sun/awt/X11/XlibWrapper.java | 11 +- .../classes/sun/awt/X11GraphicsDevice.java | 31 ++- .../sun/awt/X11GraphicsEnvironment.java | 183 ++++++++---------- .../sun/awt/screencast/ScreencastHelper.java | 11 +- .../sun/awt/screencast/TokenStorage.java | 56 ++---- .../classes/sun/font/FcFontConfiguration.java | 5 - .../sun/java2d/x11/X11SurfaceData.java | 8 +- .../sun/java2d/xr/XRCompositeManager.java | 10 +- .../unix/classes/sun/print/CUPSPrinter.java | 49 ++--- .../classes/sun/print/IPPPrintService.java | 20 +- .../sun/print/PrintServiceLookupProvider.java | 112 +++++------ .../unix/classes/sun/print/UnixPrintJob.java | 15 +- .../classes/sun/print/UnixPrintService.java | 4 +- 25 files changed, 260 insertions(+), 501 deletions(-) diff --git a/src/java.desktop/unix/classes/sun/awt/PlatformGraphicsInfo.java b/src/java.desktop/unix/classes/sun/awt/PlatformGraphicsInfo.java index 6640042259ec5..9ab68a4ff4400 100644 --- a/src/java.desktop/unix/classes/sun/awt/PlatformGraphicsInfo.java +++ b/src/java.desktop/unix/classes/sun/awt/PlatformGraphicsInfo.java @@ -28,8 +28,6 @@ import java.io.File; import java.awt.GraphicsEnvironment; import java.awt.Toolkit; -import java.security.AccessController; -import java.security.PrivilegedAction; public class PlatformGraphicsInfo { @@ -47,14 +45,10 @@ public static Toolkit createToolkit() { * headless mode, in the case the application did not specify * a value for the java.awt.headless system property. */ - @SuppressWarnings("removal") public static boolean getDefaultHeadlessProperty() { - boolean noDisplay = - AccessController.doPrivileged((PrivilegedAction) () -> { + final String display = System.getenv("DISPLAY"); + boolean noDisplay = (display == null || display.trim().isEmpty()); - final String display = System.getenv("DISPLAY"); - return display == null || display.trim().isEmpty(); - }); if (noDisplay) { return true; } @@ -67,18 +61,16 @@ public static boolean getDefaultHeadlessProperty() { * code is also set up as headless from the start - it is not so easy * to try headful and then unwind that and then retry as headless. */ - boolean headless = - AccessController.doPrivileged((PrivilegedAction) () -> { - String[] libDirs = System.getProperty("sun.boot.library.path", "").split(":"); - for (String libDir : libDirs) { - File headlessLib = new File(libDir, "libawt_headless.so"); - File xawtLib = new File(libDir, "libawt_xawt.so"); - if (headlessLib.exists() && !xawtLib.exists()) { - return true; - } - } - return false; - }); + boolean headless = false; + String[] libDirs = System.getProperty("sun.boot.library.path", "").split(":"); + for (String libDir : libDirs) { + File headlessLib = new File(libDir, "libawt_headless.so"); + File xawtLib = new File(libDir, "libawt_xawt.so"); + if (headlessLib.exists() && !xawtLib.exists()) { + headless = true; + break; + } + } return headless; } diff --git a/src/java.desktop/unix/classes/sun/awt/UNIXToolkit.java b/src/java.desktop/unix/classes/sun/awt/UNIXToolkit.java index d509fe802b028..8e22441442780 100644 --- a/src/java.desktop/unix/classes/sun/awt/UNIXToolkit.java +++ b/src/java.desktop/unix/classes/sun/awt/UNIXToolkit.java @@ -105,9 +105,7 @@ public int getNumber() { private BufferedImage tmpImage = null; public static int getDatatransferTimeout() { - @SuppressWarnings("removal") - Integer dt = AccessController.doPrivileged( - new GetIntegerAction("sun.awt.datatransfer.timeout")); + Integer dt = Integer.getInteger("sun.awt.datatransfer.timeout"); if (dt == null || dt <= 0) { return DEFAULT_DATATRANSFER_TIMEOUT; } else { @@ -118,18 +116,12 @@ public static int getDatatransferTimeout() { @Override public String getDesktop() { String gnome = "gnome"; - @SuppressWarnings("removal") - String gsi = AccessController.doPrivileged( - (PrivilegedAction) () - -> System.getenv("GNOME_DESKTOP_SESSION_ID")); + String gsi = System.getenv("GNOME_DESKTOP_SESSION_ID"); if (gsi != null) { return gnome; } - @SuppressWarnings("removal") - String desktop = AccessController.doPrivileged( - (PrivilegedAction) () - -> System.getenv("XDG_CURRENT_DESKTOP")); + String desktop = System.getenv("XDG_CURRENT_DESKTOP"); return (desktop != null && desktop.toLowerCase().contains(gnome)) ? gnome : null; } @@ -252,11 +244,7 @@ public boolean shouldDisableSystemTray() { result = shouldDisableSystemTray; if (result == null) { if ("gnome".equals(getDesktop())) { - @SuppressWarnings("removal") - Integer gnomeShellMajorVersion = - AccessController - .doPrivileged((PrivilegedAction) - this::getGnomeShellMajorVersion); + Integer gnomeShellMajorVersion = getGnomeShellMajorVersion(); if (gnomeShellMajorVersion == null || gnomeShellMajorVersion < 45) { @@ -486,9 +474,7 @@ public boolean checkGtkVersion(int major, int minor, int micro) { } public static GtkVersions getEnabledGtkVersion() { - @SuppressWarnings("removal") - String version = AccessController.doPrivileged( - new GetPropertyAction("jdk.gtk.version")); + String version = System.getProperty("jdk.gtk.version"); if ("3".equals(version)) { return GtkVersions.GTK3; } @@ -499,32 +485,22 @@ public static GtkVersions getGtkVersion() { return GtkVersions.getVersion(get_gtk_version()); } - @SuppressWarnings("removal") public static boolean isGtkVerbose() { - return AccessController.doPrivileged((PrivilegedAction)() - -> Boolean.getBoolean("jdk.gtk.verbose")); + return Boolean.getBoolean("jdk.gtk.verbose"); } private static volatile Boolean isOnWayland = null; - @SuppressWarnings("removal") public static boolean isOnWayland() { Boolean result = isOnWayland; if (result == null) { synchronized (GTK_LOCK) { result = isOnWayland; if (result == null) { + final String display = System.getenv("WAYLAND_DISPLAY"); isOnWayland = result - = AccessController.doPrivileged( - (PrivilegedAction) () -> { - final String display = - System.getenv("WAYLAND_DISPLAY"); - - return display != null - && !display.trim().isEmpty(); - } - ); + = (display != null && !display.trim().isEmpty()); } } } diff --git a/src/java.desktop/unix/classes/sun/awt/X11/InfoWindow.java b/src/java.desktop/unix/classes/sun/awt/X11/InfoWindow.java index d86d49290a43a..641e2f86c023d 100644 --- a/src/java.desktop/unix/classes/sun/awt/X11/InfoWindow.java +++ b/src/java.desktop/unix/classes/sun/awt/X11/InfoWindow.java @@ -47,8 +47,6 @@ import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.text.BreakIterator; import java.util.concurrent.ArrayBlockingQueue; @@ -227,16 +225,8 @@ public void run() { textLabel.setText(tooltipString); } - @SuppressWarnings("removal") - Point pointer = AccessController.doPrivileged( - new PrivilegedAction() { - public Point run() { - if (!isPointerOverTrayIcon(liveArguments.getBounds())) { - return null; - } - return MouseInfo.getPointerInfo().getLocation(); - } - }); + Point pointer = !isPointerOverTrayIcon(liveArguments.getBounds()) + ? null : MouseInfo.getPointerInfo().getLocation(); if (pointer == null) { return; } diff --git a/src/java.desktop/unix/classes/sun/awt/X11/Native.java b/src/java.desktop/unix/classes/sun/awt/X11/Native.java index 744e665baaa94..773668ff53aee 100644 --- a/src/java.desktop/unix/classes/sun/awt/X11/Native.java +++ b/src/java.desktop/unix/classes/sun/awt/X11/Native.java @@ -27,8 +27,6 @@ import jdk.internal.misc.Unsafe; import java.util.Vector; -import java.security.AccessController; -import java.security.PrivilegedAction; /** * This class contains the collection of utility functions to help work with @@ -43,13 +41,7 @@ class Native { static int dataModel; static { - @SuppressWarnings("removal") - String dataModelProp = AccessController.doPrivileged( - new PrivilegedAction() { - public String run() { - return System.getProperty("sun.arch.data.model"); - } - }); + String dataModelProp = System.getProperty("sun.arch.data.model"); try { dataModel = Integer.parseInt(dataModelProp); } catch (Exception e) { diff --git a/src/java.desktop/unix/classes/sun/awt/X11/XClipboard.java b/src/java.desktop/unix/classes/sun/awt/X11/XClipboard.java index a12dddcb7dff7..3a36c3195a85b 100644 --- a/src/java.desktop/unix/classes/sun/awt/X11/XClipboard.java +++ b/src/java.desktop/unix/classes/sun/awt/X11/XClipboard.java @@ -29,14 +29,12 @@ import java.awt.datatransfer.DataFlavor; import java.util.SortedMap; import java.io.IOException; -import java.security.AccessController; import java.util.HashMap; import java.util.Map; import sun.awt.UNIXToolkit; import sun.awt.datatransfer.DataTransferer; import sun.awt.datatransfer.SunClipboard; import sun.awt.datatransfer.ClipboardTransferable; -import sun.security.action.GetIntegerAction; /** * A class which interfaces with the X11 selection service in order to support @@ -129,13 +127,11 @@ private void checkChangeHere(Transferable contents) { } } - @SuppressWarnings("removal") private static int getPollInterval() { synchronized (XClipboard.classLock) { if (pollInterval <= 0) { - pollInterval = AccessController.doPrivileged( - new GetIntegerAction("awt.datatransfer.clipboard.poll.interval", - defaultPollInterval)); + pollInterval = Integer.getInteger("awt.datatransfer.clipboard.poll.interval" + , defaultPollInterval); if (pollInterval <= 0) { pollInterval = defaultPollInterval; } diff --git a/src/java.desktop/unix/classes/sun/awt/X11/XEmbedCanvasPeer.java b/src/java.desktop/unix/classes/sun/awt/X11/XEmbedCanvasPeer.java index 4317136816c2a..57e06cf94de2b 100644 --- a/src/java.desktop/unix/classes/sun/awt/X11/XEmbedCanvasPeer.java +++ b/src/java.desktop/unix/classes/sun/awt/X11/XEmbedCanvasPeer.java @@ -35,9 +35,6 @@ import java.util.*; import static sun.awt.X11.XEmbedHelper.*; -import java.security.AccessController; -import sun.security.action.GetBooleanAction; - public class XEmbedCanvasPeer extends XCanvasPeer implements WindowFocusListener, KeyEventPostProcessor, ModalityListener, WindowIDProvider { private static final PlatformLogger xembedLog = PlatformLogger.getLogger("sun.awt.X11.xembed.XEmbedCanvasPeer"); @@ -439,12 +436,11 @@ void canvasFocusGained(FocusEvent e) { } } - @SuppressWarnings("removal") void canvasFocusLost(FocusEvent e) { if (isXEmbedActive() && !e.isTemporary()) { xembedLog.fine("Forwarding FOCUS_LOST"); int num = 0; - if (AccessController.doPrivileged(new GetBooleanAction("sun.awt.xembed.testing"))) { + if (Boolean.getBoolean("sun.awt.xembed.testing")) { Component opp = e.getOppositeComponent(); try { num = Integer.parseInt(opp.getName()); diff --git a/src/java.desktop/unix/classes/sun/awt/X11/XErrorHandlerUtil.java b/src/java.desktop/unix/classes/sun/awt/X11/XErrorHandlerUtil.java index 9d43399e23c96..1dfaa4b8d4dfe 100644 --- a/src/java.desktop/unix/classes/sun/awt/X11/XErrorHandlerUtil.java +++ b/src/java.desktop/unix/classes/sun/awt/X11/XErrorHandlerUtil.java @@ -24,9 +24,7 @@ */ package sun.awt.X11; -import java.security.AccessController; import sun.awt.SunToolkit; -import sun.security.action.GetBooleanAction; import sun.util.logging.PlatformLogger; /** @@ -59,9 +57,7 @@ public final class XErrorHandlerUtil { /** * Value of sun.awt.noisyerrorhandler system property. */ - @SuppressWarnings("removal") - private static boolean noisyAwtHandler = AccessController.doPrivileged( - new GetBooleanAction("sun.awt.noisyerrorhandler")); + private static boolean noisyAwtHandler = Boolean.getBoolean("sun.awt.noisyerrorhandler"); /** * The flag indicating that {@code init} was called already. diff --git a/src/java.desktop/unix/classes/sun/awt/X11/XFileDialogPeer.java b/src/java.desktop/unix/classes/sun/awt/X11/XFileDialogPeer.java index f11f11ba53e0f..596bc493f0040 100644 --- a/src/java.desktop/unix/classes/sun/awt/X11/XFileDialogPeer.java +++ b/src/java.desktop/unix/classes/sun/awt/X11/XFileDialogPeer.java @@ -32,8 +32,6 @@ import java.io.*; import java.util.Locale; import java.util.Arrays; -import java.security.AccessController; -import java.security.PrivilegedAction; import sun.awt.AWTAccessor.ComponentAccessor; import sun.util.logging.PlatformLogger; @@ -139,7 +137,7 @@ void installStrings() { this.target = target; } - @SuppressWarnings({"removal","deprecation"}) + @SuppressWarnings("deprecation") private void init(FileDialog target) { fileDialog = target; //new Dialog(target, target.getTitle(), false); this.title = target.getTitle(); @@ -151,12 +149,7 @@ private void init(FileDialog target) { savedDir = target.getDirectory(); // Shouldn't save 'user.dir' to 'savedDir' // since getDirectory() will be incorrect after handleCancel - userDir = AccessController.doPrivileged( - new PrivilegedAction() { - public String run() { - return System.getProperty("user.dir"); - } - }); + userDir = System.getProperty("user.dir"); installStrings(); gbl = new GridBagLayout(); diff --git a/src/java.desktop/unix/classes/sun/awt/X11/XRobotPeer.java b/src/java.desktop/unix/classes/sun/awt/X11/XRobotPeer.java index 6d155c0bcc8b7..010c5aeff5ae3 100644 --- a/src/java.desktop/unix/classes/sun/awt/X11/XRobotPeer.java +++ b/src/java.desktop/unix/classes/sun/awt/X11/XRobotPeer.java @@ -28,7 +28,6 @@ import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.peer.RobotPeer; -import java.security.AccessController; import sun.awt.AWTAccessor; import sun.awt.SunToolkit; @@ -36,9 +35,7 @@ import sun.awt.X11GraphicsConfig; import sun.awt.X11GraphicsDevice; import sun.awt.screencast.ScreencastHelper; -import sun.security.action.GetPropertyAction; -@SuppressWarnings("removal") final class XRobotPeer implements RobotPeer { private static final boolean tryGtk; @@ -50,10 +47,8 @@ final class XRobotPeer implements RobotPeer { loadNativeLibraries(); tryGtk = Boolean.parseBoolean( - AccessController.doPrivileged( - new GetPropertyAction("awt.robot.gtk", - "true") - )); + System.getProperty("awt.robot.gtk", "true") + ); boolean isOnWayland = false; @@ -61,13 +56,12 @@ final class XRobotPeer implements RobotPeer { isOnWayland = sunToolkit.isRunningOnWayland(); } - screenshotMethod = AccessController.doPrivileged( - new GetPropertyAction( + screenshotMethod = System.getProperty( "awt.robot.screenshotMethod", isOnWayland ? METHOD_SCREENCAST : METHOD_X11 - )); + ); } private static volatile boolean useGtk; diff --git a/src/java.desktop/unix/classes/sun/awt/X11/XTaskbarPeer.java b/src/java.desktop/unix/classes/sun/awt/X11/XTaskbarPeer.java index 33bebe77de7d4..73668bf591ce9 100644 --- a/src/java.desktop/unix/classes/sun/awt/X11/XTaskbarPeer.java +++ b/src/java.desktop/unix/classes/sun/awt/X11/XTaskbarPeer.java @@ -31,9 +31,6 @@ import java.awt.event.ActionEvent; import sun.awt.UNIXToolkit; -import java.security.AccessController; -import java.security.PrivilegedAction; -import sun.security.action.GetPropertyAction; final class XTaskbarPeer implements TaskbarPeer { @@ -44,10 +41,7 @@ final class XTaskbarPeer implements TaskbarPeer { private static boolean isUnity; static { - @SuppressWarnings("removal") - String de = AccessController.doPrivileged( - (PrivilegedAction) () - -> System.getenv("XDG_CURRENT_DESKTOP")); + String de = System.getenv("XDG_CURRENT_DESKTOP"); isUnity = "Unity".equals(de); } @@ -55,9 +49,7 @@ private static void initWithLock() { XToolkit.awtLock(); try { if (!initExecuted) { - @SuppressWarnings("removal") - String dname = AccessController.doPrivileged( - new GetPropertyAction("java.desktop.appName", "")); + String dname = System.getProperty("java.desktop.appName", ""); nativeLibraryLoaded = init(dname, UNIXToolkit.getEnabledGtkVersion().ordinal(), UNIXToolkit.isGtkVerbose()); diff --git a/src/java.desktop/unix/classes/sun/awt/X11/XToolkit.java b/src/java.desktop/unix/classes/sun/awt/X11/XToolkit.java index 1b4f45b55f1f4..920e1235fca7d 100644 --- a/src/java.desktop/unix/classes/sun/awt/X11/XToolkit.java +++ b/src/java.desktop/unix/classes/sun/awt/X11/XToolkit.java @@ -111,8 +111,6 @@ import java.awt.peer.TrayIconPeer; import java.awt.peer.WindowPeer; import java.beans.PropertyChangeListener; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; @@ -147,8 +145,6 @@ import sun.font.FontConfigManager; import sun.java2d.SunGraphicsEnvironment; import sun.print.PrintJob2D; -import sun.security.action.GetBooleanAction; -import sun.security.action.GetPropertyAction; import sun.util.logging.PlatformLogger; import static sun.awt.X11.XlibUtil.scaleDown; @@ -246,9 +242,7 @@ static boolean isToolkitThread() { static void initSecurityWarning() { // Enable warning only for internal builds - @SuppressWarnings("removal") - String runtime = AccessController.doPrivileged( - new GetPropertyAction("java.runtime.version")); + String runtime = System.getProperty("java.runtime.version"); securityWarningEnabled = (runtime != null && runtime.contains("internal")); } @@ -326,7 +320,6 @@ public static long getDefaultRootWindow() { } } - @SuppressWarnings("removal") void init() { awtLock(); try { @@ -339,13 +332,10 @@ void init() { arrowCursor = XlibWrapper.XCreateFontCursor(XToolkit.getDisplay(), XCursorFontConstants.XC_arrow); final String extraButtons = "sun.awt.enableExtraMouseButtons"; - AccessController.doPrivileged((PrivilegedAction) () -> { - areExtraMouseButtonsEnabled = - Boolean.parseBoolean(System.getProperty(extraButtons, "true")); - //set system property if not yet assigned - System.setProperty(extraButtons, ""+areExtraMouseButtonsEnabled); - return null; - }); + areExtraMouseButtonsEnabled = + Boolean.parseBoolean(System.getProperty(extraButtons, "true")); + //set system property if not yet assigned + System.setProperty(extraButtons, "" + areExtraMouseButtonsEnabled); // Detect display mode changes XlibWrapper.XSelectInput(XToolkit.getDisplay(), XToolkit.getDefaultRootWindow(), XConstants.StructureNotifyMask); XToolkit.addEventDispatcher(XToolkit.getDefaultRootWindow(), new XEventDispatcher() { @@ -370,28 +360,24 @@ public void dispatchEvent(XEvent ev) { } finally { awtUnlock(); } - PrivilegedAction a = () -> { - Runnable r = () -> { - XSystemTrayPeer peer = XSystemTrayPeer.getPeerInstance(); - if (peer != null) { - peer.dispose(); - } - if (xs != null) { - ((XAWTXSettings)xs).dispose(); - } - freeXKB(); - if (log.isLoggable(PlatformLogger.Level.FINE)) { - dumpPeers(); - } - }; - String name = "XToolkt-Shutdown-Thread"; - Thread shutdownThread = new Thread( - ThreadGroupUtils.getRootThreadGroup(), r, name, 0, false); - shutdownThread.setContextClassLoader(null); - Runtime.getRuntime().addShutdownHook(shutdownThread); - return null; + Runnable r = () -> { + XSystemTrayPeer peer = XSystemTrayPeer.getPeerInstance(); + if (peer != null) { + peer.dispose(); + } + if (xs != null) { + ((XAWTXSettings)xs).dispose(); + } + freeXKB(); + if (log.isLoggable(PlatformLogger.Level.FINE)) { + dumpPeers(); + } }; - AccessController.doPrivileged(a); + String name = "XToolkt-Shutdown-Thread"; + Thread shutdownThread = new Thread( + ThreadGroupUtils.getRootThreadGroup(), r, name, 0, false); + shutdownThread.setContextClassLoader(null); + Runtime.getRuntime().addShutdownHook(shutdownThread); } static String getCorrectXIDString(String val) { @@ -409,7 +395,6 @@ static String getAWTAppClassName() { return awtAppClassName; } - @SuppressWarnings("removal") public XToolkit() { super(); if (PerformanceLogger.loggingEnabled()) { @@ -432,16 +417,13 @@ public XToolkit() { init(); XWM.init(); - toolkitThread = AccessController.doPrivileged((PrivilegedAction) () -> { - String name = "AWT-XAWT"; - Thread thread = new Thread( + String name = "AWT-XAWT"; + toolkitThread = new Thread( ThreadGroupUtils.getRootThreadGroup(), this, name, 0, false); - thread.setContextClassLoader(null); - thread.setPriority(Thread.NORM_PRIORITY + 1); - thread.setDaemon(true); - return thread; - }); + toolkitThread.setContextClassLoader(null); + toolkitThread.setPriority(Thread.NORM_PRIORITY + 1); + toolkitThread.setDaemon(true); toolkitThread.start(); } } @@ -1120,11 +1102,9 @@ public DialogPeer createDialog(Dialog target) { * Returns the value of "sun.awt.disableGtkFileDialogs" property. Default * value is {@code false}. */ - @SuppressWarnings("removal") public static synchronized boolean getSunAwtDisableGtkFileDialogs() { if (sunAwtDisableGtkFileDialogs == null) { - sunAwtDisableGtkFileDialogs = AccessController.doPrivileged( - new GetBooleanAction("sun.awt.disableGtkFileDialogs")); + sunAwtDisableGtkFileDialogs = Boolean.getBoolean("sun.awt.disableGtkFileDialogs"); } return sunAwtDisableGtkFileDialogs.booleanValue(); } @@ -2139,9 +2119,7 @@ static int getBackingStoreType() { } private static void setBackingStoreType() { - @SuppressWarnings("removal") - String prop = AccessController.doPrivileged( - new sun.security.action.GetPropertyAction("sun.awt.backingStore")); + String prop = System.getProperty("sun.awt.backingStore"); if (prop == null) { backingStoreType = XConstants.NotUseful; @@ -2565,8 +2543,7 @@ public boolean isTranslucencyCapable(GraphicsConfiguration gc) { * Returns the value of "sun.awt.disablegrab" property. Default * value is {@code false}. */ - @SuppressWarnings("removal") public static boolean getSunAwtDisableGrab() { - return AccessController.doPrivileged(new GetBooleanAction("sun.awt.disablegrab")); + return Boolean.getBoolean("sun.awt.disablegrab"); } } diff --git a/src/java.desktop/unix/classes/sun/awt/X11/XTrayIconPeer.java b/src/java.desktop/unix/classes/sun/awt/X11/XTrayIconPeer.java index a53dbebdd15f3..c3711010b7c1f 100644 --- a/src/java.desktop/unix/classes/sun/awt/X11/XTrayIconPeer.java +++ b/src/java.desktop/unix/classes/sun/awt/X11/XTrayIconPeer.java @@ -30,8 +30,6 @@ import java.awt.peer.TrayIconPeer; import sun.awt.*; import java.awt.image.*; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.lang.reflect.InvocationTargetException; import sun.util.logging.PlatformLogger; @@ -66,7 +64,6 @@ public void dispatchEvent(XEvent ev) {} static final int TRAY_ICON_WIDTH = 24; static final int TRAY_ICON_HEIGHT = 24; - @SuppressWarnings("removal") XTrayIconPeer(TrayIcon target) throws AWTException { @@ -84,12 +81,7 @@ public void dispatchEvent(XEvent ev) {} // Fix for 6317038: as EmbeddedFrame is instance of Frame, it is blocked // by modal dialogs, but in the case of TrayIcon it shouldn't. So we // set ModalExclusion property on it. - AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { - eframe.setModalExclusionType(Dialog.ModalExclusionType.TOOLKIT_EXCLUDE); - return null; - } - }); + eframe.setModalExclusionType(Dialog.ModalExclusionType.TOOLKIT_EXCLUDE); if (XWM.getWMID() != XWM.METACITY_WM) { diff --git a/src/java.desktop/unix/classes/sun/awt/X11/XlibWrapper.java b/src/java.desktop/unix/classes/sun/awt/X11/XlibWrapper.java index 7a23c806374b8..804107d982066 100644 --- a/src/java.desktop/unix/classes/sun/awt/X11/XlibWrapper.java +++ b/src/java.desktop/unix/classes/sun/awt/X11/XlibWrapper.java @@ -25,10 +25,7 @@ package sun.awt.X11; -import java.security.AccessController; - import jdk.internal.misc.Unsafe; -import sun.security.action.GetPropertyAction; final class XlibWrapper { @@ -585,9 +582,7 @@ static native void SetBitmapShape(long display, long window, static final boolean isBuildInternal; static { - @SuppressWarnings("removal") - String dataModelProp = AccessController.doPrivileged( - new GetPropertyAction("sun.arch.data.model")); + String dataModelProp = System.getProperty("sun.arch.data.model"); try { dataModel = Integer.parseInt(dataModelProp); } catch (Exception e) { @@ -639,9 +634,7 @@ static String getEventToString( int type ) { } private static boolean getBuildInternal() { - @SuppressWarnings("removal") - String javaVersion = AccessController.doPrivileged( - new GetPropertyAction("java.version")); + String javaVersion = System.getProperty("java.version"); return javaVersion != null && javaVersion.contains("internal"); } diff --git a/src/java.desktop/unix/classes/sun/awt/X11GraphicsDevice.java b/src/java.desktop/unix/classes/sun/awt/X11GraphicsDevice.java index 03f06408765c9..ca43142a098b4 100644 --- a/src/java.desktop/unix/classes/sun/awt/X11GraphicsDevice.java +++ b/src/java.desktop/unix/classes/sun/awt/X11GraphicsDevice.java @@ -33,8 +33,6 @@ import java.awt.Insets; import java.awt.Rectangle; import java.awt.Window; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -447,7 +445,6 @@ public synchronized DisplayMode[] getDisplayModes() { return modes.toArray(retArray); } - @SuppressWarnings("removal") @Override public synchronized void setDisplayMode(DisplayMode dm) { if (!isDisplayChangeSupported()) { @@ -474,24 +471,20 @@ public synchronized void setDisplayMode(DisplayMode dm) { // is already in the original DisplayMode at that time, this // hook will have no effect) shutdownHookRegistered = true; - PrivilegedAction a = () -> { - Runnable r = () -> { - Window old = getFullScreenWindow(); - if (old != null) { - exitFullScreenExclusive(old); - if (isDisplayChangeSupported()) { - setDisplayMode(origDisplayMode); - } + Runnable r = () -> { + Window old = getFullScreenWindow(); + if (old != null) { + exitFullScreenExclusive(old); + if (isDisplayChangeSupported()) { + setDisplayMode(origDisplayMode); } - }; - String name = "Display-Change-Shutdown-Thread-" + screen; - Thread t = new Thread( - ThreadGroupUtils.getRootThreadGroup(), r, name, 0, false); - t.setContextClassLoader(null); - Runtime.getRuntime().addShutdownHook(t); - return null; + } }; - AccessController.doPrivileged(a); + String name = "Display-Change-Shutdown-Thread-" + screen; + Thread t = new Thread( + ThreadGroupUtils.getRootThreadGroup(), r, name, 0, false); + t.setContextClassLoader(null); + Runtime.getRuntime().addShutdownHook(t); } // switch to the new DisplayMode diff --git a/src/java.desktop/unix/classes/sun/awt/X11GraphicsEnvironment.java b/src/java.desktop/unix/classes/sun/awt/X11GraphicsEnvironment.java index 42b20f6684398..9d42e2c92da8f 100644 --- a/src/java.desktop/unix/classes/sun/awt/X11GraphicsEnvironment.java +++ b/src/java.desktop/unix/classes/sun/awt/X11GraphicsEnvironment.java @@ -59,78 +59,71 @@ public final class X11GraphicsEnvironment extends SunGraphicsEnvironment { initStatic(); } - @SuppressWarnings({"removal", "restricted"}) + @SuppressWarnings("restricted") private static void initStatic() { - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Object run() { - System.loadLibrary("awt"); - - /* - * Note: The XToolkit object depends on the static initializer - * of X11GraphicsEnvironment to initialize the connection to - * the X11 server. - */ - if (!isHeadless()) { - // first check the OGL system property - boolean glxRequested = false; - String prop = System.getProperty("sun.java2d.opengl"); - if (prop != null) { - if (prop.equals("true") || prop.equals("t")) { - glxRequested = true; - } else if (prop.equals("True") || prop.equals("T")) { - glxRequested = true; - glxVerbose = true; - } - } + System.loadLibrary("awt"); + + /* + * Note: The XToolkit object depends on the static initializer + * of X11GraphicsEnvironment to initialize the connection to + * the X11 server. + */ + if (!isHeadless()) { + // first check the OGL system property + boolean glxRequested = false; + String prop = System.getProperty("sun.java2d.opengl"); + if (prop != null) { + if (prop.equals("true") || prop.equals("t")) { + glxRequested = true; + } else if (prop.equals("True") || prop.equals("T")) { + glxRequested = true; + glxVerbose = true; + } + } - // Now check for XRender system property - boolean xRenderRequested = true; - boolean xRenderIgnoreLinuxVersion = false; - String xProp = System.getProperty("sun.java2d.xrender"); - if (xProp != null) { - if (xProp.equals("false") || xProp.equals("f")) { - xRenderRequested = false; - } else if (xProp.equals("True") || xProp.equals("T")) { - xRenderRequested = true; - xRenderVerbose = true; - } - - if(xProp.equalsIgnoreCase("t") || xProp.equalsIgnoreCase("true")) { - xRenderIgnoreLinuxVersion = true; - } - } + // Now check for XRender system property + boolean xRenderRequested = true; + boolean xRenderIgnoreLinuxVersion = false; + String xProp = System.getProperty("sun.java2d.xrender"); + if (xProp != null) { + if (xProp.equals("false") || xProp.equals("f")) { + xRenderRequested = false; + } else if (xProp.equals("True") || xProp.equals("T")) { + xRenderRequested = true; + xRenderVerbose = true; + } - // initialize the X11 display connection - initDisplay(glxRequested); - - // only attempt to initialize GLX if it was requested - if (glxRequested) { - glxAvailable = initGLX(); - if (glxVerbose && !glxAvailable) { - System.out.println( - "Could not enable OpenGL " + - "pipeline (GLX 1.3 not available)"); - } - } + if (xProp.equalsIgnoreCase("t") || xProp.equalsIgnoreCase("true")) { + xRenderIgnoreLinuxVersion = true; + } + } - // only attempt to initialize Xrender if it was requested - if (xRenderRequested) { - xRenderAvailable = initXRender(xRenderVerbose, xRenderIgnoreLinuxVersion); - if (xRenderVerbose && !xRenderAvailable) { - System.out.println( - "Could not enable XRender pipeline"); - } - } + // initialize the X11 display connection + initDisplay(glxRequested); - if (xRenderAvailable) { - XRSurfaceData.initXRSurfaceData(); - } + // only attempt to initialize GLX if it was requested + if (glxRequested) { + glxAvailable = initGLX(); + if (glxVerbose && !glxAvailable) { + System.out.println( + "Could not enable OpenGL " + + "pipeline (GLX 1.3 not available)"); + } + } + + // only attempt to initialize Xrender if it was requested + if (xRenderRequested) { + xRenderAvailable = initXRender(xRenderVerbose, xRenderIgnoreLinuxVersion); + if (xRenderVerbose && !xRenderAvailable) { + System.out.println( + "Could not enable XRender pipeline"); } + } - return null; + if (xRenderAvailable) { + XRSurfaceData.initXRSurfaceData(); } - }); + } // Install the correct surface manager factory. SurfaceManagerFactory.setInstance(new UnixSurfaceManagerFactory()); @@ -299,9 +292,7 @@ private static boolean _isDisplayLocal() { return true; } - @SuppressWarnings("removal") - String isRemote = java.security.AccessController.doPrivileged( - new sun.security.action.GetPropertyAction("sun.java2d.remote")); + String isRemote = System.getProperty("sun.java2d.remote"); if (isRemote != null) { return isRemote.equals("false"); } @@ -322,41 +313,35 @@ private static boolean _isDisplayLocal() { return true; } - @SuppressWarnings("removal") - Boolean result = java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Boolean run() { - InetAddress[] remAddr = null; - Enumeration locals = null; - Enumeration interfaces = null; - try { - interfaces = NetworkInterface.getNetworkInterfaces(); - remAddr = InetAddress.getAllByName(hostName); - if (remAddr == null) { - return Boolean.FALSE; - } - } catch (UnknownHostException e) { - System.err.println("Unknown host: " + hostName); - return Boolean.FALSE; - } catch (SocketException e1) { - System.err.println(e1.getMessage()); - return Boolean.FALSE; - } + InetAddress[] remAddr = null; + Enumeration locals = null; + Enumeration interfaces = null; + try { + interfaces = NetworkInterface.getNetworkInterfaces(); + remAddr = InetAddress.getAllByName(hostName); + if (remAddr == null) { + return false; + } + } catch (UnknownHostException e) { + System.err.println("Unknown host: " + hostName); + return false; + } catch (SocketException e1) { + System.err.println(e1.getMessage()); + return false; + } - for (; interfaces.hasMoreElements();) { - locals = interfaces.nextElement().getInetAddresses(); - for (; locals.hasMoreElements();) { - final InetAddress localAddr = locals.nextElement(); - for (int i = 0; i < remAddr.length; i++) { - if (localAddr.equals(remAddr[i])) { - return Boolean.TRUE; - } - } + for (; interfaces.hasMoreElements();) { + locals = interfaces.nextElement().getInetAddresses(); + for (; locals.hasMoreElements();) { + final InetAddress localAddr = locals.nextElement(); + for (int i = 0; i < remAddr.length; i++) { + if (localAddr.equals(remAddr[i])) { + return true; } } - return Boolean.FALSE; - }}); - return result.booleanValue(); + } + } + return false; } diff --git a/src/java.desktop/unix/classes/sun/awt/screencast/ScreencastHelper.java b/src/java.desktop/unix/classes/sun/awt/screencast/ScreencastHelper.java index 78661587554e3..8f276954d6dca 100644 --- a/src/java.desktop/unix/classes/sun/awt/screencast/ScreencastHelper.java +++ b/src/java.desktop/unix/classes/sun/awt/screencast/ScreencastHelper.java @@ -27,14 +27,12 @@ import sun.awt.UNIXToolkit; import sun.java2d.pipe.Region; -import sun.security.action.GetPropertyAction; import java.awt.GraphicsConfiguration; import java.awt.GraphicsEnvironment; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.geom.AffineTransform; -import java.security.AccessController; import java.util.Arrays; import java.util.List; import java.util.Set; @@ -48,7 +46,6 @@ * org.freedesktop.portal.ScreenCast API */ -@SuppressWarnings("removal") public class ScreencastHelper { static final boolean SCREENCAST_DEBUG; @@ -70,13 +67,7 @@ private ScreencastHelper() { } static { - SCREENCAST_DEBUG = Boolean.parseBoolean( - AccessController.doPrivileged( - new GetPropertyAction( - "awt.robot.screenshotDebug", - "false" - ) - )); + SCREENCAST_DEBUG = Boolean.getBoolean("awt.robot.screenshotDebug"); boolean loadFailed = false; diff --git a/src/java.desktop/unix/classes/sun/awt/screencast/TokenStorage.java b/src/java.desktop/unix/classes/sun/awt/screencast/TokenStorage.java index b05ff7f8c4add..0db18c9c3b799 100644 --- a/src/java.desktop/unix/classes/sun/awt/screencast/TokenStorage.java +++ b/src/java.desktop/unix/classes/sun/awt/screencast/TokenStorage.java @@ -37,8 +37,6 @@ import java.nio.file.WatchKey; import java.nio.file.WatchService; import java.nio.file.attribute.PosixFilePermission; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedHashSet; @@ -73,18 +71,8 @@ private TokenStorage() {} private static final Path PROPS_PATH; private static final Path PROP_FILENAME; - @SuppressWarnings("removal") - private static void doPrivilegedRunnable(Runnable runnable) { - AccessController.doPrivileged((PrivilegedAction) () -> { - runnable.run(); - return null; - }); - } - static { - @SuppressWarnings("removal") - Path propsPath = AccessController - .doPrivileged((PrivilegedAction) () -> setupPath()); + Path propsPath = setupPath(); PROPS_PATH = propsPath; @@ -226,9 +214,9 @@ public void run() { } if (kind == ENTRY_CREATE) { - doPrivilegedRunnable(() -> setFilePermission(PROPS_PATH)); + setFilePermission(PROPS_PATH); } else if (kind == ENTRY_MODIFY) { - doPrivilegedRunnable(() -> readTokens(PROPS_PATH)); + readTokens(PROPS_PATH); } else if (kind == ENTRY_DELETE) { synchronized (PROPS) { PROPS.clear(); @@ -244,25 +232,23 @@ public void run() { private static WatchService watchService; private static void setupWatch() { - doPrivilegedRunnable(() -> { - try { - watchService = - FileSystems.getDefault().newWatchService(); - - PROPS_PATH - .getParent() - .register(watchService, - ENTRY_CREATE, - ENTRY_DELETE, - ENTRY_MODIFY); - - } catch (Exception e) { - if (SCREENCAST_DEBUG) { - System.err.printf("Token storage: failed to setup " + - "file watch %s\n", e); - } + try { + watchService = + FileSystems.getDefault().newWatchService(); + + PROPS_PATH + .getParent() + .register(watchService, + ENTRY_CREATE, + ENTRY_DELETE, + ENTRY_MODIFY); + + } catch (Exception e) { + if (SCREENCAST_DEBUG) { + System.err.printf("Token storage: failed to setup " + + "file watch %s\n", e); } - }); + } if (watchService != null) { new WatcherThread(watchService).start(); @@ -317,7 +303,7 @@ private static void storeTokenFromNative(String oldToken, } if (changed) { - doPrivilegedRunnable(() -> store(PROPS_PATH, "save tokens")); + store(PROPS_PATH, "save tokens"); } } } @@ -372,7 +358,7 @@ static Set getTokens(List affectedScreenBounds) { .toList(); } - doPrivilegedRunnable(() -> removeMalformedRecords(malformed)); + removeMalformedRecords(malformed); // 1. Try to find exact matches for (TokenItem tokenItem : allTokenItems) { diff --git a/src/java.desktop/unix/classes/sun/font/FcFontConfiguration.java b/src/java.desktop/unix/classes/sun/font/FcFontConfiguration.java index 8638bd3f59473..0e9b612301c23 100644 --- a/src/java.desktop/unix/classes/sun/font/FcFontConfiguration.java +++ b/src/java.desktop/unix/classes/sun/font/FcFontConfiguration.java @@ -363,11 +363,6 @@ protected void setOsNameAndVersion() { private File getFcInfoFile() { if (fcInfoFileName == null) { - // NB need security permissions to get true IP address, and - // we should have those as the whole initialisation is in a - // doPrivileged block. But in this case no exception is thrown, - // and it returns the loop back address, and so we end up with - // "localhost" String hostname; try { hostname = InetAddress.getLocalHost().getHostName(); diff --git a/src/java.desktop/unix/classes/sun/java2d/x11/X11SurfaceData.java b/src/java.desktop/unix/classes/sun/java2d/x11/X11SurfaceData.java index 0210dd929cbde..88c44369abf64 100644 --- a/src/java.desktop/unix/classes/sun/java2d/x11/X11SurfaceData.java +++ b/src/java.desktop/unix/classes/sun/java2d/x11/X11SurfaceData.java @@ -210,9 +210,7 @@ public Raster getRaster(int x, int y, int w, int h) { initIDs(XORComposite.class); - @SuppressWarnings("removal") - String xtextpipe = java.security.AccessController.doPrivileged - (new sun.security.action.GetPropertyAction("sun.java2d.xtextpipe")); + String xtextpipe = System.getProperty("sun.java2d.xtextpipe"); if (xtextpipe == null || "true".startsWith(xtextpipe)) { if ("true".equals(xtextpipe)) { // Only verbose if they use the full string "true" @@ -248,9 +246,7 @@ public static boolean isAccelerationEnabled() { if (GraphicsEnvironment.isHeadless()) { accelerationEnabled = Boolean.FALSE; } else { - @SuppressWarnings("removal") - String prop = java.security.AccessController.doPrivileged( - new sun.security.action.GetPropertyAction("sun.java2d.pmoffscreen")); + String prop = System.getProperty("sun.java2d.pmoffscreen"); if (prop != null) { // true iff prop==true, false otherwise accelerationEnabled = Boolean.valueOf(prop); diff --git a/src/java.desktop/unix/classes/sun/java2d/xr/XRCompositeManager.java b/src/java.desktop/unix/classes/sun/java2d/xr/XRCompositeManager.java index c2201cb7c7c3d..0d10e85f607bc 100644 --- a/src/java.desktop/unix/classes/sun/java2d/xr/XRCompositeManager.java +++ b/src/java.desktop/unix/classes/sun/java2d/xr/XRCompositeManager.java @@ -30,8 +30,6 @@ import java.awt.Paint; import java.awt.geom.AffineTransform; import java.awt.geom.NoninvertibleTransformException; -import java.security.AccessController; -import java.security.PrivilegedAction; import sun.awt.image.PixelConverter; import sun.font.XRTextRenderer; @@ -93,13 +91,7 @@ public static synchronized XRCompositeManager getInstance( private XRCompositeManager(XRSurfaceData surface) { con = new XRBackendNative(); - @SuppressWarnings("removal") - String gradProp = - AccessController.doPrivileged(new PrivilegedAction() { - public String run() { - return System.getProperty("sun.java2d.xrgradcache"); - } - }); + String gradProp = System.getProperty("sun.java2d.xrgradcache"); enableGradCache = gradProp == null || !(gradProp.equalsIgnoreCase("false") || diff --git a/src/java.desktop/unix/classes/sun/print/CUPSPrinter.java b/src/java.desktop/unix/classes/sun/print/CUPSPrinter.java index 8be118c42a570..62c4331606594 100644 --- a/src/java.desktop/unix/classes/sun/print/CUPSPrinter.java +++ b/src/java.desktop/unix/classes/sun/print/CUPSPrinter.java @@ -90,16 +90,10 @@ public class CUPSPrinter { initStatic(); } - @SuppressWarnings({"removal", "restricted"}) + @SuppressWarnings("restricted") private static void initStatic() { // load awt library to access native code - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Void run() { - System.loadLibrary("awt"); - return null; - } - }); + System.loadLibrary("awt"); libFound = initIDs(); if (libFound) { cupsServer = getCupsServer(); @@ -308,18 +302,12 @@ static String[] getDefaultPrinter() { IPPPrintService.getIPPConnection(url); if (urlConnection != null) { - @SuppressWarnings("removal") - OutputStream os = java.security.AccessController. - doPrivileged(new java.security.PrivilegedAction() { - public OutputStream run() { - try { - return urlConnection.getOutputStream(); - } catch (Exception e) { - IPPPrintService.debug_println(debugPrefix+e); - } - return null; - } - }); + OutputStream os = null; + try { + os = urlConnection.getOutputStream(); + } catch (Exception e) { + IPPPrintService.debug_println(debugPrefix+e); + } if (os == null) { return null; @@ -424,17 +412,11 @@ static String[] getAllPrinters() { IPPPrintService.getIPPConnection(url); if (urlConnection != null) { - @SuppressWarnings("removal") - OutputStream os = java.security.AccessController. - doPrivileged(new java.security.PrivilegedAction() { - public OutputStream run() { - try { - return urlConnection.getOutputStream(); - } catch (Exception e) { - } - return null; - } - }); + OutputStream os = null; + try { + os = urlConnection.getOutputStream(); + } catch (Exception e) { + } if (os == null) { return null; @@ -507,12 +489,9 @@ private static String getDomainSocketPathname() { return domainSocketPathname; } - @SuppressWarnings("removal") private static boolean isSandboxedApp() { if (PrintServiceLookupProvider.isMac()) { - return java.security.AccessController - .doPrivileged((java.security.PrivilegedAction) () -> - System.getenv("APP_SANDBOX_CONTAINER_ID") != null); + return (System.getenv("APP_SANDBOX_CONTAINER_ID") != null); } return false; } diff --git a/src/java.desktop/unix/classes/sun/print/IPPPrintService.java b/src/java.desktop/unix/classes/sun/print/IPPPrintService.java index 5a6437014ddc3..4d217ec6e3e18 100644 --- a/src/java.desktop/unix/classes/sun/print/IPPPrintService.java +++ b/src/java.desktop/unix/classes/sun/print/IPPPrintService.java @@ -119,9 +119,7 @@ protected static void debug_println(String str) { private static final String FORCE_PIPE_PROP = "sun.print.ippdebug"; static { - @SuppressWarnings("removal") - String debugStr = java.security.AccessController.doPrivileged( - new sun.security.action.GetPropertyAction(FORCE_PIPE_PROP)); + String debugStr = System.getProperty(FORCE_PIPE_PROP); debugPrint = "true".equalsIgnoreCase(debugStr); } @@ -1874,18 +1872,12 @@ private void opGetAttributes() { AttributeClass.TAG_URI, ""+myURI)}; - @SuppressWarnings("removal") - OutputStream os = java.security.AccessController. - doPrivileged(new java.security.PrivilegedAction() { - public OutputStream run() { - try { - return urlConnection.getOutputStream(); - } catch (Exception e) { - } - return null; - } - }); + OutputStream os = null; + try { + os = urlConnection.getOutputStream(); + } catch (Exception e) { + } if (os == null) { return; } diff --git a/src/java.desktop/unix/classes/sun/print/PrintServiceLookupProvider.java b/src/java.desktop/unix/classes/sun/print/PrintServiceLookupProvider.java index 5e45b00861e58..15025d43d6f5d 100644 --- a/src/java.desktop/unix/classes/sun/print/PrintServiceLookupProvider.java +++ b/src/java.desktop/unix/classes/sun/print/PrintServiceLookupProvider.java @@ -28,12 +28,8 @@ import java.io.BufferedReader; import java.io.IOException; import java.net.MalformedURLException; -import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Vector; -import java.security.AccessController; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; import javax.print.DocFlavor; import javax.print.MultiDocPrintService; import javax.print.PrintService; @@ -95,9 +91,7 @@ public class PrintServiceLookupProvider extends PrintServiceLookup * can be used to force the printing code to poll or not poll * for PrintServices. */ - @SuppressWarnings("removal") - String pollStr = java.security.AccessController.doPrivileged( - new sun.security.action.GetPropertyAction("sun.java2d.print.polling")); + String pollStr = System.getProperty("sun.java2d.print.polling"); if (pollStr != null) { if (pollStr.equalsIgnoreCase("true")) { @@ -111,10 +105,7 @@ public class PrintServiceLookupProvider extends PrintServiceLookup * can be used to specify minimum refresh time (in seconds) * for polling PrintServices. The default is 120. */ - @SuppressWarnings("removal") - String refreshTimeStr = java.security.AccessController.doPrivileged( - new sun.security.action.GetPropertyAction( - "sun.java2d.print.minRefreshTime")); + String refreshTimeStr = System.getProperty("sun.java2d.print.minRefreshTime"); if (refreshTimeStr != null) { try { @@ -132,9 +123,7 @@ public class PrintServiceLookupProvider extends PrintServiceLookup * take lots of time if thousands of printers are attached to a server. */ if (isAIX()) { - @SuppressWarnings("removal") - String aixPrinterEnumerator = java.security.AccessController.doPrivileged( - new sun.security.action.GetPropertyAction("sun.java2d.print.aix.lpstat")); + String aixPrinterEnumerator = System.getProperty("sun.java2d.print.aix.lpstat"); if (aixPrinterEnumerator != null) { if (aixPrinterEnumerator.equalsIgnoreCase("lpstat")) { @@ -202,18 +191,15 @@ static int getBSDCommandIndex() { return BSD_LPD; } - @SuppressWarnings("removal") public PrintServiceLookupProvider() { // start the printer listener thread if (pollServices) { - AccessController.doPrivileged((PrivilegedAction) () -> { - Thread thr = new Thread(ThreadGroupUtils.getRootThreadGroup(), - new PrinterChangeListener(), - "PrinterListener", 0, false); - thr.setContextClassLoader(null); - thr.setDaemon(true); - return thr; - }).start(); + Thread thr = new Thread(ThreadGroupUtils.getRootThreadGroup(), + new PrinterChangeListener(), + "PrinterListener", 0, false); + thr.setContextClassLoader(null); + thr.setDaemon(true); + thr.start(); IPPPrintService.debug_println(debugPrefix+"polling turned on"); } } @@ -871,7 +857,6 @@ private String[] getAllPrinterNamesAIX() { return printerNames.toArray(new String[printerNames.size()]); } - @SuppressWarnings("removal") static String[] execCmd(final String command) { ArrayList results = null; try { @@ -886,51 +871,46 @@ static String[] execCmd(final String command) { cmd[2] = "LC_ALL=C " + command; } - results = AccessController.doPrivileged( - new PrivilegedExceptionAction>() { - public ArrayList run() throws IOException { + Process proc; + BufferedReader bufferedReader = null; + File f = Files.createTempFile("prn", "xc") + .toFile(); + cmd[2] = cmd[2] + ">" + f.getAbsolutePath(); - Process proc; - BufferedReader bufferedReader = null; - File f = Files.createTempFile("prn","xc").toFile(); - cmd[2] = cmd[2]+">"+f.getAbsolutePath(); - - proc = Runtime.getRuntime().exec(cmd); - try { - boolean done = false; // in case of interrupt. - while (!done) { - try { - proc.waitFor(); - done = true; - } catch (InterruptedException e) { - } - } + proc = Runtime.getRuntime().exec(cmd); + try { + boolean done = false; // in case of interrupt. + while (!done) { + try { + proc.waitFor(); + done = true; + } catch (InterruptedException ignored) { + } + } - if (proc.exitValue() == 0) { - FileReader reader = new FileReader(f); - bufferedReader = new BufferedReader(reader); - String line; - ArrayList results = new ArrayList<>(); - while ((line = bufferedReader.readLine()) - != null) { - results.add(line); - } - return results; - } - } finally { - f.delete(); - // promptly close all streams. - if (bufferedReader != null) { - bufferedReader.close(); - } - proc.getInputStream().close(); - proc.getErrorStream().close(); - proc.getOutputStream().close(); - } - return null; + if (proc.exitValue() == 0) { + FileReader reader = new FileReader(f); + bufferedReader = new BufferedReader(reader); + String line; + while ((line = bufferedReader.readLine()) + != null) { + results.add(line); } - }); - } catch (PrivilegedActionException e) { + } + } finally { + f.delete(); + // promptly close all streams. + if (bufferedReader != null) { + bufferedReader.close(); + } + proc.getInputStream() + .close(); + proc.getErrorStream() + .close(); + proc.getOutputStream() + .close(); + } + } catch (IOException ignored) { } if (results == null) { return new String[0]; diff --git a/src/java.desktop/unix/classes/sun/print/UnixPrintJob.java b/src/java.desktop/unix/classes/sun/print/UnixPrintJob.java index 913c69e40eef8..1249d29ec72fd 100644 --- a/src/java.desktop/unix/classes/sun/print/UnixPrintJob.java +++ b/src/java.desktop/unix/classes/sun/print/UnixPrintJob.java @@ -86,7 +86,6 @@ import java.awt.print.PrinterException; - public class UnixPrintJob implements CancelablePrintJob { private static String debugPrefix = "UnixPrintJob>> "; @@ -525,8 +524,7 @@ public void print(Doc doc, PrintRequestAttributeSet attributes) // now spool the print data. PrinterOpener po = new PrinterOpener(); - @SuppressWarnings("removal") - var dummy = java.security.AccessController.doPrivileged(po); + po.run(); if (po.pex != null) { throw po.pex; } @@ -599,8 +597,7 @@ public void print(Doc doc, PrintRequestAttributeSet attributes) if (mDestType == UnixPrintJob.DESTPRINTER) { PrinterSpooler spooler = new PrinterSpooler(); - @SuppressWarnings("removal") - var dummy2 = java.security.AccessController.doPrivileged(spooler); + spooler.run(); if (spooler.pex != null) { throw spooler.pex; } @@ -911,9 +908,7 @@ private String[] printExecCmd(String printer, String options, private String mDestination, mOptions=""; private boolean mNoJobSheet = false; - // Inner class to run "privileged" to open the printer output stream. - - private class PrinterOpener implements java.security.PrivilegedAction { + private class PrinterOpener { PrintException pex; OutputStream result; @@ -941,9 +936,7 @@ public OutputStream run() { } } - // Inner class to run "privileged" to invoke the system print command - - private class PrinterSpooler implements java.security.PrivilegedAction { + private class PrinterSpooler { PrintException pex; private void handleProcessFailure(final Process failedProcess, diff --git a/src/java.desktop/unix/classes/sun/print/UnixPrintService.java b/src/java.desktop/unix/classes/sun/print/UnixPrintService.java index bbd8c6c9c78f2..201487e9ca46e 100644 --- a/src/java.desktop/unix/classes/sun/print/UnixPrintService.java +++ b/src/java.desktop/unix/classes/sun/print/UnixPrintService.java @@ -145,9 +145,7 @@ public class UnixPrintService implements PrintService, AttributeUpdater, "| grep -E '^[ 0-9a-zA-Z_-]*@' | awk '{print $4}'" }; - @SuppressWarnings("removal") - private static String encoding = java.security.AccessController.doPrivileged( - new sun.security.action.GetPropertyAction("file.encoding")); + private static String encoding = System.getProperty("file.encoding"); /* let's try to support a few of these */ private static final Class[] serviceAttrCats = { From a599c30171fe2b1557ad967d61048656fdb8c752 Mon Sep 17 00:00:00 2001 From: Jaikiran Pai Date: Thu, 21 Nov 2024 00:49:25 +0000 Subject: [PATCH 56/74] 8344471: Remove SecurityManager related code from java.compiler module Reviewed-by: rriggs, jlahoda, jjg --- .../classes/javax/tools/ToolProvider.java | 22 ++----------------- 1 file changed, 2 insertions(+), 20 deletions(-) diff --git a/src/java.compiler/share/classes/javax/tools/ToolProvider.java b/src/java.compiler/share/classes/javax/tools/ToolProvider.java index 8cdfd63b17ded..03a56139fdd25 100644 --- a/src/java.compiler/share/classes/javax/tools/ToolProvider.java +++ b/src/java.compiler/share/classes/javax/tools/ToolProvider.java @@ -25,8 +25,6 @@ package javax.tools; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.Objects; import java.util.ServiceConfigurationError; import java.util.ServiceLoader; @@ -118,29 +116,13 @@ private static T getSystemTool(Class clazz, String moduleName, String cla try { ServiceLoader sl = ServiceLoader.load(clazz, ClassLoader.getSystemClassLoader()); for (T tool : sl) { - if (matches(tool, moduleName)) + if (Objects.equals(tool.getClass().getModule().getName(), moduleName)) { return tool; + } } } catch (ServiceConfigurationError e) { throw new Error(e); } return null; } - - /** - * Determine if this is the desired tool instance. - * @param the interface of the tool - * @param tool the instance of the tool - * @param moduleName the name of the module containing the desired implementation - * @return true if and only if the tool matches the specified criteria - */ - @SuppressWarnings("removal") - private static boolean matches(T tool, String moduleName) { - PrivilegedAction pa = () -> { - Module toolModule = tool.getClass().getModule(); - String toolModuleName = toolModule.getName(); - return Objects.equals(toolModuleName, moduleName); - }; - return AccessController.doPrivileged(pa); - } } From 400eb9b10ae0e53e58893b7ea5233d2d2e4046b6 Mon Sep 17 00:00:00 2001 From: Jaikiran Pai Date: Thu, 21 Nov 2024 00:55:23 +0000 Subject: [PATCH 57/74] 8344524: Remove SecurityManager related code from jdk.jlink module Reviewed-by: alanb, lancea, iris --- .../jdk/tools/jlink/internal/Jlink.java | 12 ------ .../tools/jlink/internal/JlinkPermission.java | 42 ------------------- .../jdk/tools/jlink/internal/Main.java | 8 +--- 3 files changed, 1 insertion(+), 61 deletions(-) delete mode 100644 src/jdk.jlink/share/classes/jdk/tools/jlink/internal/JlinkPermission.java diff --git a/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/Jlink.java b/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/Jlink.java index 465a1cae8d98b..99029651bfb1c 100644 --- a/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/Jlink.java +++ b/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/Jlink.java @@ -242,18 +242,6 @@ public String toString() { } } - /** - * Jlink instance constructor, if a security manager is set, the jlink - * permission is checked. - */ - @SuppressWarnings("removal") - public Jlink() { - if (System.getSecurityManager() != null) { - System.getSecurityManager(). - checkPermission(new JlinkPermission("jlink")); - } - } - /** * Build the image. * diff --git a/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/JlinkPermission.java b/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/JlinkPermission.java deleted file mode 100644 index f1725e77ee209..0000000000000 --- a/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/JlinkPermission.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2015, 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 jdk.tools.jlink.internal; - -import java.security.BasicPermission; - -/** - * The permission required to use jlink API. The permission target_name is - * "jlink". e.g.: permission jdk.tools.jlink.plugins.JlinkPermission "jlink"; - * - */ -public final class JlinkPermission extends BasicPermission { - - private static final long serialVersionUID = -3687912306077727801L; - - public JlinkPermission(String name) { - super(name); - } - -} diff --git a/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/Main.java b/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/Main.java index df08b2b54a435..eb743bc4dadd3 100644 --- a/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/Main.java +++ b/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/Main.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2024, 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 @@ -44,13 +44,7 @@ public static void main(String... args) throws Exception { * @param args command line arguments * @return an exit code. 0 means success, non-zero means an error occurred. */ - @SuppressWarnings("removal") public static int run(PrintWriter out, PrintWriter err, String... args) { - if (System.getSecurityManager() != null) { - System.getSecurityManager(). - checkPermission(new JlinkPermission("jlink")); - } - JlinkTask t = new JlinkTask(); t.setLog(out, err); return t.run(args); From 13439113c361dcb0629ece37844443cbf99ef704 Mon Sep 17 00:00:00 2001 From: Leonid Mesnik Date: Thu, 21 Nov 2024 01:32:09 +0000 Subject: [PATCH 58/74] 8340334: Update jcmd VM.events max parameter to be INT Reviewed-by: cjplummer, kevinw --- src/hotspot/share/services/diagnosticCommand.cpp | 14 +++++--------- src/hotspot/share/services/diagnosticCommand.hpp | 2 +- src/jdk.jcmd/share/man/jcmd.md | 2 +- 3 files changed, 7 insertions(+), 11 deletions(-) diff --git a/src/hotspot/share/services/diagnosticCommand.cpp b/src/hotspot/share/services/diagnosticCommand.cpp index 240f3604cc1da..b807a42661c2a 100644 --- a/src/hotspot/share/services/diagnosticCommand.cpp +++ b/src/hotspot/share/services/diagnosticCommand.cpp @@ -884,21 +884,17 @@ void CodeHeapAnalyticsDCmd::execute(DCmdSource source, TRAPS) { EventLogDCmd::EventLogDCmd(outputStream* output, bool heap) : DCmdWithParser(output, heap), _log("log", "Name of log to be printed. If omitted, all logs are printed.", "STRING", false, nullptr), - _max("max", "Maximum number of events to be printed (newest first). If omitted, all events are printed.", "STRING", false, nullptr) + _max("max", "Maximum number of events to be printed (newest first). If omitted or zero, all events are printed.", "INT", false, "0") { _dcmdparser.add_dcmd_option(&_log); _dcmdparser.add_dcmd_option(&_max); } void EventLogDCmd::execute(DCmdSource source, TRAPS) { - const char* max_value = _max.value(); - int max = -1; - if (max_value != nullptr) { - char* endptr = nullptr; - if (!parse_integer(max_value, &max)) { - output()->print_cr("Invalid max option: \"%s\".", max_value); - return; - } + int max = (int)_max.value(); + if (max < 0) { + output()->print_cr("Invalid max option: \"%d\".", max); + return; } const char* log_name = _log.value(); if (log_name != nullptr) { diff --git a/src/hotspot/share/services/diagnosticCommand.hpp b/src/hotspot/share/services/diagnosticCommand.hpp index c8e26504ece83..92e5849cbcd56 100644 --- a/src/hotspot/share/services/diagnosticCommand.hpp +++ b/src/hotspot/share/services/diagnosticCommand.hpp @@ -889,7 +889,7 @@ class ClassesDCmd : public DCmdWithParser { class EventLogDCmd : public DCmdWithParser { protected: DCmdArgument _log; - DCmdArgument _max; + DCmdArgument _max; public: static int num_arguments() { return 2; } EventLogDCmd(outputStream* output, bool heap); diff --git a/src/jdk.jcmd/share/man/jcmd.md b/src/jdk.jcmd/share/man/jcmd.md index 448dfdd305123..2d2e08bc9f500 100644 --- a/src/jdk.jcmd/share/man/jcmd.md +++ b/src/jdk.jcmd/share/man/jcmd.md @@ -836,7 +836,7 @@ The following commands are available: - `log`: (Optional) Name of log to be printed. If omitted, all logs are printed. (STRING, no default value) - `max`: (Optional) Maximum number of events to be printed (newest first). - If omitted, all events are printed. (STRING, no default value) + If omitted or zero, all events are printed. (INT, 0) `VM.flags` \[*options*\] : Print the VM flag options and their current values. From 4fbf272017d2f6933e66f8a67cb88e3ffc42339e Mon Sep 17 00:00:00 2001 From: SendaoYan Date: Thu, 21 Nov 2024 02:05:00 +0000 Subject: [PATCH 59/74] 8344526: RISC-V: implement -XX:+VerifyActivationFrameSize Co-authored-by: Fei Yang Reviewed-by: mli, fyang --- src/hotspot/cpu/riscv/interp_masm_riscv.cpp | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/hotspot/cpu/riscv/interp_masm_riscv.cpp b/src/hotspot/cpu/riscv/interp_masm_riscv.cpp index b00b4474d69da..897222ef995f4 100644 --- a/src/hotspot/cpu/riscv/interp_masm_riscv.cpp +++ b/src/hotspot/cpu/riscv/interp_masm_riscv.cpp @@ -441,7 +441,14 @@ void InterpreterMacroAssembler::dispatch_base(TosState state, Register Rs) { // Pay attention to the argument Rs, which is acquiesce in t0. if (VerifyActivationFrameSize) { - Unimplemented(); + Label L; + sub(t1, fp, esp); + int min_frame_size = + (frame::link_offset - frame::interpreter_frame_initial_sp_offset + frame::metadata_words) * wordSize; + sub(t1, t1, min_frame_size); + bgez(t1, L); + stop("broken stack frame"); + bind(L); } if (verifyoop && state == atos) { verify_oop(x10); From a01aa2202602d2fcdb81b4c5b4183cb6b7acfacb Mon Sep 17 00:00:00 2001 From: Phil Race Date: Thu, 21 Nov 2024 03:58:49 +0000 Subject: [PATCH 60/74] 8342281: Deprecate for removal javax.sound.sampled.AudioPermission Reviewed-by: honkar, kizune --- .../sun/media/sound/DirectAudioDevice.java | 19 ------------------- .../sun/media/sound/JSSecurityManager.java | 16 +++------------- .../javax/sound/sampled/AudioPermission.java | 3 +++ .../javax/sound/sampled/Lines/GetLine.java | 16 ---------------- 4 files changed, 6 insertions(+), 48 deletions(-) diff --git a/src/java.desktop/share/classes/com/sun/media/sound/DirectAudioDevice.java b/src/java.desktop/share/classes/com/sun/media/sound/DirectAudioDevice.java index cbc5416cd6072..77c03c5267dc2 100644 --- a/src/java.desktop/share/classes/com/sun/media/sound/DirectAudioDevice.java +++ b/src/java.desktop/share/classes/com/sun/media/sound/DirectAudioDevice.java @@ -404,10 +404,6 @@ void implOpen(AudioFormat format, int bufferSize) throws LineUnavailableExceptio // $$fb part of fix for 4679187: Clip.open() throws unexpected Exceptions Toolkit.isFullySpecifiedAudioFormat(format); - // check for record permission - if (!isSource) { - JSSecurityManager.checkRecordPermission(); - } int encoding = PCM; if (format.getEncoding().equals(AudioFormat.Encoding.ULAW)) { encoding = ULAW; @@ -509,11 +505,6 @@ else if (waitTime > 1000) { @Override void implStart() { - // check for record permission - if (!isSource) { - JSSecurityManager.checkRecordPermission(); - } - synchronized (lockNative) { nStart(id, isSource); @@ -538,11 +529,6 @@ void implStart() { @Override void implStop() { - // check for record permission - if (!isSource) { - JSSecurityManager.checkRecordPermission(); - } - if (monitoring) { getEventDispatcher().removeLineMonitor(this); monitoring = false; @@ -565,11 +551,6 @@ void implStop() { @Override void implClose() { - // check for record permission - if (!isSource) { - JSSecurityManager.checkRecordPermission(); - } - // be sure to remove this monitor if (monitoring) { getEventDispatcher().removeLineMonitor(this); diff --git a/src/java.desktop/share/classes/com/sun/media/sound/JSSecurityManager.java b/src/java.desktop/share/classes/com/sun/media/sound/JSSecurityManager.java index e9b99ac1a1097..91d5c0284b599 100644 --- a/src/java.desktop/share/classes/com/sun/media/sound/JSSecurityManager.java +++ b/src/java.desktop/share/classes/com/sun/media/sound/JSSecurityManager.java @@ -35,11 +35,9 @@ import java.util.Properties; import java.util.ServiceLoader; -import javax.sound.sampled.AudioPermission; - -/** Managing security in the Java Sound implementation. - * This class contains all code that uses and is used by - * SecurityManager +/** + * Historically this class managed ensuring privileges to access resources + * it is still used to get those resources but no longer does checks. * * @author Matthias Pfisterer */ @@ -50,14 +48,6 @@ final class JSSecurityManager { private JSSecurityManager() { } - static void checkRecordPermission() throws SecurityException { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPermission(new AudioPermission("record")); - } - } - /** * Load properties from a file. *

diff --git a/src/java.desktop/share/classes/javax/sound/sampled/AudioPermission.java b/src/java.desktop/share/classes/javax/sound/sampled/AudioPermission.java index 296360a65500c..f834c342b6fc3 100644 --- a/src/java.desktop/share/classes/javax/sound/sampled/AudioPermission.java +++ b/src/java.desktop/share/classes/javax/sound/sampled/AudioPermission.java @@ -40,10 +40,13 @@ * @apiNote * This permission cannot be used for controlling access to resources * as the Security Manager is no longer supported. + * Consequently this class is deprecated and may be removed in a future release. * * @author Kara Kytle * @since 1.3 + * @deprecated There is no replacement for this class. */ +@Deprecated(since="24", forRemoval=true) public class AudioPermission extends BasicPermission { /** diff --git a/test/jdk/javax/sound/sampled/Lines/GetLine.java b/test/jdk/javax/sound/sampled/Lines/GetLine.java index daa0114ae8a44..e31c5ac8d6f60 100644 --- a/test/jdk/javax/sound/sampled/Lines/GetLine.java +++ b/test/jdk/javax/sound/sampled/Lines/GetLine.java @@ -21,7 +21,6 @@ * questions. */ -import javax.sound.sampled.AudioPermission; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine; import javax.sound.sampled.Line; @@ -35,18 +34,6 @@ */ public class GetLine { - static boolean isSoundAccessDenied = false; - static { - SecurityManager securityManager = System.getSecurityManager(); - if (securityManager != null) { - try { - securityManager.checkPermission(new AudioPermission("*")); - } catch (SecurityException e) { - isSoundAccessDenied = true; - } - } - } - static final int STATUS_PASSED = 0; static final int STATUS_FAILED = 2; static final int STATUS_TEMP = 95; @@ -80,9 +67,6 @@ public static int run(String argv[], java.io.PrintStream out) { } try { l = AudioSystem.getLine(infos[0]); - } catch(SecurityException lue) { - log.println("SecurityException"); - return STATUS_PASSED; } catch (LineUnavailableException e1) { log.println("LUE"); return STATUS_PASSED; From 7105bb98cf8797082d2b61f0e08a4e5ba0bae8ac Mon Sep 17 00:00:00 2001 From: Phil Race Date: Thu, 21 Nov 2024 04:22:27 +0000 Subject: [PATCH 61/74] 8344664: Remove some un-used java/sun.security imports in the java.desktop module Reviewed-by: iris --- .../classes/com/sun/java/swing/plaf/gtk/GTKLookAndFeel.java | 2 -- .../share/classes/com/sun/media/sound/JARSoundbankReader.java | 1 - .../share/classes/com/sun/media/sound/Printer.java | 2 -- src/java.desktop/share/classes/java/awt/Component.java | 1 - src/java.desktop/share/classes/java/awt/Container.java | 2 -- src/java.desktop/share/classes/java/awt/Window.java | 1 - src/java.desktop/share/classes/javax/imageio/ImageIO.java | 2 -- .../share/classes/sun/awt/im/InputMethodContext.java | 1 - .../share/classes/sun/awt/util/ThreadGroupUtils.java | 1 - src/java.desktop/share/classes/sun/font/TrueTypeFont.java | 1 - .../share/classes/sun/java2d/marlin/MarlinUtils.java | 1 - src/java.desktop/unix/classes/sun/awt/UNIXToolkit.java | 4 ---- .../unix/classes/sun/awt/X11InputMethodDescriptor.java | 2 -- 13 files changed, 21 deletions(-) diff --git a/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/GTKLookAndFeel.java b/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/GTKLookAndFeel.java index a2414da455955..9490dc6bdff2b 100644 --- a/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/GTKLookAndFeel.java +++ b/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/GTKLookAndFeel.java @@ -38,7 +38,6 @@ import java.beans.PropertyChangeListener; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; -import java.security.AccessController; import java.util.HashMap; import java.util.Map; @@ -65,7 +64,6 @@ import com.sun.java.swing.plaf.gtk.GTKConstants.StateType; import sun.awt.SunToolkit; import sun.awt.UNIXToolkit; -import sun.security.action.GetPropertyAction; import sun.swing.AltProcessor; import sun.swing.DefaultLayoutStyle; import sun.swing.MnemonicHandler; diff --git a/src/java.desktop/share/classes/com/sun/media/sound/JARSoundbankReader.java b/src/java.desktop/share/classes/com/sun/media/sound/JARSoundbankReader.java index 4ff72c7040a8e..8b492fa77823b 100644 --- a/src/java.desktop/share/classes/com/sun/media/sound/JARSoundbankReader.java +++ b/src/java.desktop/share/classes/com/sun/media/sound/JARSoundbankReader.java @@ -40,7 +40,6 @@ import javax.sound.midi.spi.SoundbankReader; import sun.reflect.misc.ReflectUtil; -import sun.security.action.GetBooleanAction; /** * JarSoundbankReader is used to read soundbank object from jar files. diff --git a/src/java.desktop/share/classes/com/sun/media/sound/Printer.java b/src/java.desktop/share/classes/com/sun/media/sound/Printer.java index 40e179b1bd84b..af2c3e1198887 100644 --- a/src/java.desktop/share/classes/com/sun/media/sound/Printer.java +++ b/src/java.desktop/share/classes/com/sun/media/sound/Printer.java @@ -26,8 +26,6 @@ package com.sun.media.sound; -import sun.security.action.GetPropertyAction; - /** * Printer allows you to set up global debugging status and print * messages accordingly. diff --git a/src/java.desktop/share/classes/java/awt/Component.java b/src/java.desktop/share/classes/java/awt/Component.java index 71618eea95b88..36683ff2813ee 100644 --- a/src/java.desktop/share/classes/java/awt/Component.java +++ b/src/java.desktop/share/classes/java/awt/Component.java @@ -108,7 +108,6 @@ import sun.java2d.SunGraphicsEnvironment; import sun.java2d.pipe.Region; import sun.java2d.pipe.hw.ExtendedBufferCapabilities; -import sun.security.action.GetPropertyAction; import sun.swing.SwingAccessor; import sun.util.logging.PlatformLogger; diff --git a/src/java.desktop/share/classes/java/awt/Container.java b/src/java.desktop/share/classes/java/awt/Container.java index 63bd7467d91f2..b6fbfb808a682 100644 --- a/src/java.desktop/share/classes/java/awt/Container.java +++ b/src/java.desktop/share/classes/java/awt/Container.java @@ -50,7 +50,6 @@ import java.io.Serial; import java.io.Serializable; import java.lang.ref.WeakReference; -import java.security.AccessController; import java.util.ArrayList; import java.util.EventListener; import java.util.HashSet; @@ -67,7 +66,6 @@ import sun.awt.SunToolkit; import sun.awt.dnd.SunDropTargetEvent; import sun.java2d.pipe.Region; -import sun.security.action.GetBooleanAction; import sun.util.logging.PlatformLogger; /** diff --git a/src/java.desktop/share/classes/java/awt/Window.java b/src/java.desktop/share/classes/java/awt/Window.java index 9b8557394433b..f6560fb8e5870 100644 --- a/src/java.desktop/share/classes/java/awt/Window.java +++ b/src/java.desktop/share/classes/java/awt/Window.java @@ -70,7 +70,6 @@ import sun.awt.SunToolkit; import sun.awt.util.IdentityArrayList; import sun.java2d.pipe.Region; -import sun.security.action.GetPropertyAction; import sun.util.logging.PlatformLogger; /** diff --git a/src/java.desktop/share/classes/javax/imageio/ImageIO.java b/src/java.desktop/share/classes/javax/imageio/ImageIO.java index 316a74a22ea1b..f085383284ea9 100644 --- a/src/java.desktop/share/classes/javax/imageio/ImageIO.java +++ b/src/java.desktop/share/classes/javax/imageio/ImageIO.java @@ -34,7 +34,6 @@ import java.io.OutputStream; import java.lang.reflect.Method; import java.net.URL; -import java.security.AccessController; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; @@ -50,7 +49,6 @@ import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.ImageOutputStream; import sun.awt.AppContext; -import sun.security.action.GetPropertyAction; /** * A class containing static convenience methods for locating diff --git a/src/java.desktop/share/classes/sun/awt/im/InputMethodContext.java b/src/java.desktop/share/classes/sun/awt/im/InputMethodContext.java index a0f9baa3112cb..fd165a52f7247 100644 --- a/src/java.desktop/share/classes/sun/awt/im/InputMethodContext.java +++ b/src/java.desktop/share/classes/sun/awt/im/InputMethodContext.java @@ -43,7 +43,6 @@ import java.text.CharacterIterator; import javax.swing.JFrame; import sun.awt.InputMethodSupport; -import sun.security.action.GetPropertyAction; /** * The InputMethodContext class provides methods that input methods diff --git a/src/java.desktop/share/classes/sun/awt/util/ThreadGroupUtils.java b/src/java.desktop/share/classes/sun/awt/util/ThreadGroupUtils.java index 5d58a1c29d440..6944ba4487947 100644 --- a/src/java.desktop/share/classes/sun/awt/util/ThreadGroupUtils.java +++ b/src/java.desktop/share/classes/sun/awt/util/ThreadGroupUtils.java @@ -39,7 +39,6 @@ private ThreadGroupUtils() { /** * Returns a root thread group. - * Should be called with {@link sun.security.util.SecurityConstants#MODIFY_THREADGROUP_PERMISSION} * * @return a root {@code ThreadGroup} */ diff --git a/src/java.desktop/share/classes/sun/font/TrueTypeFont.java b/src/java.desktop/share/classes/sun/font/TrueTypeFont.java index a44a013b7492f..8b7f9b95f5c56 100644 --- a/src/java.desktop/share/classes/sun/font/TrueTypeFont.java +++ b/src/java.desktop/share/classes/sun/font/TrueTypeFont.java @@ -45,7 +45,6 @@ import sun.java2d.Disposer; import sun.java2d.DisposerRecord; -import sun.security.action.GetPropertyAction; /** * TrueTypeFont is not called SFntFont because it is not expected diff --git a/src/java.desktop/share/classes/sun/java2d/marlin/MarlinUtils.java b/src/java.desktop/share/classes/sun/java2d/marlin/MarlinUtils.java index 05ea55f170bdd..49f5ab613a87a 100644 --- a/src/java.desktop/share/classes/sun/java2d/marlin/MarlinUtils.java +++ b/src/java.desktop/share/classes/sun/java2d/marlin/MarlinUtils.java @@ -65,7 +65,6 @@ public static void logException(final String msg, final Throwable th) { /** * Returns a root thread group. - * Should be called with {@link sun.security.util.SecurityConstants#MODIFY_THREADGROUP_PERMISSION} * * @return a root {@code ThreadGroup} */ diff --git a/src/java.desktop/unix/classes/sun/awt/UNIXToolkit.java b/src/java.desktop/unix/classes/sun/awt/UNIXToolkit.java index 8e22441442780..5881ba55ef399 100644 --- a/src/java.desktop/unix/classes/sun/awt/UNIXToolkit.java +++ b/src/java.desktop/unix/classes/sun/awt/UNIXToolkit.java @@ -51,15 +51,11 @@ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.Arrays; import sun.awt.X11.XBaseWindow; -import sun.security.action.GetIntegerAction; import com.sun.java.swing.plaf.gtk.GTKConstants.TextDirection; import sun.java2d.opengl.OGLRenderQueue; -import sun.security.action.GetPropertyAction; public abstract class UNIXToolkit extends SunToolkit { diff --git a/src/java.desktop/unix/classes/sun/awt/X11InputMethodDescriptor.java b/src/java.desktop/unix/classes/sun/awt/X11InputMethodDescriptor.java index d0502505dc6df..f05419feef475 100644 --- a/src/java.desktop/unix/classes/sun/awt/X11InputMethodDescriptor.java +++ b/src/java.desktop/unix/classes/sun/awt/X11InputMethodDescriptor.java @@ -30,10 +30,8 @@ import java.awt.Toolkit; import java.awt.im.spi.InputMethod; import java.awt.im.spi.InputMethodDescriptor; -import java.security.AccessController; import java.util.Locale; import sun.awt.SunToolkit; -import sun.security.action.GetPropertyAction; /** * Provides sufficient information about an input method From 10def484dfe5821940c6fef6d857db93c30d0b06 Mon Sep 17 00:00:00 2001 From: Jaikiran Pai Date: Thu, 21 Nov 2024 05:01:52 +0000 Subject: [PATCH 62/74] 8344236: Revisit SecurityManager usage in jdk.net after JEP 486 integration Reviewed-by: dfuchs --- .../aix/classes/jdk/net/AIXSocketOptions.java | 15 +++------------ .../linux/classes/jdk/net/LinuxSocketOptions.java | 15 +++------------ .../classes/jdk/net/MacOSXSocketOptions.java | 15 +++------------ src/jdk.net/share/classes/jdk/nio/Channels.java | 7 ------- .../classes/jdk/net/WindowsSocketOptions.java | 15 +++------------ 5 files changed, 12 insertions(+), 55 deletions(-) diff --git a/src/jdk.net/aix/classes/jdk/net/AIXSocketOptions.java b/src/jdk.net/aix/classes/jdk/net/AIXSocketOptions.java index 086c346ff8f97..604386b371806 100644 --- a/src/jdk.net/aix/classes/jdk/net/AIXSocketOptions.java +++ b/src/jdk.net/aix/classes/jdk/net/AIXSocketOptions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2024, 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 @@ -27,12 +27,10 @@ import java.net.SocketException; import java.nio.file.attribute.UserPrincipal; import java.nio.file.attribute.GroupPrincipal; -import java.security.AccessController; -import java.security.PrivilegedAction; import jdk.net.ExtendedSocketOptions.PlatformSocketOptions; import sun.nio.fs.UnixUserPrincipals; -@SuppressWarnings({"removal", "restricted"}) +@SuppressWarnings("restricted") class AIXSocketOptions extends PlatformSocketOptions { public AIXSocketOptions() { @@ -131,13 +129,6 @@ UnixDomainPrincipal getSoPeerCred(int fd) throws SocketException { private static native boolean keepAliveOptionsSupported0(); private static native boolean quickAckSupported0(); static { - if (System.getSecurityManager() == null) { - System.loadLibrary("extnet"); - } else { - AccessController.doPrivileged((PrivilegedAction) () -> { - System.loadLibrary("extnet"); - return null; - }); - } + System.loadLibrary("extnet"); } } diff --git a/src/jdk.net/linux/classes/jdk/net/LinuxSocketOptions.java b/src/jdk.net/linux/classes/jdk/net/LinuxSocketOptions.java index 8d3ceeebfa9a3..bffe094ea453d 100644 --- a/src/jdk.net/linux/classes/jdk/net/LinuxSocketOptions.java +++ b/src/jdk.net/linux/classes/jdk/net/LinuxSocketOptions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2024, 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 @@ -27,12 +27,10 @@ import java.net.SocketException; import java.nio.file.attribute.UserPrincipal; import java.nio.file.attribute.GroupPrincipal; -import java.security.AccessController; -import java.security.PrivilegedAction; import jdk.net.ExtendedSocketOptions.PlatformSocketOptions; import sun.nio.fs.UnixUserPrincipals; -@SuppressWarnings({"removal", "restricted"}) +@SuppressWarnings("restricted") class LinuxSocketOptions extends PlatformSocketOptions { public LinuxSocketOptions() { @@ -143,14 +141,7 @@ UnixDomainPrincipal getSoPeerCred(int fd) throws SocketException { private static native boolean incomingNapiIdSupported0(); private static native int getIncomingNapiId0(int fd) throws SocketException; static { - if (System.getSecurityManager() == null) { - System.loadLibrary("extnet"); - } else { - AccessController.doPrivileged((PrivilegedAction) () -> { - System.loadLibrary("extnet"); - return null; - }); - } + System.loadLibrary("extnet"); } } diff --git a/src/jdk.net/macosx/classes/jdk/net/MacOSXSocketOptions.java b/src/jdk.net/macosx/classes/jdk/net/MacOSXSocketOptions.java index c2912e8b80808..23055954b212a 100644 --- a/src/jdk.net/macosx/classes/jdk/net/MacOSXSocketOptions.java +++ b/src/jdk.net/macosx/classes/jdk/net/MacOSXSocketOptions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, 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 @@ -27,12 +27,10 @@ import java.net.SocketException; import java.nio.file.attribute.UserPrincipal; import java.nio.file.attribute.GroupPrincipal; -import java.security.AccessController; -import java.security.PrivilegedAction; import jdk.net.ExtendedSocketOptions.PlatformSocketOptions; import sun.nio.fs.UnixUserPrincipals; -@SuppressWarnings({"removal", "restricted"}) +@SuppressWarnings("restricted") class MacOSXSocketOptions extends PlatformSocketOptions { public MacOSXSocketOptions() { @@ -116,13 +114,6 @@ UnixDomainPrincipal getSoPeerCred(int fd) throws SocketException { private static native boolean ipDontFragmentSupported0(); static { - if (System.getSecurityManager() == null) { - System.loadLibrary("extnet"); - } else { - AccessController.doPrivileged((PrivilegedAction) () -> { - System.loadLibrary("extnet"); - return null; - }); - } + System.loadLibrary("extnet"); } } diff --git a/src/jdk.net/share/classes/jdk/nio/Channels.java b/src/jdk.net/share/classes/jdk/nio/Channels.java index fbbbaa2b3a47a..fa15cf189fd3a 100644 --- a/src/jdk.net/share/classes/jdk/nio/Channels.java +++ b/src/jdk.net/share/classes/jdk/nio/Channels.java @@ -148,13 +148,6 @@ public static SelectableChannel readWriteSelectableChannel(FileDescriptor fd, if (!fd.valid()) throw new IllegalArgumentException("file descriptor is not valid"); - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkRead(fd); - sm.checkWrite(fd); - } - SelectorProvider provider = SelectorProvider.provider(); if (!(provider instanceof SelectorProviderImpl)) throw new UnsupportedOperationException("custom SelectorProvider"); diff --git a/src/jdk.net/windows/classes/jdk/net/WindowsSocketOptions.java b/src/jdk.net/windows/classes/jdk/net/WindowsSocketOptions.java index f5f69e205176f..ad824168e7909 100644 --- a/src/jdk.net/windows/classes/jdk/net/WindowsSocketOptions.java +++ b/src/jdk.net/windows/classes/jdk/net/WindowsSocketOptions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, 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 @@ -25,12 +25,10 @@ package jdk.net; import java.net.SocketException; -import java.security.AccessController; -import java.security.PrivilegedAction; import jdk.net.ExtendedSocketOptions.PlatformSocketOptions; -@SuppressWarnings({"removal", "restricted"}) +@SuppressWarnings("restricted") class WindowsSocketOptions extends PlatformSocketOptions { public WindowsSocketOptions() { @@ -97,13 +95,6 @@ int getTcpKeepAliveIntvl(int fd) throws SocketException { private static native int getTcpKeepAliveIntvl0(int fd) throws SocketException; static { - if (System.getSecurityManager() == null) { - System.loadLibrary("extnet"); - } else { - AccessController.doPrivileged((PrivilegedAction) () -> { - System.loadLibrary("extnet"); - return null; - }); - } + System.loadLibrary("extnet"); } } From 93aa7e2fcf87c4dc62de4ea71be543ee677b11be Mon Sep 17 00:00:00 2001 From: Richard Reingruber Date: Thu, 21 Nov 2024 06:57:09 +0000 Subject: [PATCH 63/74] 8328085: C2: Use after free in PhaseChaitin::Register_Allocate() Reviewed-by: thartmann, mdoerr --- src/hotspot/share/opto/postaloc.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/src/hotspot/share/opto/postaloc.cpp b/src/hotspot/share/opto/postaloc.cpp index ac91d8a775e02..2c1d0098b78d3 100644 --- a/src/hotspot/share/opto/postaloc.cpp +++ b/src/hotspot/share/opto/postaloc.cpp @@ -402,7 +402,6 @@ bool PhaseChaitin::eliminate_copy_of_constant(Node* val, Node* n, // as they get encountered with the merge node and keep adding these defs to the merge inputs. void PhaseChaitin::merge_multidefs() { Compile::TracePhase tp(_t_mergeMultidefs); - ResourceMark rm; // Keep track of the defs seen in registers and collect their uses in the block. RegToDefUseMap reg2defuse(_max_reg, _max_reg, RegDefUse()); for (uint i = 0; i < _cfg.number_of_blocks(); i++) { From 5ccd5106e023dbb47473e8914035c811e0cc6ee1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Galder=20Zamarre=C3=B1o?= Date: Thu, 21 Nov 2024 09:48:08 +0000 Subject: [PATCH 64/74] 8326369: Add test to verify bimorphic inlining happens after morphism changes Reviewed-by: thartmann, epeter --- ...orphicVirtualCallAfterMorphismChanged.java | 115 ++++++++++++++++++ 1 file changed, 115 insertions(+) create mode 100644 test/hotspot/jtreg/compiler/inlining/InlineBimorphicVirtualCallAfterMorphismChanged.java diff --git a/test/hotspot/jtreg/compiler/inlining/InlineBimorphicVirtualCallAfterMorphismChanged.java b/test/hotspot/jtreg/compiler/inlining/InlineBimorphicVirtualCallAfterMorphismChanged.java new file mode 100644 index 0000000000000..2f6f7f20d9d3f --- /dev/null +++ b/test/hotspot/jtreg/compiler/inlining/InlineBimorphicVirtualCallAfterMorphismChanged.java @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2024, Red Hat, Inc. All rights reserved. + * Copyright (c) 2024, JetBrains s.r.o.. 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. + * + * 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. + */ + +/** + * @test + * @bug 8339299 + * @summary C2 doesn't perform bimorphic inlining on a call site that was monomorphic during tier 3 compilation. + * @modules java.base/jdk.internal.misc + * @library /test/lib + * @requires vm.flagless + * + * @run driver compiler.inlining.InlineBimorphicVirtualCallAfterMorphismChanged + */ + +package compiler.inlining; + +import jdk.test.lib.process.OutputAnalyzer; +import jdk.test.lib.process.ProcessTools; + +public class InlineBimorphicVirtualCallAfterMorphismChanged { + public static abstract class AbstractBase { + public final int callSiteHolder() { + return inlinee(); + } + + public abstract int inlinee(); + + public static void main(String[] args) { + AbstractBase[] classes = new AbstractBase[] { firstInstance() }; + // first step: trigger a compilation while call site is monomorphic + for (int i = 0; i < 10000; i++) { + for (AbstractBase instance : classes) { + instance.callSiteHolder(); + } + } + + // second step: trigger recompilation by loading a second instance, + // also make the call site bimorphic + classes = new AbstractBase[] { firstInstance(), secondInstance() }; + for (int i = 0; i < 10000; i++) { + for (AbstractBase instance : classes) { + instance.callSiteHolder(); + } + } + } + + private static AbstractBase firstInstance() { + return new FirstClass(); + } + + private static AbstractBase secondInstance() { + return new SecondClass(); + } + } + + public final static class FirstClass extends AbstractBase { + public int inlinee() { + return 1; + } + } + + public final static class SecondClass extends AbstractBase { + public int inlinee() { + return 2; + }; + } + + public static void main(String[] args) throws Exception { + test("-XX:-TieredCompilation"); + test("-XX:+TieredCompilation"); + } + + private static void test(String option) throws Exception { + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( + "-server", "-XX:+UnlockDiagnosticVMOptions", "-XX:+PrintInlining", + "-XX:CompileCommand=compileonly,*::callSiteHolder", option, + AbstractBase.class.getName() + ); + + OutputAnalyzer analyzer = new OutputAnalyzer(pb.start()); + analyzer.shouldHaveExitValue(0); + + String re = ".*AbstractBase::inlinee.+virtual call.*"; + boolean virtualInliningFailed = analyzer.asLines().stream() + .anyMatch(s -> s.matches(re)); + + if (virtualInliningFailed) { + analyzer.outputTo(System.out); + throw new Exception( + "Bimorphic virtual call was not inlined with '" + option + "'" + ); + } + } +} From f2b10c6c228f7be879b3f043accb22e0bc6535d6 Mon Sep 17 00:00:00 2001 From: Axel Boldt-Christmas Date: Thu, 21 Nov 2024 09:54:25 +0000 Subject: [PATCH 65/74] 8340422: ZGC: TestAllocateHeapAt.java should not run with transparent hugepages Reviewed-by: stefank, jsikstro --- test/hotspot/jtreg/gc/z/TestAllocateHeapAt.java | 11 +++++++++++ .../os/THPsInThreadStackPreventionTest.java | 3 +++ .../os/TestHugePageDecisionsAtVMStartup.java | 2 ++ .../jtreg/runtime/os/TestHugePageDetection.java | 2 ++ test/jtreg-ext/requires/VMProps.java | 1 + .../lib/os/linux}/HugePageConfiguration.java | 17 ++++++++++++++--- 6 files changed, 33 insertions(+), 3 deletions(-) rename test/{hotspot/jtreg/runtime/os => lib/jdk/test/lib/os/linux}/HugePageConfiguration.java (96%) diff --git a/test/hotspot/jtreg/gc/z/TestAllocateHeapAt.java b/test/hotspot/jtreg/gc/z/TestAllocateHeapAt.java index dbcca704fab4f..f960ac3a5470f 100644 --- a/test/hotspot/jtreg/gc/z/TestAllocateHeapAt.java +++ b/test/hotspot/jtreg/gc/z/TestAllocateHeapAt.java @@ -27,13 +27,17 @@ * @test TestAllocateHeapAt * @requires vm.gc.Z & os.family == "linux" * @requires !vm.opt.final.UseLargePages + * @requires !vm.opt.final.UseTransparentHugePages * @summary Test ZGC with -XX:AllocateHeapAt * @library /test/lib * @run main/othervm gc.z.TestAllocateHeapAt . true * @run main/othervm gc.z.TestAllocateHeapAt non-existing-directory false */ +import jdk.test.lib.os.linux.HugePageConfiguration; +import jdk.test.lib.os.linux.HugePageConfiguration.ShmemTHPMode; import jdk.test.lib.process.ProcessTools; +import jtreg.SkippedException; public class TestAllocateHeapAt { public static void main(String[] args) throws Exception { @@ -42,6 +46,13 @@ public static void main(String[] args) throws Exception { final String heapBackingFile = "Heap Backing File: " + directory; final String failedToCreateFile = "Failed to create file " + directory; + final HugePageConfiguration hugePageConfiguration = HugePageConfiguration.readFromOS(); + final ShmemTHPMode mode = hugePageConfiguration.getShmemThpMode(); + + if (mode != ShmemTHPMode.never && mode != ShmemTHPMode.advise) { + throw new SkippedException("The UseTransparentHugePages option may not be respected with Shmem THP Mode: " + mode.name()); + } + ProcessTools.executeTestJava( "-XX:+UseZGC", "-Xlog:gc*", diff --git a/test/hotspot/jtreg/runtime/os/THPsInThreadStackPreventionTest.java b/test/hotspot/jtreg/runtime/os/THPsInThreadStackPreventionTest.java index 519bcc94b0120..02fb77bf2428a 100644 --- a/test/hotspot/jtreg/runtime/os/THPsInThreadStackPreventionTest.java +++ b/test/hotspot/jtreg/runtime/os/THPsInThreadStackPreventionTest.java @@ -45,10 +45,13 @@ * @requires os.family == "linux" * @requires vm.debug * @requires os.arch=="amd64" | os.arch=="x86_64" | os.arch=="aarch64" + * @library /test/lib * @modules java.base/jdk.internal.misc * java.management * @run main/manual THPsInThreadStackPreventionTest PATCH-DISABLED */ + +import jdk.test.lib.os.linux.HugePageConfiguration; import jdk.test.lib.process.OutputAnalyzer; import jdk.test.lib.process.ProcessTools; import jtreg.SkippedException; diff --git a/test/hotspot/jtreg/runtime/os/TestHugePageDecisionsAtVMStartup.java b/test/hotspot/jtreg/runtime/os/TestHugePageDecisionsAtVMStartup.java index daf1269e7ab7a..2def134b9d301 100644 --- a/test/hotspot/jtreg/runtime/os/TestHugePageDecisionsAtVMStartup.java +++ b/test/hotspot/jtreg/runtime/os/TestHugePageDecisionsAtVMStartup.java @@ -47,11 +47,13 @@ * @summary Test JVM large page setup (+THP) * @library /test/lib * @requires os.family == "linux" + * @library /test/lib * @modules java.base/jdk.internal.misc * java.management * @run driver TestHugePageDecisionsAtVMStartup -XX:+UseTransparentHugePages */ +import jdk.test.lib.os.linux.HugePageConfiguration; import jdk.test.lib.process.OutputAnalyzer; import jdk.test.lib.process.ProcessTools; import java.util.ArrayList; diff --git a/test/hotspot/jtreg/runtime/os/TestHugePageDetection.java b/test/hotspot/jtreg/runtime/os/TestHugePageDetection.java index 2e2d9092c742f..7231f30ed413e 100644 --- a/test/hotspot/jtreg/runtime/os/TestHugePageDetection.java +++ b/test/hotspot/jtreg/runtime/os/TestHugePageDetection.java @@ -28,12 +28,14 @@ * @library /test/lib * @requires vm.flagless * @requires os.family == "linux" + * @library /test/lib * @modules java.base/jdk.internal.misc * java.management * @run driver TestHugePageDetection */ import java.util.*; +import jdk.test.lib.os.linux.HugePageConfiguration; import jdk.test.lib.process.OutputAnalyzer; import jdk.test.lib.process.ProcessTools; diff --git a/test/jtreg-ext/requires/VMProps.java b/test/jtreg-ext/requires/VMProps.java index 5544ad1bebd1d..f5dcb44db2b79 100644 --- a/test/jtreg-ext/requires/VMProps.java +++ b/test/jtreg-ext/requires/VMProps.java @@ -378,6 +378,7 @@ protected void vmOptFinalFlags(SafeMap map) { vmOptFinalFlag(map, "UnlockExperimentalVMOptions"); vmOptFinalFlag(map, "UseCompressedOops"); vmOptFinalFlag(map, "UseLargePages"); + vmOptFinalFlag(map, "UseTransparentHugePages"); vmOptFinalFlag(map, "UseVectorizedMismatchIntrinsic"); } diff --git a/test/hotspot/jtreg/runtime/os/HugePageConfiguration.java b/test/lib/jdk/test/lib/os/linux/HugePageConfiguration.java similarity index 96% rename from test/hotspot/jtreg/runtime/os/HugePageConfiguration.java rename to test/lib/jdk/test/lib/os/linux/HugePageConfiguration.java index adde51ec75f15..0bb6db1602102 100644 --- a/test/hotspot/jtreg/runtime/os/HugePageConfiguration.java +++ b/test/lib/jdk/test/lib/os/linux/HugePageConfiguration.java @@ -22,6 +22,8 @@ * questions. */ +package jdk.test.lib.os.linux; + import jdk.test.lib.process.OutputAnalyzer; import java.io.*; @@ -33,7 +35,7 @@ // - a) the Operating System (the truth) // - b) the JVM log (-Xlog:pagesize) // This is used e.g. in TestHugePageDetection to determine if the JVM detects the correct settings from the OS. -class HugePageConfiguration { +public class HugePageConfiguration { public static class ExplicitHugePageConfig implements Comparable { public long pageSize = -1; @@ -63,11 +65,11 @@ public int compareTo(ExplicitHugePageConfig o) { Set _explicitHugePageConfigurations; long _explicitDefaultHugePageSize = -1; - enum THPMode {always, never, madvise} + public enum THPMode {always, never, madvise} THPMode _thpMode; long _thpPageSize; - enum ShmemTHPMode {always, within_size, advise, never, deny, force, unknown} + public enum ShmemTHPMode {always, within_size, advise, never, deny, force, unknown} ShmemTHPMode _shmemThpMode; public Set getExplicitHugePageConfigurations() { @@ -133,6 +135,15 @@ public String toString() { '}'; } + @Override + public int hashCode() { + return Objects.hash(_explicitDefaultHugePageSize, + _thpPageSize, + _explicitHugePageConfigurations, + _thpMode, + _shmemThpMode); + } + @Override public boolean equals(Object o) { if (this == o) return true; From 18df6fd5ba93c3c2d5965c072d482dcf7cbfc675 Mon Sep 17 00:00:00 2001 From: Doug Lea Date: Thu, 21 Nov 2024 11:50:46 +0000 Subject: [PATCH 66/74] 8336707: Contention of ForkJoinPool grows when stealing works Reviewed-by: vklang --- .../java/util/concurrent/ForkJoinPool.java | 729 ++++++++++-------- .../util/concurrent/ForkJoinWorkerThread.java | 35 +- 2 files changed, 420 insertions(+), 344 deletions(-) diff --git a/src/java.base/share/classes/java/util/concurrent/ForkJoinPool.java b/src/java.base/share/classes/java/util/concurrent/ForkJoinPool.java index ee2f85249d72c..0f9ccbf62840f 100644 --- a/src/java.base/share/classes/java/util/concurrent/ForkJoinPool.java +++ b/src/java.base/share/classes/java/util/concurrent/ForkJoinPool.java @@ -259,10 +259,7 @@ public class ForkJoinPool extends AbstractExecutorService { * (http://www.di.ens.fr/~zappa/readings/ppopp13.pdf) for an * analysis of memory ordering requirements in work-stealing * algorithms similar to the one used here. We use per-operation - * ordered writes of various kinds for updates, but usually use - * explicit load fences for reads, to cover access of several - * fields of possibly several objects without further constraining - * read-by-read ordering. + * ordered writes of various kinds for accesses when required. * * We also support a user mode in which local task processing is * in FIFO, not LIFO order, simply by using a local version of @@ -302,8 +299,7 @@ public class ForkJoinPool extends AbstractExecutorService { * * * Slot k must be read with an acquiring read, which it must * anyway to dereference and run the task if the (acquiring) - * CAS succeeds, but uses an explicit acquire fence to support - * the following rechecks even if the CAS is not attempted. + * CAS succeeds. * * * q.base may change between reading and using its value to * index the slot. To avoid trying to use the wrong t, the @@ -410,7 +406,11 @@ public class ForkJoinPool extends AbstractExecutorService { * * Field "runState" and per-WorkQueue field "phase" play similar * roles, as lockable, versioned counters. Field runState also - * includes monotonic event bits (SHUTDOWN, STOP, and TERMINATED). + * includes monotonic event bits: + * * SHUTDOWN: no more external tasks accepted; STOP when quiescent + * * STOP: no more tasks run, and deregister all workers + * * CLEANED: all unexecuted tasks have been cancelled + * * TERMINATED: all workers deregistered and all queues cleaned * The version tags enable detection of state changes (by * comparing two reads) modulo bit wraparound. The bit range in * each case suffices for purposes of determining quiescence, @@ -546,22 +546,27 @@ public class ForkJoinPool extends AbstractExecutorService { * * If computations are purely tree structured, it suffices for * every worker to activate another when it pushes a task into * an empty queue, resulting in O(log(#threads)) steps to full - * activation. Emptiness must be conservatively approximated - * (by checking if there is apparently at most one existing - * task) which may result in unnecessary signals. Also, to - * reduce resource usages in some cases, at the expense of - * slower startup in others, activation of an idle thread is - * preferred over creating a new one, here and elsewhere. + * activation. Emptiness must be conservatively approximated, + * which may result in unnecessary signals. Also, to reduce + * resource usages in some cases, at the expense of slower + * startup in others, activation of an idle thread is preferred + * over creating a new one, here and elsewhere. * * * At the other extreme, if "flat" tasks (those that do not in * turn generate others) come in serially from only a single - * producer, each worker taking its first (since the last - * activation) task from a queue should propagate a signal if - * there are more tasks in that queue. This is equivalent to, - * but generally faster than, arranging the stealer take - * multiple tasks, re-pushing one or more on its own queue, and - * signalling (because its queue is empty), also resulting in - * logarithmic full activation time. + * producer, each worker taking a task from a queue should + * propagate a signal if there are more tasks in that + * queue. This is equivalent to, but generally faster than, + * arranging the stealer take multiple tasks, re-pushing one or + * more on its own queue, and signalling (because its queue is + * empty), also resulting in logarithmic full activation + * time. If tasks do not not engage in unbounded loops based on + * the actions of other workers with unknown dependencies loop, + * this form of proagation can be limited to one signal per + * activation (phase change). We distinguish the cases by + * further signalling only if the task is an InterruptibleTask + * (see below), which are the only supported forms of task that + * may do so. * * * Because we don't know about usage patterns (or most commonly, * mixtures), we use both approaches, which present even more @@ -611,9 +616,12 @@ public class ForkJoinPool extends AbstractExecutorService { * it tries to deactivate()), giving up (and rescanning) on "ctl" * contention. To avoid missed signals during deactivation, the * method rescans and reactivates if there may have been a missed - * signal during deactivation. Because idle workers are often not - * yet blocked (parked), we use a WorkQueue field to advertise - * that a waiter actually needs unparking upon signal. + * (external) signal during deactivation. To reduce false-alarm + * reactivations while doing so, we scan multiple times + * (analogously to method quiescent()) before trying to + * reactivate. Because idle workers are often not yet blocked + * (parked), we use a WorkQueue field to advertise that a waiter + * actually needs unparking upon signal. * * Quiescence. Workers scan looking for work, giving up when they * don't find any, without being sure that none are available. @@ -644,22 +652,36 @@ public class ForkJoinPool extends AbstractExecutorService { * workers are inactive because the caller and any others * executing helpQuiesce are not included in counts. * - * Termination. A call to shutdownNow invokes tryTerminate to - * atomically set a runState mode bit. However, the process of - * termination is intrinsically non-atomic. The calling thread, as - * well as other workers thereafter terminating help cancel queued - * tasks and interrupt other workers. These actions race with - * unterminated workers. By default, workers check for - * termination only when accessing pool state. This may take a - * while but suffices for structured computational tasks. But not - * necessarily for others. Class InterruptibleTask (see below) - * further arranges runState checks before executing task bodies, - * and ensures interrupts while terminating. Even so, there are no - * guarantees after an abrupt shutdown that remaining tasks - * complete normally or exceptionally or are cancelled. - * Termination may fail to complete if running tasks ignore both - * task status and interrupts and/or produce more tasks after - * others that could cancel them have exited. + * Termination. Termination is initiated by setting STOP in one of + * three ways (via methods tryTerminate and quiescent): + * * A call to shutdownNow, in which case all workers are + * interrupted, first ensuring that the queues array is stable, + * to avoid missing any workers. + * * A call to shutdown when quiescent, in which case method + * releaseWaiters is used to dequeue them, at which point they notice + * STOP state and return from runWorker to deregister(); + * * The pool becomes quiescent() sometime after shutdown has + * been called, in which case releaseWaiters is also used to + * propagate as they deregister. + * Upon STOP, each worker, as well as external callers to + * tryTerminate (via close() etc) race to set CLEANED, indicating + * that all tasks have been cancelled. The implementation (method + * cleanQueues) balances cases in which there may be many tasks to + * cancel (benefitting from parallelism) versus contention and + * interference when many threads try to poll remaining queues, + * while also avoiding unnecessary rechecks, by using + * pseudorandom scans and giving up upon interference. This may be + * retried by the same caller only when there are no more + * registered workers, using the same criteria as method + * quiescent. When CLEANED and all workers have deregistered, + * TERMINATED is set, also signalling any caller of + * awaitTermination or close. Because shutdownNow-based + * termination relies on interrupts, there is no guarantee that + * workers will stop if their tasks ignore interrupts. Class + * InterruptibleTask (see below) further arranges runState checks + * before executing task bodies, and ensures interrupts while + * terminating. Even so, there are no guarantees because tasks may + * internally enter unbounded loops. * * Trimming workers. To release resources after periods of lack of * use, a worker starting to wait when the pool is quiescent will @@ -819,10 +841,11 @@ public class ForkJoinPool extends AbstractExecutorService { * overridden by system properties, we use workers of subclass * InnocuousForkJoinWorkerThread when there is a SecurityManager * present. These workers have no permissions set, do not belong - * to any user-defined ThreadGroup, and clear all ThreadLocals - * after executing any top-level task. The associated mechanics - * may be JVM-dependent and must access particular Thread class - * fields to achieve this effect. + * to any user-defined ThreadGroup, and clear all ThreadLocals and + * reset the ContextClassLoader before (re)activating to execute + * top-level task. The associated mechanics may be JVM-dependent + * and must access particular Thread class fields to achieve this + * effect. * * InterruptibleTasks * ==================== @@ -844,7 +867,9 @@ public class ForkJoinPool extends AbstractExecutorService { * shutdown, runners are interrupted so they can cancel. Since * external joining callers never run these tasks, they must await * cancellation by others, which can occur along several different - * paths. + * paths. The inability to rely on caller-runs may also require + * extra signalling (resulting in scanning and contention) so is + * done only conditionally in methods push and runworker. * * Across these APIs, rules for reporting exceptions for tasks * with results accessed via join() differ from those via get(), @@ -904,10 +929,8 @@ public class ForkJoinPool extends AbstractExecutorService { * direct false-sharing and indirect cases due to GC bookkeeping * (cardmarks etc), and reduce the number of resizes, which are * not especially fast because they require atomic transfers. - * Currently, arrays for workers are initialized to be just large - * enough to avoid resizing in most tree-structured tasks, but - * larger for external queues where both false-sharing problems - * and the need for resizing are more common. (Maintenance note: + * Currently, arrays are initialized to be just large enough to + * avoid resizing in most tree-structured tasks. (Maintenance note: * any changes in fields, queues, or their uses, or JVM layout * policies, must be accompanied by re-evaluation of these * placement and sizing decisions.) @@ -996,12 +1019,6 @@ public class ForkJoinPool extends AbstractExecutorService { */ static final int INITIAL_QUEUE_CAPACITY = 1 << 6; - /** - * Initial capacity of work-stealing queue array for external queues. - * Must be a power of two, at least 2. See above. - */ - static final int INITIAL_EXTERNAL_QUEUE_CAPACITY = 1 << 9; - // conversions among short, int, long static final int SMASK = 0xffff; // (unsigned) short bits static final long LMASK = 0xffffffffL; // lower 32 bits of long @@ -1015,8 +1032,9 @@ public class ForkJoinPool extends AbstractExecutorService { // pool.runState bits static final long STOP = 1L << 0; // terminating static final long SHUTDOWN = 1L << 1; // terminate when quiescent - static final long TERMINATED = 1L << 2; // only set if STOP also set - static final long RS_LOCK = 1L << 3; // lowest seqlock bit + static final long CLEANED = 1L << 2; // stopped and queues cleared + static final long TERMINATED = 1L << 3; // only set if STOP also set + static final long RS_LOCK = 1L << 4; // lowest seqlock bit // spin/sleep limits for runState locking and elsewhere static final int SPIN_WAITS = 1 << 7; // max calls to onSpinWait @@ -1246,9 +1264,7 @@ final boolean tryLockPhase() { // seqlock acquire */ WorkQueue(ForkJoinWorkerThread owner, int id, int cfg, boolean clearThreadLocals) { - array = new ForkJoinTask[owner == null ? - INITIAL_EXTERNAL_QUEUE_CAPACITY : - INITIAL_QUEUE_CAPACITY]; + array = new ForkJoinTask[INITIAL_QUEUE_CAPACITY]; this.owner = owner; this.config = (clearThreadLocals) ? cfg | CLEAR_TLS : cfg; } @@ -1294,10 +1310,12 @@ final void push(ForkJoinTask task, ForkJoinPool pool, unlockPhase(); if (room < 0) throw new RejectedExecutionException("Queue capacity exceeded"); - else if ((room == 0 || - a[m & (s - 2)] == null) && // at most one existing task - pool != null) - pool.signalWork(); + if ((room == 0 || // pad for InterruptibleTasks + a[m & (s - ((internal || task == null || + task.getClass().getSuperclass() != + interruptibleTaskClass) ? 1 : 2))] == null) && + pool != null) + pool.signalWork(); // may have appeared empty } } @@ -1351,10 +1369,8 @@ a, slotOffset(m & b), null)) != null) { updateBase(nb); break; } - while (b == (b = base)) { - U.loadFence(); + while (b == (b = U.getIntAcquire(this, BASE))) Thread.onSpinWait(); // spin to reduce memory traffic - } if (p - b <= 0) break; } @@ -1378,12 +1394,12 @@ final ForkJoinTask nextLocalTask() { final boolean tryUnpush(ForkJoinTask task, boolean internal) { boolean taken = false; ForkJoinTask[] a = array; - int p = top, s = p - 1, cap, k; + int p = top, s = p - 1, cap; long k; if (a != null && (cap = a.length) > 0 && - a[k = (cap - 1) & s] == task && + U.getReference(a, k = slotOffset((cap - 1) & s)) == task && (internal || tryLockPhase())) { if (top == p && - U.compareAndSetReference(a, slotOffset(k), task, null)) { + U.compareAndSetReference(a, k, task, null)) { taken = true; updateTop(s); } @@ -1417,28 +1433,25 @@ final ForkJoinTask peek() { * Polls for a task. Used only by non-owners. */ final ForkJoinTask poll() { - for (int b = base;;) { - int cap, k, nb; ForkJoinTask[] a; + for (int pb = -1, b; ; pb = b) { // track progress + ForkJoinTask t; int cap, nb; long k; ForkJoinTask[] a; if ((a = array) == null || (cap = a.length) <= 0) break; - long kp = slotOffset(k = (cap - 1) & b); - int nk = (nb = b + 1) & (cap - 1); // next slot - int sk = (b + 2) & (cap - 1); // 2nd slot ahead - ForkJoinTask t = a[k]; - U.loadFence(); - if (b == (b = base)) { // else inconsistent - if (t != null) { - if (U.compareAndSetReference(a, kp, t, null)) { - updateBase(nb); - return t; - } - b = base; - } - else if (a[sk] == null && a[nk] == null && a[k] == null) { - if (top - b <= 0) - break; // empty + t = (ForkJoinTask)U.getReferenceAcquire( + a, k = slotOffset((cap - 1) & (b = base))); + Object u = U.getReference( // next slot + a, slotOffset((cap - 1) & (nb = b + 1))); + if (base != b) // inconsistent + ; + else if (t == null) { + if (u == null && top - b <= 0) + break; // empty + if (pb == b) Thread.onSpinWait(); // stalled - } + } + else if (U.compareAndSetReference(a, k, t, null)) { + updateBase(nb); + return t; } } return null; @@ -1449,14 +1462,11 @@ else if (a[sk] == null && a[nk] == null && a[k] == null) { /** * Runs the given task, as well as remaining local tasks. */ - final void topLevelExec(ForkJoinTask task, int cfg) { - int fifo = cfg & FIFO; + final void topLevelExec(ForkJoinTask task, int fifo) { while (task != null) { task.doExec(); task = nextLocalTask(fifo); } - if ((cfg & CLEAR_TLS) != 0) - ThreadLocalRandom.eraseThreadLocals(Thread.currentThread()); } /** @@ -1468,23 +1478,24 @@ final void tryRemoveAndExec(ForkJoinTask task, boolean internal) { int b = base, p = top, s = p - 1, d = p - b, cap; if (a != null && (cap = a.length) > 0) { for (int m = cap - 1, i = s; d > 0; --i, --d) { - ForkJoinTask t; int k; boolean taken; - if ((t = a[k = i & m]) == null) + long k; boolean taken; + ForkJoinTask t = (ForkJoinTask)U.getReference( + a, k = slotOffset(i & m)); + if (t == null) break; if (t == task) { - long pos = slotOffset(k); if (!internal && !tryLockPhase()) break; // fail if locked if (taken = (top == p && - U.compareAndSetReference(a, pos, task, null))) { + U.compareAndSetReference(a, k, task, null))) { if (i == s) // act as pop updateTop(s); else if (i == base) // act as poll updateBase(i + 1); else { // swap with top U.putReferenceVolatile( - a, pos, (ForkJoinTask) + a, k, (ForkJoinTask) U.getAndSetReference( a, slotOffset(s & m), null)); updateTop(s); @@ -1512,19 +1523,18 @@ final int helpComplete(ForkJoinTask task, boolean internal, int limit) { int status = 0; if (task != null) { outer: for (;;) { - ForkJoinTask[] a; ForkJoinTask t; boolean taken; - int stat, p, s, cap, k; + ForkJoinTask[] a; boolean taken; Object o; + int stat, p, s, cap; if ((stat = task.status) < 0) { status = stat; break; } if ((a = array) == null || (cap = a.length) <= 0) break; - if ((t = a[k = (cap - 1) & (s = (p = top) - 1)]) == null) + long k = slotOffset((cap - 1) & (s = (p = top) - 1)); + if (!((o = U.getReference(a, k)) instanceof CountedCompleter)) break; - if (!(t instanceof CountedCompleter)) - break; - CountedCompleter f = (CountedCompleter)t; + CountedCompleter t = (CountedCompleter)o, f = t; for (int steps = cap;;) { // bound path if (f == task) break; @@ -1535,7 +1545,7 @@ final int helpComplete(ForkJoinTask task, boolean internal, int limit) { break; if (taken = (top == p && - U.compareAndSetReference(a, slotOffset(k), t, null))) + U.compareAndSetReference(a, k, t, null))) updateTop(s); if (!internal) unlockPhase(); @@ -1557,11 +1567,11 @@ final int helpComplete(ForkJoinTask task, boolean internal, int limit) { */ final void helpAsyncBlocker(ManagedBlocker blocker) { for (;;) { - ForkJoinTask[] a; int b, cap, k; + ForkJoinTask t; ForkJoinTask[] a; int b, cap; long k; if ((a = array) == null || (cap = a.length) <= 0) break; - ForkJoinTask t = a[k = (b = base) & (cap - 1)]; - U.loadFence(); + t = (ForkJoinTask)U.getReferenceAcquire( + a, k = slotOffset((cap - 1) & (b = base))); if (t == null) { if (top - b <= 0) break; @@ -1572,7 +1582,7 @@ else if (!(t instanceof CompletableFuture if (blocker != null && blocker.isReleasable()) break; if (base == b && t != null && - U.compareAndSetReference(a, slotOffset(k), t, null)) { + U.compareAndSetReference(a, k, t, null)) { updateBase(b + 1); t.doExec(); } @@ -1581,6 +1591,18 @@ else if (!(t instanceof CompletableFuture // misc + /** + * Cancels all local tasks. Called only by owner. + */ + final void cancelTasks() { + for (ForkJoinTask t; (t = nextLocalTask(0)) != null; ) { + try { + t.cancel(false); + } catch (Throwable ignore) { + } + } + } + /** * Returns true if internal and not known to be blocked. */ @@ -1630,6 +1652,16 @@ final boolean isApparentlyUnblocked() { */ static volatile RuntimePermission modifyThreadPermission; + /** + * Cached for faster type tests. + */ + static final Class interruptibleTaskClass; + + /** + * For VirtualThread intrinsics + */ + private static final JavaLangAccess JLA; + // fields declared in order of their likely layout on most VMs volatile CountDownLatch termination; // lazily constructed final Predicate saturate; @@ -1773,7 +1805,7 @@ final String nextWorkerThreadName() { * @param w caller's WorkQueue */ final void registerWorker(WorkQueue w) { - if (w != null) { + if (w != null && (runState & STOP) == 0L) { ThreadLocalRandom.localInit(); int seed = w.stackPred = ThreadLocalRandom.getProbe(); int phaseSeq = seed & ~((IDLE << 1) - 1); // initial phase tag @@ -1824,49 +1856,35 @@ final void registerWorker(WorkQueue w) { * @param ex the exception causing failure, or null if none */ final void deregisterWorker(ForkJoinWorkerThread wt, Throwable ex) { - if ((runState & STOP) != 0L) // ensure released - releaseAll(); - WorkQueue w = null; - int src = 0, phase = 0; - boolean replaceable = false; - if (wt != null && (w = wt.workQueue) != null) { - phase = w.phase; - if ((src = w.source) != DROPPED) { - w.source = DROPPED; // else already dropped - if (phase != 0) { // else failed to start - replaceable = true; - if (w.top - w.base > 0) { - ForkJoinTask t; // cancel remaining tasks - while ((t = w.nextLocalTask()) != null) { - try { - t.cancel(false); - } catch (Throwable ignore) { - } - } - } - } - } - } - if (src != DROPPED) { // decrement counts - long c = ctl; + WorkQueue w = null; // null if not created + int phase = 0; // 0 if not registered + if (wt != null && (w = wt.workQueue) != null && + (phase = w.phase) != 0 && (phase & IDLE) != 0) + releaseWaiters(); // ensure released + if (w == null || w.source != DROPPED) { + long c = ctl; // decrement counts do {} while (c != (c = compareAndExchangeCtl( c, ((RC_MASK & (c - RC_UNIT)) | (TC_MASK & (c - TC_UNIT)) | (LMASK & c))))); } - if ((tryTerminate(false, false) & STOP) == 0L && w != null) { - WorkQueue[] qs; int n, i; // remove index unless terminating + if (phase != 0 && w != null) { // remove index unless terminating long ns = w.nsteals & 0xffffffffL; - if ((lockRunState() & STOP) != 0L) - replaceable = false; - else if ((qs = queues) != null && (n = qs.length) > 0 && - qs[i = phase & SMASK & (n - 1)] == w) { - qs[i] = null; - stealCount += ns; // accumulate steals + if ((runState & STOP) == 0L) { + WorkQueue[] qs; int n, i; + if ((lockRunState() & STOP) == 0L && + (qs = queues) != null && (n = qs.length) > 0 && + qs[i = phase & SMASK & (n - 1)] == w) { + qs[i] = null; + stealCount += ns; // accumulate steals + } + unlockRunState(); } - unlockRunState(); - if (replaceable) - signalWork(); + } + if ((tryTerminate(false, false) & STOP) == 0L && + phase != 0 && w != null && w.source != DROPPED) { + signalWork(); // possibly replace + w.cancelTasks(); // clean queue } if (ex != null) ForkJoinTask.rethrow(ex); @@ -1912,12 +1930,9 @@ else if ((v = w) == null) /** * Releases all waiting workers. Called only during shutdown. - * - * @return current ctl */ - private long releaseAll() { - long c = ctl; - for (;;) { + private void releaseWaiters() { + for (long c = ctl;;) { WorkQueue[] qs; WorkQueue v; int sp, i; if ((sp = (int)c) == 0 || (qs = queues) == null || qs.length <= (i = sp & SMASK) || (v = qs[i]) == null) @@ -1930,7 +1945,6 @@ private long releaseAll() { U.unpark(v.owner); } } - return c; } /** @@ -1940,7 +1954,7 @@ private long releaseAll() { * unlocked; if so, setting STOP if shutdown is enabled */ private int quiescent() { - outer: for (;;) { + for (;;) { long phaseSum = 0L; boolean swept = false; for (long e, prevRunState = 0L; ; prevRunState = e) { @@ -1983,64 +1997,61 @@ else if (compareAndSetCtl(c, c) && casRunState(e, e | STOP)) final void runWorker(WorkQueue w) { if (w != null) { int phase = w.phase, r = w.stackPred; // seed from registerWorker - int cfg = w.config, src = -1, nsteals = 0; - rescan: for (boolean scanned = false;;) { + int fifo = w.config & FIFO, nsteals = 0, src = -1; + for (;;) { WorkQueue[] qs; r ^= r << 13; r ^= r >>> 17; r ^= r << 5; // xorshift if ((runState & STOP) != 0L || (qs = queues) == null) - return; + break; int n = qs.length, i = r, step = (r >>> 16) | 1; - for (int l = n; l > 0; --l, i += step) { // scan queues - int j; WorkQueue q; - if ((q = qs[j = i & (n - 1)]) != null) { - boolean taken = false; - for (int pb = -1, b = q.base;;) { - int cap, k, nb; ForkJoinTask[] a; - if ((a = q.array) == null || (cap = a.length) <= 0) - continue rescan; - long kp = slotOffset(k = (cap - 1) & b); - int nk = (nb = b + 1) & (cap - 1); // next slot - int sk = (b + 2) & (cap - 1); // 2nd slot ahead - ForkJoinTask t = a[k]; - U.loadFence(); - if (b != (b = q.base)) - ; // inconsistent - else if (t == null) { // possibly empty - if (a[sk] == null && a[nk] == null && - a[k] == null) { // screen - if (q.top - b > 0) { // stalled - if (!taken) // move unless taking - continue rescan; + boolean rescan = false; + scan: for (int l = n; l > 0; --l, i += step) { // scan queues + int j, cap; WorkQueue q; ForkJoinTask[] a; + if ((q = qs[j = i & (n - 1)]) != null && + (a = q.array) != null && (cap = a.length) > 0) { + for (int m = cap - 1, pb = -1, b = q.base;;) { + ForkJoinTask t; long k; + t = (ForkJoinTask)U.getReferenceAcquire( + a, k = slotOffset(m & b)); + if (b != (b = q.base) || t == null || + !U.compareAndSetReference(a, k, t, null)) { + if (a[b & m] == null) { + if (rescan) // end of run + break scan; + if (a[(b + 1) & m] == null && + a[(b + 2) & m] == null) { + break; // probably empty + } + if (pb == (pb = b)) { // track progress + rescan = true; // stalled; reorder scan + break scan; } - else if (taken) - continue rescan; // depleted; restart - else - break; // empty } - if (pb == (pb = b)) // base unchanged - Thread.onSpinWait(); } - else if (!U.compareAndSetReference(a, kp, t, null)) - b = q.base; // contended else { - q.base = nb; + boolean propagate; + int nb = q.base = b + 1; w.nsteals = ++nsteals; - w.source = j; // volatile write - if (taken != (taken = true) && a[nk] != null) - signalWork(); // propagate signal - w.topLevelExec(t, cfg); - if ((b = q.base) != nb && src != (src = j)) - continue rescan; // reduce interference + w.source = j; // volatile + rescan = true; + if (propagate = + ((src != (src = j) || + t.getClass().getSuperclass() == + interruptibleTaskClass) && + a[nb & m] != null)) + signalWork(); + w.topLevelExec(t, fifo); + if ((b = q.base) != nb && !propagate) + break scan; // reduce interference } } } } - if (!scanned) - scanned = true; // rescan before deactivate - else if (((phase = deactivate(w, r, phase)) & IDLE) == 0) - scanned = false; - else - return; + if (!rescan) { + if (((phase = deactivate(w, phase)) & IDLE) != 0) + break; + src = -1; // re-enable propagation + } } } } @@ -2049,56 +2060,38 @@ else if (((phase = deactivate(w, r, phase)) & IDLE) == 0) * Deactivates and if necessary awaits signal or termination. * * @param w the worker - * @param r random seed * @param phase current phase * @return current phase, with IDLE set if worker should exit */ - private int deactivate(WorkQueue w, int r, int phase) { + private int deactivate(WorkQueue w, int phase) { + if (w == null) // currently impossible + return IDLE; int p = phase | IDLE, activePhase = phase + (IDLE << 1); - if (w != null) { // always true - w.phase = p; - long pc = ctl, qc; - for (;;) { // try to enqueue - w.stackPred = (int)pc; // set ctl stack link - qc = (activePhase & LMASK) | ((pc - RC_UNIT) & UMASK); - if (pc == (pc = compareAndExchangeCtl(pc, qc))) // success - break; - if ((pc & RC_MASK) >= (qc & RC_MASK)) { - p = w.phase = phase; // back out on possible signal - break; - } - } - if (p != phase && // check quiescent termination - ((runState & SHUTDOWN) == 0L || quiescent() <= 0)) { - WorkQueue[] qs; - int spins = ((short)(qc >>> TC_SHIFT) << 1) + SPIN_WAITS + 1; - while ((p = w.phase) != activePhase && --spins > 0) - Thread.onSpinWait(); // reduce flailing - if (p != activePhase && (qs = queues) != null) { - int n = qs.length, step = (r >>> 16) | 1; - for (int i = r, l = n; l > 0; --l, i += step) { - WorkQueue q; // check for missed signals - if ((q = qs[i & (n - 1)]) != null && - q.top - q.base > 0) { - if (ctl == qc && compareAndSetCtl(qc, pc)) { - p = w.phase = activePhase; - break; // self-signal - } - if ((p = w.phase) == activePhase) - break; - } - } - if (p != activePhase) { - long delay = (((qc & RC_MASK) > 0L) ? 0L : - (w.source != INVALID_ID) ? keepAlive : - TIMEOUT_SLOP); // minimal delay if cascade - if ((p = w.phase) != activePhase) - p = awaitWork(w, p, delay); // block, drop, or exit - } - } - } + long pc = ctl, qc = (activePhase & LMASK) | ((pc - RC_UNIT) & UMASK); + w.stackPred = (int)pc; // set ctl stack link + w.phase = p; + if (!compareAndSetCtl(pc, qc)) // try to enqueue + return w.phase = phase; // back out on possible signal + int ac = (short)(qc >>> RC_SHIFT), n; long e; WorkQueue[] qs; + if (((e = runState) & STOP) != 0L || + ((e & SHUTDOWN) != 0L && ac == 0 && quiescent() > 0) || + (qs = queues) == null || (n = qs.length) <= 0) + return IDLE; // terminating + int prechecks = Math.min(ac, 2); // reactivation threshold + for (int k = Math.max(n + (n << 1), SPIN_WAITS << 1);;) { + WorkQueue q; int cap; ForkJoinTask[] a; + if (w.phase == activePhase) + return activePhase; + if (--k < 0) + return awaitWork(w, p); // block, drop, or exit + if ((k & 1) != 0) + Thread.onSpinWait(); // interleave spins and rechecks + else if ((q = qs[k & (n - 1)]) != null && + (a = q.array) != null && (cap = a.length) > 0 && + a[q.base & (cap - 1)] != null && --prechecks < 0 && + ctl == qc && compareAndSetCtl(qc, pc)) + return w.phase = activePhase; // reactivate } - return p; } /** @@ -2106,33 +2099,41 @@ private int deactivate(WorkQueue w, int r, int phase) { * * @param w the work queue * @param p current phase (known to be idle) - * @param delay if nonzero keepAlive before trimming if quiescent * @return current phase, with IDLE set if worker should exit */ - private int awaitWork(WorkQueue w, int p, long delay) { + private int awaitWork(WorkQueue w, int p) { if (w != null) { + ForkJoinWorkerThread t; long deadline; + if ((w.config & CLEAR_TLS) != 0 && (t = w.owner) != null) + t.resetThreadLocals(); // clear before reactivate + if ((ctl & RC_MASK) > 0L) + deadline = 0L; + else if ((deadline = + (((w.source != INVALID_ID) ? keepAlive : TIMEOUT_SLOP)) + + System.currentTimeMillis()) == 0L) + deadline = 1L; // avoid zero int activePhase = p + IDLE; - LockSupport.setCurrentBlocker(this); - long deadline = (delay == 0L ? 0L : - delay + System.currentTimeMillis()); - w.parking = 1; // enable unpark - while ((p = w.phase) != activePhase) { - boolean trimmable = false; int trim; - Thread.interrupted(); // clear status - if ((runState & STOP) != 0L) - break; - if (deadline != 0L) { - if ((trim = tryTrim(w, p, deadline)) > 0) + if ((p = w.phase) != activePhase && (runState & STOP) == 0L) { + LockSupport.setCurrentBlocker(this); + w.parking = 1; // enable unpark + while ((p = w.phase) != activePhase) { + boolean trimmable = false; int trim; + Thread.interrupted(); // clear status + if ((runState & STOP) != 0L) break; - else if (trim < 0) - deadline = 0L; - else - trimmable = true; + if (deadline != 0L) { + if ((trim = tryTrim(w, p, deadline)) > 0) + break; + else if (trim < 0) + deadline = 0L; + else + trimmable = true; + } + U.park(trimmable, deadline); } - U.park(trimmable, deadline); + w.parking = 0; + LockSupport.setCurrentBlocker(null); } - w.parking = 0; - LockSupport.setCurrentBlocker(null); } return p; } @@ -2287,12 +2288,13 @@ final int helpJoin(ForkJoinTask task, WorkQueue w, boolean internal) { int j; WorkQueue q; if ((q = qs[j = r & SMASK & (n - 1)]) != null) { for (;;) { - int sq = q.source, b, cap, k; ForkJoinTask[] a; + ForkJoinTask t; ForkJoinTask[] a; + boolean eligible = false; + int sq = q.source, b, cap; long k; if ((a = q.array) == null || (cap = a.length) <= 0) break; - ForkJoinTask t = a[k = (b = q.base) & (cap - 1)]; - U.loadFence(); - boolean eligible = false; + t = (ForkJoinTask)U.getReferenceAcquire( + a, k = slotOffset((cap - 1) & (b = q.base))); if (t == task) eligible = true; else if (t != null) { // check steal chain @@ -2311,18 +2313,16 @@ else if (t != null) { // check steal chain } if ((s = task.status) < 0) break outer; // validate - if (q.source == sq && q.base == b && a[k] == t) { - int nb = b + 1, nk = nb & (cap - 1); + if (q.source == sq && q.base == b && + U.getReference(a, k) == t) { if (!eligible) { // revisit if nonempty - if (!rescan && t == null && - (a[nk] != null || q.top - b > 0)) + if (!rescan && t == null && q.top - b > 0) rescan = true; break; } - if (U.compareAndSetReference( - a, slotOffset(k), t, null)) { - q.updateBase(nb); - w.source = j; + if (U.compareAndSetReference(a, k, t, null)) { + q.base = b + 1; + w.source = j; // volatile write t.doExec(); w.source = wsrc; rescan = true; // restart at index r @@ -2369,12 +2369,13 @@ final int helpComplete(ForkJoinTask task, WorkQueue w, boolean internal) { int j; WorkQueue q; if ((q = qs[j = r & SMASK & (n - 1)]) != null) { for (;;) { - ForkJoinTask[] a; int b, cap, k; + ForkJoinTask t; ForkJoinTask[] a; + int b, cap, nb; long k; + boolean eligible = false; if ((a = q.array) == null || (cap = a.length) <= 0) break; - ForkJoinTask t = a[k = (b = q.base) & (cap - 1)]; - U.loadFence(); - boolean eligible = false; + t = (ForkJoinTask)U.getReferenceAcquire( + a, k = slotOffset((cap - 1) & (b = q.base))); if (t instanceof CountedCompleter) { CountedCompleter f = (CountedCompleter)t; for (int steps = cap; steps > 0; --steps) { @@ -2389,19 +2390,17 @@ final int helpComplete(ForkJoinTask task, WorkQueue w, boolean internal) { if ((s = task.status) < 0) // validate break outer; if (q.base == b) { - int nb = b + 1, nk = nb & (cap - 1); if (eligible) { if (U.compareAndSetReference( - a, slotOffset(k), t, null)) { - q.updateBase(nb); + a, k, t, null)) { + q.updateBase(b + 1); t.doExec(); locals = rescan = true; break scan; } } - else if (a[k] == t) { - if (!rescan && t == null && - (a[nk] != null || q.top - b > 0)) + else if (U.getReference(a, k) == t) { + if (!rescan && t == null && q.top - b > 0) rescan = true; // revisit break; } @@ -2454,14 +2453,15 @@ private int helpQuiesce(WorkQueue w, long nanos, boolean interruptible) { int j; WorkQueue q; if ((q = qs[j = r & SMASK & (n - 1)]) != null && q != w) { for (;;) { - ForkJoinTask[] a; int b, cap, k; + ForkJoinTask t; ForkJoinTask[] a; + int b, cap; long k; if ((a = q.array) == null || (cap = a.length) <= 0) break; - ForkJoinTask t = a[k = (b = q.base) & (cap - 1)]; + t = (ForkJoinTask)U.getReferenceAcquire( + a, k = slotOffset((cap - 1) & (b = q.base))); if (t != null && phase == inactivePhase) // reactivate w.phase = phase = activePhase; - U.loadFence(); - if (q.base == b && a[k] == t) { + if (q.base == b && U.getReference(a, k) == t) { int nb = b + 1; if (t == null) { if (!rescan) { @@ -2474,10 +2474,9 @@ else if (mq == 1) } break; } - if (U.compareAndSetReference( - a, slotOffset(k), t, null)) { - q.updateBase(nb); - w.source = j; + if (U.compareAndSetReference(a, k, t, null)) { + q.base = nb; + w.source = j; // volatile write t.doExec(); w.source = wsrc; rescan = locals = true; @@ -2603,15 +2602,15 @@ private WorkQueue submissionQueue(int r) { if (w == null) w = new WorkQueue(null, id, 0, false); w.phase = id; - long stop = lockRunState() & STOP; - if (stop == 0L && queues == qs && qs[i] == null) { + long isShutdown = lockRunState() & SHUTDOWN; + if (isShutdown == 0L && queues == qs && qs[i] == null) { q = qs[i] = w; // else retry w = null; } unlockRunState(); if (q != null) return q; - if (stop != 0L) + if (isShutdown != 0L) break; } else if (!q.tryLockPhase()) // move index @@ -2623,7 +2622,6 @@ else if ((runState & SHUTDOWN) != 0L) { else return q; } - tryTerminate(false, false); throw new RejectedExecutionException(); } @@ -2640,7 +2638,6 @@ private void poolSubmit(boolean signalIfEmpty, ForkJoinTask task) { } q.push(task, signalIfEmpty ? this : null, internal); } - private static final JavaLangAccess JLA = SharedSecrets.getJavaLangAccess(); /** * Returns queue for an external submission, bypassing call to @@ -2760,49 +2757,94 @@ static int getSurplusQueuedTaskCount() { * @return runState on exit */ private long tryTerminate(boolean now, boolean enable) { - long e = runState, isShutdown; - if ((e & STOP) == 0L) { - if (now) - runState = e = (lockRunState() + RS_LOCK) | STOP | SHUTDOWN; - else if ((isShutdown = (e & SHUTDOWN)) != 0 || enable) { - if (isShutdown == 0) - getAndBitwiseOrRunState(SHUTDOWN); - if (quiescent() > 0) - e = runState; - } - if ((e & STOP) != 0L && (releaseAll() & RC_MASK) > 0L && now) + long e, isShutdown, ps; + if (((e = runState) & TERMINATED) != 0L) + now = false; + else if ((e & STOP) != 0L) + now = true; + else if (now) { + if (((ps = getAndBitwiseOrRunState(SHUTDOWN|STOP) & STOP)) == 0L) { + if ((ps & RS_LOCK) != 0L) { + spinLockRunState(); // ensure queues array stable after stop + unlockRunState(); + } interruptAll(); + } } - if ((e & (STOP | TERMINATED)) == STOP) { // help cancel tasks - if ((ctl & RC_MASK) > 0L) { // unless all inactive - int r = (int)Thread.currentThread().threadId(); - WorkQueue[] qs = queues; // stagger traversals - int n = (qs == null) ? 0 : qs.length; - for (int l = n; l > 0; --l, ++r) { - WorkQueue q; ForkJoinTask t; - if ((q = qs[r & (n - 1)]) != null && - q.source != DROPPED) { - while ((t = q.poll()) != null) { - try { - t.cancel(false); - } catch (Throwable ignore) { - } - } + else if ((isShutdown = (e & SHUTDOWN)) != 0L || enable) { + if (isShutdown == 0L) + getAndBitwiseOrRunState(SHUTDOWN); + if (quiescent() > 0) + now = true; + } + + if (now) { + releaseWaiters(); + for (;;) { + if (((e = runState) & CLEANED) == 0L) { + boolean clean = cleanQueues(); + if (((e = runState) & CLEANED) == 0L && clean) + e = getAndBitwiseOrRunState(CLEANED) | CLEANED; + } + if ((e & TERMINATED) != 0L) + break; + if (ctl != 0L) // else loop if didn't finish cleaning + break; + if ((e & CLEANED) != 0L) { + e |= TERMINATED; + if ((getAndBitwiseOrRunState(TERMINATED) & TERMINATED) == 0L) { + CountDownLatch done; SharedThreadContainer ctr; + if ((done = termination) != null) + done.countDown(); + if ((ctr = container) != null) + ctr.close(); } + break; } } - if (((e = runState) & TERMINATED) == 0L && ctl == 0L) { - e |= TERMINATED; - if ((getAndBitwiseOrRunState(TERMINATED) & TERMINATED) == 0L) { - CountDownLatch done; SharedThreadContainer ctr; - if ((done = termination) != null) - done.countDown(); - if ((ctr = container) != null) - ctr.close(); + } + return e; + } + + /** + * Scans queues in a psuedorandom order based on thread id, + * cancelling tasks until empty, or returning early upon + * interference or still-active external queues, in which case + * other calls will finish cancellation. + * + * @return true if all queues empty + */ + private boolean cleanQueues() { + int r = (int)Thread.currentThread().threadId(); + r ^= r << 13; r ^= r >>> 17; r ^= r << 5; // xorshift + int step = (r >>> 16) | 1; // randomize traversals + WorkQueue[] qs = queues; + int n = (qs == null) ? 0 : qs.length; + for (int l = n; l > 0; --l, r += step) { + WorkQueue q; ForkJoinTask[] a; int cap; + if ((q = qs[r & (n - 1)]) != null && + (a = q.array) != null && (cap = a.length) > 0) { + for (;;) { + ForkJoinTask t; int b; long k; + t = (ForkJoinTask)U.getReferenceAcquire( + a, k = slotOffset((cap - 1) & (b = q.base))); + if (q.base == b && t != null && + U.compareAndSetReference(a, k, t, null)) { + q.updateBase(b + 1); + try { + t.cancel(false); + } catch (Throwable ignore) { + } + } + else if ((q.phase & (IDLE|1)) == 0 || // externally locked + q.top - q.base > 0) + return false; // incomplete + else + break; } } } - return e; + return true; } /** @@ -2814,8 +2856,7 @@ private void interruptAll() { int n = (qs == null) ? 0 : qs.length; for (int i = 1; i < n; i += 2) { WorkQueue q; Thread o; - if ((q = qs[i]) != null && (o = q.owner) != null && o != current && - q.source != DROPPED) { + if ((q = qs[i]) != null && (o = q.owner) != null && o != current) { try { o.interrupt(); } catch (Throwable ignore) { @@ -4018,15 +4059,10 @@ protected RunnableFuture newTaskFor(Callable callable) { if ((scale & (scale - 1)) != 0) throw new Error("array index scale not a power of two"); - defaultForkJoinWorkerThreadFactory = - new DefaultForkJoinWorkerThreadFactory(); - @SuppressWarnings("removal") - ForkJoinPool p = common = (System.getSecurityManager() == null) ? - new ForkJoinPool((byte)0) : - AccessController.doPrivileged(new PrivilegedAction<>() { - public ForkJoinPool run() { - return new ForkJoinPool((byte)0); }}); + interruptibleTaskClass = ForkJoinTask.InterruptibleTask.class; + Class dep = LockSupport.class; // ensure loaded // allow access to non-public methods + JLA = SharedSecrets.getJavaLangAccess(); SharedSecrets.setJavaUtilConcurrentFJPAccess( new JavaUtilConcurrentFJPAccess() { @Override @@ -4037,6 +4073,13 @@ public void endCompensatedBlock(ForkJoinPool pool, long post) { pool.endCompensatedBlock(post); } }); - Class dep = LockSupport.class; // ensure loaded + defaultForkJoinWorkerThreadFactory = + new DefaultForkJoinWorkerThreadFactory(); + @SuppressWarnings("removal") + ForkJoinPool p = common = (System.getSecurityManager() == null) ? + new ForkJoinPool((byte)0) : + AccessController.doPrivileged(new PrivilegedAction<>() { + public ForkJoinPool run() { + return new ForkJoinPool((byte)0); }}); } } diff --git a/src/java.base/share/classes/java/util/concurrent/ForkJoinWorkerThread.java b/src/java.base/share/classes/java/util/concurrent/ForkJoinWorkerThread.java index 27b9b0812d61c..7a468666ad32f 100644 --- a/src/java.base/share/classes/java/util/concurrent/ForkJoinWorkerThread.java +++ b/src/java.base/share/classes/java/util/concurrent/ForkJoinWorkerThread.java @@ -41,6 +41,7 @@ import java.security.ProtectionDomain; import jdk.internal.access.JavaLangAccess; import jdk.internal.access.SharedSecrets; +import jdk.internal.misc.Unsafe; /** * A thread managed by a {@link ForkJoinPool}, which executes @@ -225,6 +226,25 @@ static boolean hasKnownQueuedWork() { (sq = qs[i]) != null && sq.top - sq.base > 0) || q.top - q.base > 0)); } + + /** + * Clears ThreadLocals, and if necessary resets ContextClassLoader + */ + final void resetThreadLocals() { + if (U.getReference(this, THREADLOCALS) != null) + U.putReference(this, THREADLOCALS, null); + if (U.getReference(this, INHERITABLETHREADLOCALS) != null) + U.putReference(this, INHERITABLETHREADLOCALS, null); + if ((this instanceof InnocuousForkJoinWorkerThread) && + ((InnocuousForkJoinWorkerThread)this).needCCLReset()) + super.setContextClassLoader(ClassLoader.getSystemClassLoader()); + } + + private static final Unsafe U = Unsafe.getUnsafe(); + private static final long THREADLOCALS + = U.objectFieldOffset(Thread.class, "threadLocals"); + private static final long INHERITABLETHREADLOCALS + = U.objectFieldOffset(Thread.class, "inheritableThreadLocals"); private static final JavaLangAccess JLA = SharedSecrets.getJavaLangAccess(); /** @@ -236,6 +256,7 @@ static boolean hasKnownQueuedWork() { static final class InnocuousForkJoinWorkerThread extends ForkJoinWorkerThread { /** The ThreadGroup for all InnocuousForkJoinWorkerThreads */ private static final ThreadGroup innocuousThreadGroup = createGroup(); + private boolean resetCCL; InnocuousForkJoinWorkerThread(ForkJoinPool pool) { super(innocuousThreadGroup, pool, true, true); } @@ -244,9 +265,20 @@ static final class InnocuousForkJoinWorkerThread extends ForkJoinWorkerThread { public void setUncaughtExceptionHandler(UncaughtExceptionHandler x) { } @Override // paranoically + @SuppressWarnings("removal") public void setContextClassLoader(ClassLoader cl) { - if (cl != null && ClassLoader.getSystemClassLoader() != cl) + if (System.getSecurityManager() != null && + cl != null && ClassLoader.getSystemClassLoader() != cl) throw new SecurityException("setContextClassLoader"); + resetCCL = true; + super.setContextClassLoader(cl); + } + + final boolean needCCLReset() { // get and clear + boolean needReset; + if (needReset = resetCCL) + resetCCL = false; + return needReset; } static ThreadGroup createGroup() { @@ -255,5 +287,6 @@ static ThreadGroup createGroup() { group = p; return new ThreadGroup(group, "InnocuousForkJoinWorkerThreadGroup"); } + } } From a62279ca0a520fdf4bce77dec4cb06d4d573c109 Mon Sep 17 00:00:00 2001 From: Daniel Fuchs Date: Thu, 21 Nov 2024 11:54:28 +0000 Subject: [PATCH 67/74] 8344235: Revisit SecurityManager usage in java.logging after JEP 486 and JEP 491 integration Reviewed-by: jpai --- .../jdk/internal/logger/BootstrapLogger.java | 102 ++---- .../internal/logger/DefaultLoggerFinder.java | 38 +-- .../jdk/internal/logger/LazyLoggers.java | 25 +- .../internal/logger/LoggerFinderLoader.java | 64 +--- .../internal/logger/SimpleConsoleLogger.java | 26 +- .../java/util/logging/ConsoleHandler.java | 4 +- .../java/util/logging/FileHandler.java | 84 +---- .../classes/java/util/logging/Handler.java | 157 ++------- .../classes/java/util/logging/Level.java | 8 +- .../classes/java/util/logging/LogManager.java | 307 +++++------------- .../classes/java/util/logging/LogRecord.java | 14 +- .../classes/java/util/logging/Logger.java | 47 +-- .../java/util/logging/LoggingPermission.java | 1 - .../java/util/logging/MemoryHandler.java | 49 +-- .../java/util/logging/SocketHandler.java | 34 +- .../java/util/logging/StreamHandler.java | 99 +----- .../logging/internal/LoggingProviderImpl.java | 54 +-- 17 files changed, 206 insertions(+), 907 deletions(-) diff --git a/src/java.base/share/classes/jdk/internal/logger/BootstrapLogger.java b/src/java.base/share/classes/jdk/internal/logger/BootstrapLogger.java index f351b52968d8b..a4c9e4baf639d 100644 --- a/src/java.base/share/classes/jdk/internal/logger/BootstrapLogger.java +++ b/src/java.base/share/classes/jdk/internal/logger/BootstrapLogger.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2024, 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 @@ -25,9 +25,6 @@ package jdk.internal.logger; -import java.security.AccessControlContext; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.HashMap; import java.util.Iterator; import java.util.Map; @@ -131,15 +128,8 @@ private static ExecutorService getExecutor() { @Override public Thread newThread(Runnable r) { ExecutorService owner = getExecutor(); - @SuppressWarnings("removal") - Thread thread = AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Thread run() { - Thread t = InnocuousThread.newThread(new BootstrapMessageLoggerTask(owner, r)); - t.setName("BootstrapMessageLoggerTask-"+t.getName()); - return t; - } - }, null, new RuntimePermission("enableContextClassLoaderOverride")); + Thread thread = InnocuousThread.newThread(new BootstrapMessageLoggerTask(owner, r)); + thread.setName("BootstrapMessageLoggerTask-" + thread.getName()); thread.setDaemon(true); return thread; } @@ -269,8 +259,6 @@ static final class LogEvent { // the parameters etc... we need to store the context of the // caller who logged the message - so that we can reuse it when // we finally log the message. - @SuppressWarnings("removal") - final AccessControlContext acc; // The next event in the queue LogEvent next; @@ -279,7 +267,6 @@ static final class LogEvent { private LogEvent(BootstrapLogger bootstrap, Level level, ResourceBundle bundle, String msg, Throwable thrown, Object[] params) { - this.acc = AccessController.getContext(); this.timeMillis = System.currentTimeMillis(); this.nanoAdjustment = VM.getNanoTimeAdjustment(timeMillis); this.level = level; @@ -298,7 +285,6 @@ private LogEvent(BootstrapLogger bootstrap, Level level, private LogEvent(BootstrapLogger bootstrap, Level level, Supplier msgSupplier, Throwable thrown, Object[] params) { - this.acc = AccessController.getContext(); this.timeMillis = System.currentTimeMillis(); this.nanoAdjustment = VM.getNanoTimeAdjustment(timeMillis); this.level = level; @@ -319,7 +305,6 @@ private LogEvent(BootstrapLogger bootstrap, String sourceClass, String sourceMethod, ResourceBundle bundle, String msg, Throwable thrown, Object[] params) { - this.acc = AccessController.getContext(); this.timeMillis = System.currentTimeMillis(); this.nanoAdjustment = VM.getNanoTimeAdjustment(timeMillis); this.level = null; @@ -340,7 +325,6 @@ private LogEvent(BootstrapLogger bootstrap, String sourceClass, String sourceMethod, Supplier msgSupplier, Throwable thrown, Object[] params) { - this.acc = AccessController.getContext(); this.timeMillis = System.currentTimeMillis(); this.nanoAdjustment = VM.getNanoTimeAdjustment(timeMillis); this.level = null; @@ -444,20 +428,12 @@ static LogEvent valueOf(BootstrapLogger bootstrap, Level level, Objects.requireNonNull(level), Objects.requireNonNull(msgSupplier), null, null); } - @SuppressWarnings("removal") + static void log(LogEvent log, Logger logger) { - final SecurityManager sm = System.getSecurityManager(); // not sure we can actually use lambda here. We may need to create // an anonymous class. Although if we reach here, then it means // the VM is booted. - if (sm == null || log.acc == null) { - BootstrapExecutors.submit(() -> log.log(logger)); - } else { - BootstrapExecutors.submit(() -> - AccessController.doPrivileged((PrivilegedAction) () -> { - log.log(logger); return null; - }, log.acc)); - } + BootstrapExecutors.submit(() -> log.log(logger)); } // non default methods from PlatformLogger.Bridge interface @@ -510,20 +486,9 @@ static LogEvent valueOf(BootstrapLogger bootstrap, PlatformLogger.Level level, Objects.requireNonNull(level), sourceClass, sourceMethod, msgSupplier, thrown, null); } - @SuppressWarnings("removal") + static void log(LogEvent log, PlatformLogger.Bridge logger) { - final SecurityManager sm = System.getSecurityManager(); - if (sm == null || log.acc == null) { - BootstrapExecutors.submit(() -> log.log(logger)); - } else { - // not sure we can actually use lambda here. We may need to create - // an anonymous class. Although if we reach here, then it means - // the VM is booted. - BootstrapExecutors.submit(() -> - AccessController.doPrivileged((PrivilegedAction) () -> { - log.log(logger); return null; - }, log.acc)); - } + BootstrapExecutors.submit(() -> log.log(logger)); } static void log(LogEvent event) { @@ -897,37 +862,32 @@ private LoggingBackend(boolean useLoggerFinder) { // We do not want this field to get initialized if VM.isBooted() is false. @SuppressWarnings("removal") private static final class DetectBackend { - static final LoggingBackend detectedBackend; - static { - detectedBackend = AccessController.doPrivileged(new PrivilegedAction() { - @Override - public LoggingBackend run() { - final Iterator iterator = - ServiceLoader.load(LoggerFinder.class, ClassLoader.getSystemClassLoader()) + static final LoggingBackend detectedBackend = detectBackend(); + + static LoggingBackend detectBackend() { + final Iterator iterator = + ServiceLoader.load(LoggerFinder.class, ClassLoader.getSystemClassLoader()) .iterator(); - if (iterator.hasNext()) { - return LoggingBackend.CUSTOM; // Custom Logger Provider is registered - } - // No custom logger provider: we will be using the default - // backend. - final Iterator iterator2 = - ServiceLoader.loadInstalled(DefaultLoggerFinder.class) + if (iterator.hasNext()) { + return LoggingBackend.CUSTOM; // Custom Logger Provider is registered + } + // No custom logger provider: we will be using the default + // backend. + final Iterator iterator2 = + ServiceLoader.loadInstalled(DefaultLoggerFinder.class) .iterator(); - if (iterator2.hasNext()) { - // LoggingProviderImpl is registered. The default - // implementation is java.util.logging - String cname = System.getProperty("java.util.logging.config.class"); - String fname = System.getProperty("java.util.logging.config.file"); - return (cname != null || fname != null) - ? LoggingBackend.JUL_WITH_CONFIG - : LoggingBackend.JUL_DEFAULT; - } else { - // SimpleConsoleLogger is used - return LoggingBackend.NONE; - } - } - }); - + if (iterator2.hasNext()) { + // LoggingProviderImpl is registered. The default + // implementation is java.util.logging + String cname = System.getProperty("java.util.logging.config.class"); + String fname = System.getProperty("java.util.logging.config.file"); + return (cname != null || fname != null) + ? LoggingBackend.JUL_WITH_CONFIG + : LoggingBackend.JUL_DEFAULT; + } else { + // SimpleConsoleLogger is used + return LoggingBackend.NONE; + } } } diff --git a/src/java.base/share/classes/jdk/internal/logger/DefaultLoggerFinder.java b/src/java.base/share/classes/jdk/internal/logger/DefaultLoggerFinder.java index 1d077f1531cdf..348b131b3b95b 100644 --- a/src/java.base/share/classes/jdk/internal/logger/DefaultLoggerFinder.java +++ b/src/java.base/share/classes/jdk/internal/logger/DefaultLoggerFinder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2024, 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 @@ -36,8 +36,6 @@ import java.lang.System.LoggerFinder; import java.lang.System.Logger; import java.lang.ref.ReferenceQueue; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.Collection; import java.util.ResourceBundle; @@ -70,7 +68,7 @@ * that provides the necessary configuration. * * @apiNote Programmers are not expected to call this class directly. - * Instead they should rely on the static methods defined by {@link + * Instead, they should rely on the static methods defined by {@link * java.lang.System java.lang.System} or {@link sun.util.logging.PlatformLogger * sun.util.logging.PlatformLogger}. * @@ -81,30 +79,12 @@ */ public class DefaultLoggerFinder extends LoggerFinder { - static final RuntimePermission LOGGERFINDER_PERMISSION = - new RuntimePermission("loggerFinder"); - /** * Creates a new instance of DefaultLoggerFinder. - * @throws SecurityException if the calling code does not have the - * {@code RuntimePermission("loggerFinder")} */ protected DefaultLoggerFinder() { - this(checkPermission()); - } - - private DefaultLoggerFinder(Void unused) { - // nothing to do. } - private static Void checkPermission() { - @SuppressWarnings("removal") - final SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPermission(LOGGERFINDER_PERMISSION); - } - return null; - } // SharedLoggers is a default cache of loggers used when JUL is not // present - in that case we use instances of SimpleConsoleLogger which @@ -139,23 +119,14 @@ synchronized Logger get(Function loggerSupplier, final String na static final SharedLoggers application = new SharedLoggers(); } - @SuppressWarnings("removal") public static boolean isSystem(Module m) { - return AccessController.doPrivileged(new PrivilegedAction<>() { - @Override - public Boolean run() { - // returns true if moduleCL is the platform class loader - // or one of its ancestors. - return VM.isSystemDomainLoader(m.getClassLoader()); - } - }); + return VM.isSystemDomainLoader(m.getClassLoader()); } @Override public final Logger getLogger(String name, Module module) { Objects.requireNonNull(name, "name"); Objects.requireNonNull(module, "module"); - checkPermission(); return demandLoggerFor(name, module); } @@ -176,11 +147,8 @@ public final Logger getLocalizedLogger(String name, ResourceBundle bundle, * @param name The name of the logger. * @param module The module on behalf of which the logger is created. * @return A {@link Logger logger} suitable for the application usage. - * @throws SecurityException if the calling code does not have the - * {@code RuntimePermission("loggerFinder")}. */ protected Logger demandLoggerFor(String name, Module module) { - checkPermission(); if (isSystem(module)) { return SharedLoggers.system.get(SimpleConsoleLogger::makeSimpleLogger, name); } else { diff --git a/src/java.base/share/classes/jdk/internal/logger/LazyLoggers.java b/src/java.base/share/classes/jdk/internal/logger/LazyLoggers.java index 2c62496287668..885e2e8c4d7b4 100644 --- a/src/java.base/share/classes/jdk/internal/logger/LazyLoggers.java +++ b/src/java.base/share/classes/jdk/internal/logger/LazyLoggers.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2024, 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 @@ -25,8 +25,6 @@ package jdk.internal.logger; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.function.BiFunction; import java.lang.System.LoggerFinder; import java.lang.System.Logger; @@ -44,9 +42,6 @@ */ public final class LazyLoggers { - static final RuntimePermission LOGGERFINDER_PERMISSION = - new RuntimePermission("loggerFinder"); - private LazyLoggers() { throw new InternalError(); } @@ -341,7 +336,6 @@ PlatformLogger.Bridge platformProxy() { // Do not expose this outside of this package. private static volatile LoggerFinder provider; - @SuppressWarnings("removal") private static LoggerFinder accessLoggerFinder() { LoggerFinder prov = provider; if (prov == null) { @@ -350,10 +344,7 @@ private static LoggerFinder accessLoggerFinder() { // the result. // This is just an optimization to avoid the cost of calling // doPrivileged every time. - final SecurityManager sm = System.getSecurityManager(); - prov = sm == null ? LoggerFinder.getLoggerFinder() : - AccessController.doPrivileged( - (PrivilegedAction)LoggerFinder::getLoggerFinder); + prov = LoggerFinder.getLoggerFinder(); if (prov instanceof TemporaryLoggerFinder) return prov; provider = prov; } @@ -403,17 +394,9 @@ static Logger makeLazyLogger(String name, Module module, BooleanSupplier isLoadi * @param module module on behalf of which the logger is created * @return The logger returned by the LoggerFinder. */ - @SuppressWarnings("removal") static Logger getLoggerFromFinder(String name, Module module) { - final SecurityManager sm = System.getSecurityManager(); - if (sm == null) { - return accessLoggerFinder().getLogger(name, module); - } else { - return AccessController.doPrivileged((PrivilegedAction) - () -> {return accessLoggerFinder().getLogger(name, module);}, - null, LOGGERFINDER_PERMISSION); - } - } + return accessLoggerFinder().getLogger(name, module); + } /** * Returns a (possibly lazy) Logger for the caller. diff --git a/src/java.base/share/classes/jdk/internal/logger/LoggerFinderLoader.java b/src/java.base/share/classes/jdk/internal/logger/LoggerFinderLoader.java index 932de4ef55463..36edb918712e8 100644 --- a/src/java.base/share/classes/jdk/internal/logger/LoggerFinderLoader.java +++ b/src/java.base/share/classes/jdk/internal/logger/LoggerFinderLoader.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2024, 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 @@ -24,12 +24,8 @@ */ package jdk.internal.logger; -import java.io.FilePermission; import java.lang.System.Logger; import java.lang.System.LoggerFinder; -import java.security.AccessController; -import java.security.Permission; -import java.security.PrivilegedAction; import java.util.Iterator; import java.util.Locale; import java.util.ServiceConfigurationError; @@ -37,9 +33,6 @@ import java.util.function.BooleanSupplier; import jdk.internal.vm.annotation.Stable; -import sun.security.util.SecurityConstants; -import sun.security.action.GetBooleanAction; -import sun.security.action.GetPropertyAction; /** * Helper class used to load the {@link java.lang.System.LoggerFinder}. @@ -47,13 +40,6 @@ public final class LoggerFinderLoader { private static volatile System.LoggerFinder service; private static final Object lock = new int[0]; - static final Permission CLASSLOADER_PERMISSION = - SecurityConstants.GET_CLASSLOADER_PERMISSION; - static final Permission READ_PERMISSION = - new FilePermission("<>", - SecurityConstants.FILE_READ_ACTION); - public static final RuntimePermission LOGGERFINDER_PERMISSION = - new RuntimePermission("loggerFinder"); // This is used to control how the LoggerFinderLoader handles // errors when instantiating the LoggerFinder provider. @@ -63,7 +49,7 @@ public final class LoggerFinderLoader { // DEBUG => Do not fail, use plain default (simple logger) implementation, // prints warning and exception stack trace on console. // QUIET => Do not fail and stay silent. - private static enum ErrorPolicy { ERROR, WARNING, DEBUG, QUIET }; + private static enum ErrorPolicy { ERROR, WARNING, DEBUG, QUIET } // This class is static and cannot be instantiated. private LoggerFinderLoader() { @@ -107,8 +93,7 @@ static boolean isLoadingThread() { // Get configuration error policy private static ErrorPolicy configurationErrorPolicy() { - String errorPolicy = - GetPropertyAction.privilegedGetProperty("jdk.logger.finder.error"); + String errorPolicy = System.getProperty("jdk.logger.finder.error"); if (errorPolicy == null || errorPolicy.isEmpty()) { return ErrorPolicy.WARNING; } @@ -122,25 +107,12 @@ private static ErrorPolicy configurationErrorPolicy() { // Whether multiple provider should be considered as an error. // This is further submitted to the configuration error policy. private static boolean ensureSingletonProvider() { - return GetBooleanAction.privilegedGetProperty - ("jdk.logger.finder.singleton"); + return Boolean.getBoolean("jdk.logger.finder.singleton"); } - @SuppressWarnings("removal") private static Iterator findLoggerFinderProviders() { - final Iterator iterator; - if (System.getSecurityManager() == null) { - iterator = ServiceLoader.load(System.LoggerFinder.class, + return ServiceLoader.load(System.LoggerFinder.class, ClassLoader.getSystemClassLoader()).iterator(); - } else { - final PrivilegedAction> pa = - () -> ServiceLoader.load(System.LoggerFinder.class, - ClassLoader.getSystemClassLoader()).iterator(); - iterator = AccessController.doPrivileged(pa, null, - LOGGERFINDER_PERMISSION, CLASSLOADER_PERMISSION, - READ_PERMISSION); - } - return iterator; } public static final class TemporaryLoggerFinder extends LoggerFinder { @@ -219,25 +191,10 @@ private static System.LoggerFinder loadLoggerFinder() { return result; } - @SuppressWarnings("removal") private static System.LoggerFinder loadDefaultImplementation() { - final SecurityManager sm = System.getSecurityManager(); - final Iterator iterator; - if (sm == null) { - iterator = ServiceLoader.loadInstalled(DefaultLoggerFinder.class).iterator(); - } else { - // We use limited do privileged here - the minimum set of - // permissions required to 'see' the META-INF/services resources - // seems to be CLASSLOADER_PERMISSION and READ_PERMISSION. - // Note that do privileged is required because - // otherwise the SecurityManager will prevent the ServiceLoader - // from seeing the installed provider. - PrivilegedAction> pa = () -> - ServiceLoader.loadInstalled(DefaultLoggerFinder.class).iterator(); - iterator = AccessController.doPrivileged(pa, null, - LOGGERFINDER_PERMISSION, CLASSLOADER_PERMISSION, - READ_PERMISSION); - } + final Iterator iterator = + ServiceLoader.loadInstalled(DefaultLoggerFinder.class).iterator(); + DefaultLoggerFinder result = null; try { // Iterator iterates with the access control context stored @@ -256,11 +213,6 @@ private static System.LoggerFinder loadDefaultImplementation() { } public static System.LoggerFinder getLoggerFinder() { - @SuppressWarnings("removal") - final SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPermission(LOGGERFINDER_PERMISSION); - } return service(); } diff --git a/src/java.base/share/classes/jdk/internal/logger/SimpleConsoleLogger.java b/src/java.base/share/classes/jdk/internal/logger/SimpleConsoleLogger.java index 317e475d1a8d4..664ffaf73565d 100644 --- a/src/java.base/share/classes/jdk/internal/logger/SimpleConsoleLogger.java +++ b/src/java.base/share/classes/jdk/internal/logger/SimpleConsoleLogger.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2024, 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 @@ -29,8 +29,6 @@ import java.io.PrintWriter; import java.io.StringWriter; import java.lang.StackWalker.StackFrame; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.time.ZonedDateTime; import java.util.Optional; import java.util.MissingResourceException; @@ -39,7 +37,6 @@ import java.lang.System.Logger; import java.util.function.Predicate; import java.util.function.Supplier; -import sun.security.action.GetPropertyAction; import sun.util.logging.PlatformLogger; import sun.util.logging.PlatformLogger.ConfigurableBridge.LoggerConfiguration; @@ -56,8 +53,7 @@ public class SimpleConsoleLogger extends LoggerConfiguration PlatformLogger.toPlatformLevel(DEFAULT_LEVEL); static Level getDefaultLevel() { - String levelName = GetPropertyAction - .privilegedGetProperty("jdk.system.logger.level", "INFO"); + String levelName = System.getProperty("jdk.system.logger.level", "INFO"); try { return Level.valueOf(levelName); } catch (IllegalArgumentException iae) { @@ -202,18 +198,9 @@ private String getCallerInfo() { /* * CallerFinder is a stateful predicate. */ - @SuppressWarnings("removal") static final class CallerFinder implements Predicate { - private static final StackWalker WALKER; - static { - final PrivilegedAction action = new PrivilegedAction<>() { - @Override - public StackWalker run() { - return StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE); - } - }; - WALKER = AccessController.doPrivileged(action); - } + private static final StackWalker WALKER = + StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE); /** * Returns StackFrame of the caller's frame. @@ -439,8 +426,7 @@ static final class Formatting { // Make it easier to wrap Logger... private static final String[] skips; static { - String additionalPkgs = - GetPropertyAction.privilegedGetProperty("jdk.logger.packages"); + String additionalPkgs = System.getProperty("jdk.logger.packages"); skips = additionalPkgs == null ? new String[0] : additionalPkgs.split(","); } @@ -499,7 +485,7 @@ static String getSimpleFormat(String key, Function defaultProper // jdk/test/java/lang/invoke/lambda/LogGeneratedClassesTest.java // to fail - because that test has a testcase which somehow references // PlatformLogger and counts the number of generated lambda classes. - String format = GetPropertyAction.privilegedGetProperty(key); + String format = System.getProperty(key); if (format == null && defaultPropertyGetter != null) { format = defaultPropertyGetter.apply(key); diff --git a/src/java.logging/share/classes/java/util/logging/ConsoleHandler.java b/src/java.logging/share/classes/java/util/logging/ConsoleHandler.java index 13a6d294e7442..cab4805b9e739 100644 --- a/src/java.logging/share/classes/java/util/logging/ConsoleHandler.java +++ b/src/java.logging/share/classes/java/util/logging/ConsoleHandler.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2024, 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 @@ -78,7 +78,7 @@ public ConsoleHandler() { // configure with specific defaults for ConsoleHandler super(Level.INFO, new SimpleFormatter(), null); - setOutputStreamPrivileged(System.err); + setOutputStream(System.err); } /** diff --git a/src/java.logging/share/classes/java/util/logging/FileHandler.java b/src/java.logging/share/classes/java/util/logging/FileHandler.java index b56f53adbb3ec..3c36a21516c07 100644 --- a/src/java.logging/share/classes/java/util/logging/FileHandler.java +++ b/src/java.logging/share/classes/java/util/logging/FileHandler.java @@ -43,8 +43,6 @@ import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.nio.file.Paths; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.HashSet; import java.util.Set; @@ -267,7 +265,6 @@ private void configure() { * @throws NullPointerException if pattern property is an empty String. */ public FileHandler() throws IOException { - checkPermission(); configure(); // pattern will have been set by configure. check that it's not // empty. @@ -293,10 +290,9 @@ public FileHandler() throws IOException { * @throws IllegalArgumentException if pattern is an empty string */ public FileHandler(String pattern) throws IOException { - if (pattern.length() < 1 ) { + if (pattern.isEmpty()) { throw new IllegalArgumentException(); } - checkPermission(); configure(); this.pattern = pattern; this.limit = 0; @@ -323,10 +319,9 @@ public FileHandler(String pattern) throws IOException { * @throws IllegalArgumentException if pattern is an empty string */ public FileHandler(String pattern, boolean append) throws IOException { - if (pattern.length() < 1 ) { + if (pattern.isEmpty()) { throw new IllegalArgumentException(); } - checkPermission(); configure(); this.pattern = pattern; this.limit = 0; @@ -357,10 +352,9 @@ public FileHandler(String pattern, boolean append) throws IOException { * @throws IllegalArgumentException if pattern is an empty string */ public FileHandler(String pattern, int limit, int count) throws IOException { - if (limit < 0 || count < 1 || pattern.length() < 1) { + if (limit < 0 || count < 1 || pattern.isEmpty()) { throw new IllegalArgumentException(); } - checkPermission(); configure(); this.pattern = pattern; this.limit = limit; @@ -425,10 +419,9 @@ public FileHandler(String pattern, int limit, int count, boolean append) */ public FileHandler(String pattern, long limit, int count, boolean append) throws IOException { - if (limit < 0 || count < 1 || pattern.length() < 1) { + if (limit < 0 || count < 1 || pattern.isEmpty()) { throw new IllegalArgumentException(); } - checkPermission(); configure(); this.pattern = pattern; this.limit = limit; @@ -451,7 +444,6 @@ private boolean isParentWritable(Path path) { */ private void openFiles() throws IOException { LogManager manager = LogManager.getLogManager(); - manager.checkPermission(); if (count < 1) { throw new IllegalArgumentException("file count = " + count); } @@ -481,7 +473,7 @@ private void openFiles() throws IOException { // Now try to lock that filename. // Because some systems (e.g., Solaris) can only do file locks // between processes (and not within a process), we first check - // if we ourself already have the file locked. + // if we ourselves already have the file locked. synchronized(locks) { if (locks.contains(lockFileName)) { // We already own this lock, for a different FileHandler @@ -616,7 +608,7 @@ && isParentWritable(lockFilePath)) { * @param generation the generation number to distinguish rotated logs * @param unique a unique number to resolve conflicts * @return the generated File - * @throws IOException + * @throws IOException if an I/O error occurs */ private File generate(String pattern, int generation, int unique) throws IOException @@ -696,7 +688,7 @@ static File generate(String pat, int count, int generation, int unique) if (unique > 0 && !sawu) { word = word.append('.').append(unique); } - if (word.length() > 0) { + if (!word.isEmpty()) { String n = word.toString(); Path p = prev == null ? Paths.get(n) : prev.resolveSibling(n); result = result == null ? p : result.resolve(p); @@ -714,21 +706,7 @@ static File generate(String pat, int count, int generation, int unique) /** * Rotate the set of output files */ - private void rotate() { - if (tryUseLock()) { - try { - rotate0(); - } finally { - unlock(); - } - } else { - synchronized (this) { - rotate0(); - } - } - } - - private void rotate0() { + private synchronized void rotate() { Level oldLevel = getLevel(); setLevel(Level.OFF); @@ -761,40 +739,14 @@ private void rotate0() { * silently ignored and is not published */ @Override - public void publish(LogRecord record) { - if (tryUseLock()) { - try { - publish0(record); - } finally { - unlock(); - } - } else { - synchronized (this) { - publish0(record); - } - } - - } - @SuppressWarnings("removal") - private void publish0(LogRecord record) { + public synchronized void publish(LogRecord record) { if (!isLoggable(record)) { return; } super.publish(record); flush(); if (limit > 0 && (meter.written >= limit || meter.written < 0)) { - // We performed access checks in the "init" method to make sure - // we are only initialized from trusted code. So we assume - // it is OK to write the target files, even if we are - // currently being called from untrusted code. - // So it is safe to raise privilege here. - AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Object run() { - rotate(); - return null; - } - }); + rotate(); } } @@ -802,21 +754,7 @@ public Object run() { * Close all the files. */ @Override - public void close() { - if (tryUseLock()) { - try { - close0(); - } finally { - unlock(); - } - } else { - synchronized (this) { - close0(); - } - } - } - - private void close0() throws SecurityException { + public synchronized void close() { super.close(); // Unlock any lock file. if (lockFileName == null) { diff --git a/src/java.logging/share/classes/java/util/logging/Handler.java b/src/java.logging/share/classes/java/util/logging/Handler.java index e5fbc131de615..7b93e517e972a 100644 --- a/src/java.logging/share/classes/java/util/logging/Handler.java +++ b/src/java.logging/share/classes/java/util/logging/Handler.java @@ -28,9 +28,6 @@ import java.util.Objects; import java.io.UnsupportedEncodingException; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.util.concurrent.locks.ReentrantLock; /** * A {@code Handler} object takes log messages from a {@code Logger} and @@ -52,6 +49,8 @@ public abstract class Handler { private static final int offValue = Level.OFF.intValue(); + + // ensure log manager is initialized private final LogManager manager = LogManager.getLogManager(); // We're using volatile here to avoid synchronizing getters, which @@ -66,7 +65,6 @@ public abstract class Handler { private volatile Level logLevel = Level.ALL; private volatile ErrorManager errorManager = new ErrorManager(); private volatile String encoding; - private final ReentrantLock lock; /** * Default constructor. The resulting {@code Handler} has a log @@ -74,19 +72,7 @@ public abstract class Handler { * {@code Filter}. A default {@code ErrorManager} instance is installed * as the {@code ErrorManager}. */ - protected Handler() { - lock = initLocking(); - } - - private ReentrantLock initLocking() { - Class clazz = this.getClass(); - ClassLoader loader = clazz.getClassLoader(); - if (loader != null && loader != ClassLoader.getPlatformClassLoader()) { - return null; - } else { - return new ReentrantLock(); - } - } + protected Handler() { } /** * Package-private constructor for chaining from subclass constructors @@ -100,7 +86,6 @@ private ReentrantLock initLocking() { * nor found in LogManager configuration properties * @param specifiedFormatter if not null, this is the formatter to configure */ - @SuppressWarnings("removal") Handler(Level defaultLevel, Formatter defaultFormatter, Formatter specifiedFormatter) { this(); @@ -111,38 +96,23 @@ private ReentrantLock initLocking() { final Level level = manager.getLevelProperty(cname + ".level", defaultLevel); final Filter filter = manager.getFilterProperty(cname + ".filter", null); final Formatter formatter = specifiedFormatter == null - ? manager.getFormatterProperty(cname + ".formatter", defaultFormatter) - : specifiedFormatter; + ? manager.getFormatterProperty(cname + ".formatter", defaultFormatter) + : specifiedFormatter; final String encoding = manager.getStringProperty(cname + ".encoding", null); - AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Void run() { - setLevel(level); - setFilter(filter); - setFormatter(formatter); - try { - setEncoding(encoding); - } catch (Exception ex) { - try { - setEncoding(null); - } catch (Exception ex2) { - // doing a setEncoding with null should always work. - // assert false; - } - } - return null; + setLevel(level); + setFilter(filter); + setFormatter(formatter); + try { + setEncoding(encoding); + } catch (Exception ex) { + try { + setEncoding(null); + } catch (Exception ex2) { + // doing a setEncoding with null should always work. + // assert false; } - }, null, LogManager.controlPermission); - } - - boolean tryUseLock() { - if (lock == null) return false; - lock.lock(); - return true; - } - void unlock() { - lock.unlock(); + } } /** @@ -183,22 +153,7 @@ void unlock() { * * @param newFormatter the {@code Formatter} to use (may not be null) */ - public void setFormatter(Formatter newFormatter) { - if (tryUseLock()) { - try { - setFormatter0(newFormatter); - } finally { - unlock(); - } - } else { - synchronized (this) { - setFormatter0(newFormatter); - } - } - } - - private void setFormatter0(Formatter newFormatter) throws SecurityException { - checkPermission(); + public synchronized void setFormatter(Formatter newFormatter) { formatter = Objects.requireNonNull(newFormatter); } @@ -221,24 +176,8 @@ public Formatter getFormatter() { * @throws UnsupportedEncodingException if the named encoding is * not supported. */ - public void setEncoding(String encoding) + public synchronized void setEncoding(String encoding) throws java.io.UnsupportedEncodingException { - if (tryUseLock()) { - try { - setEncoding0(encoding); - } finally { - unlock(); - } - } else { - synchronized (this) { - setEncoding0(encoding); - } - } - } - - private void setEncoding0(String encoding) - throws SecurityException, java.io.UnsupportedEncodingException { - checkPermission(); if (encoding != null) { try { if(!java.nio.charset.Charset.isSupported(encoding)) { @@ -270,22 +209,7 @@ public String getEncoding() { * * @param newFilter a {@code Filter} object (may be null) */ - public void setFilter(Filter newFilter) { - if (tryUseLock()) { - try { - setFilter0(newFilter); - } finally { - unlock(); - } - } else { - synchronized (this) { - setFilter0(newFilter); - } - } - } - - private void setFilter0(Filter newFilter) throws SecurityException { - checkPermission(); + public synchronized void setFilter(Filter newFilter) { filter = newFilter; } @@ -306,22 +230,7 @@ public Filter getFilter() { * * @param em the new ErrorManager */ - public void setErrorManager(ErrorManager em) { - if (tryUseLock()) { - try { - setErrorManager0(em); - } finally { - unlock(); - } - } else { - synchronized (this) { - setErrorManager0(em); - } - } - } - - private void setErrorManager0(ErrorManager em) { - checkPermission(); + public synchronized void setErrorManager(ErrorManager em) { if (em == null) { throw new NullPointerException(); } @@ -334,7 +243,6 @@ private void setErrorManager0(ErrorManager em) { * @return the ErrorManager for this Handler */ public ErrorManager getErrorManager() { - checkPermission(); return errorManager; } @@ -366,25 +274,10 @@ protected void reportError(String msg, Exception ex, int code) { * * @param newLevel the new value for the log level */ - public void setLevel(Level newLevel) { - if (tryUseLock()) { - try { - setLevel0(newLevel); - } finally { - unlock(); - } - } else { - synchronized (this) { - setLevel0(newLevel); - } - } - } - - private void setLevel0(Level newLevel) throws SecurityException { + public synchronized void setLevel(Level newLevel) { if (newLevel == null) { throw new NullPointerException(); } - checkPermission(); logLevel = newLevel; } @@ -426,10 +319,4 @@ public boolean isLoggable(LogRecord record) { return filter.isLoggable(record); } - // Package-private support method for security checks. - // We check that the caller has appropriate security privileges - // to update Handler state and if not throw a SecurityException. - void checkPermission() throws SecurityException { - manager.checkPermission(); - } } diff --git a/src/java.logging/share/classes/java/util/logging/Level.java b/src/java.logging/share/classes/java/util/logging/Level.java index 4a0f876d86d77..ac9a6cae374ee 100644 --- a/src/java.logging/share/classes/java/util/logging/Level.java +++ b/src/java.logging/share/classes/java/util/logging/Level.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2024, 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 @@ -29,8 +29,6 @@ import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -620,9 +618,7 @@ static synchronized void purge() { } private static void registerWithClassLoader(Level customLevel) { - PrivilegedAction pa = customLevel.getClass()::getClassLoader; - @SuppressWarnings("removal") - final ClassLoader cl = AccessController.doPrivileged(pa); + final ClassLoader cl = customLevel.getClass().getClassLoader(); CUSTOM_LEVEL_CLV.computeIfAbsent(cl, (c, v) -> new ArrayList<>()) .add(customLevel); } diff --git a/src/java.logging/share/classes/java/util/logging/LogManager.java b/src/java.logging/share/classes/java/util/logging/LogManager.java index 59ab4bfcbcead..0b7a854dddf3b 100644 --- a/src/java.logging/share/classes/java/util/logging/LogManager.java +++ b/src/java.logging/share/classes/java/util/logging/LogManager.java @@ -27,7 +27,6 @@ import java.io.*; import java.util.*; -import java.security.*; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.util.concurrent.ConcurrentHashMap; @@ -39,8 +38,6 @@ import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; -import jdk.internal.access.JavaAWTAccess; -import jdk.internal.access.SharedSecrets; import sun.util.logging.internal.LoggingProviderImpl; import static jdk.internal.logger.DefaultLoggerFinder.isSystem; @@ -218,39 +215,36 @@ public static CloseOnReset create(Logger logger) { Collections.synchronizedMap(new IdentityHashMap<>()); // The global LogManager object - @SuppressWarnings("removal") - private static final LogManager manager = AccessController.doPrivileged( - new PrivilegedAction() { - @Override - public LogManager run() { - LogManager mgr = null; - String cname = null; - try { - cname = System.getProperty("java.util.logging.manager"); - if (cname != null) { - try { - @SuppressWarnings("deprecation") - Object tmp = ClassLoader.getSystemClassLoader() - .loadClass(cname).newInstance(); - mgr = (LogManager) tmp; - } catch (ClassNotFoundException ex) { - @SuppressWarnings("deprecation") - Object tmp = Thread.currentThread() - .getContextClassLoader().loadClass(cname).newInstance(); - mgr = (LogManager) tmp; - } - } - } catch (Exception ex) { - System.err.println("Could not load Logmanager \"" + cname + "\""); - ex.printStackTrace(); - } - if (mgr == null) { - mgr = new LogManager(); - } - return mgr; + private static final LogManager manager = initLogManager(); + private static LogManager initLogManager() { + LogManager mgr = null; + String cname = null; + try { + cname = System.getProperty("java.util.logging.manager"); + if (cname != null) { + try { + @SuppressWarnings("deprecation") + Object tmp = ClassLoader.getSystemClassLoader() + .loadClass(cname).newInstance(); + mgr = (LogManager) tmp; + } catch (ClassNotFoundException ex) { + @SuppressWarnings("deprecation") + Object tmp = Thread.currentThread() + .getContextClassLoader().loadClass(cname).newInstance(); + mgr = (LogManager) tmp; } - }); + } + } catch (Exception ex) { + System.err.println("Could not load Logmanager \"" + cname + "\""); + ex.printStackTrace(); + } + if (mgr == null) { + mgr = new LogManager(); + } + return mgr; + } + // This private class is used as a shutdown hook. // It does a "reset" to close all open handlers. @@ -290,11 +284,6 @@ public void run() { * retrieved by calling LogManager.getLogManager. */ protected LogManager() { - this(checkSubclassPermissions()); - } - - private LogManager(Void checked) { - // Add a shutdown hook to close the global handlers. try { Runtime.getRuntime().addShutdownHook(new Cleaner()); @@ -304,20 +293,6 @@ private LogManager(Void checked) { } } - private static Void checkSubclassPermissions() { - @SuppressWarnings("removal") - final SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - // These permission will be checked in the LogManager constructor, - // in order to register the Cleaner() thread as a shutdown hook. - // Check them here to avoid the penalty of constructing the object - // etc... - sm.checkPermission(new RuntimePermission("shutdownHooks")); - sm.checkPermission(new RuntimePermission("setContextClassLoader")); - } - return null; - } - /** * Lazy initialization: if this instance of manager is the global * manager then this method will read the initial configuration and @@ -380,40 +355,33 @@ final void ensureLogManagerInitialized() { // We use initializedCalled to break the recursion. initializedCalled = true; try { - AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Object run() { - assert rootLogger == null; - assert initializedCalled && !initializationDone; - - // create root logger before reading primordial - // configuration - to ensure that it will be added - // before the global logger, and not after. - final Logger root = owner.rootLogger = owner.new RootLogger(); - - // Read configuration. - owner.readPrimordialConfiguration(); - - // Create and retain Logger for the root of the namespace. - owner.addLogger(root); - - // Initialize level if not yet initialized - if (!root.isLevelInitialized()) { - root.setLevel(defaultLevel); - } - - // Adding the global Logger. - // Do not call Logger.getGlobal() here as this might trigger - // subtle inter-dependency issues. - @SuppressWarnings("deprecation") - final Logger global = Logger.global; + assert rootLogger == null; + assert initializedCalled && !initializationDone; - // Make sure the global logger will be registered in the - // global manager - owner.addLogger(global); - return null; - } - }); + // create root logger before reading primordial + // configuration - to ensure that it will be added + // before the global logger, and not after. + final Logger root = owner.rootLogger = owner.new RootLogger(); + + // Read configuration. + owner.readPrimordialConfiguration(); + + // Create and retain Logger for the root of the namespace. + owner.addLogger(root); + + // Initialize level if not yet initialized + if (!root.isLevelInitialized()) { + root.setLevel(defaultLevel); + } + + // Adding the global Logger. + // Do not call Logger.getGlobal() here as this might trigger + // subtle inter-dependency issues. + @SuppressWarnings("deprecation") final Logger global = Logger.global; + + // Make sure the global logger will be registered in the + // global manager + owner.addLogger(global); } finally { initializationDone = true; } @@ -461,29 +429,6 @@ private void readPrimordialConfiguration() { // must be called while holding con // Loggers are isolated from each AppContext. private LoggerContext getUserContext() { LoggerContext context = null; - - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - JavaAWTAccess javaAwtAccess = SharedSecrets.getJavaAWTAccess(); - if (sm != null && javaAwtAccess != null) { - // for each applet, it has its own LoggerContext isolated from others - final Object ecx = javaAwtAccess.getAppletContext(); - if (ecx != null) { - synchronized (javaAwtAccess) { - // find the AppContext of the applet code - // will be null if we are in the main app context. - if (contextsMap == null) { - contextsMap = new WeakHashMap<>(); - } - context = contextsMap.get(ecx); - if (context == null) { - // Create a new LoggerContext for the applet. - context = new LoggerContext(); - contextsMap.put(ecx, context); - } - } - } - } // for standalone app, return userContext return context != null ? context : userContext; } @@ -552,7 +497,6 @@ Logger demandSystemLogger(String name, String resourceBundleName, Class calle return demandSystemLogger(name, resourceBundleName, module); } - @SuppressWarnings("removal") Logger demandSystemLogger(String name, String resourceBundleName, Module module) { // Add a system logger in the system context's namespace final Logger sysLogger = getSystemContext() @@ -578,14 +522,7 @@ Logger demandSystemLogger(String name, String resourceBundleName, Module module) // LogManager will set the sysLogger's handlers via LogManager.addLogger method. if (logger != sysLogger) { // if logger already exists we merge the two logger configurations. - final Logger l = logger; - AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Void run() { - l.mergeWithSystemLogger(sysLogger); - return null; - } - }); + logger.mergeWithSystemLogger(sysLogger); } return sysLogger; } @@ -801,7 +738,7 @@ synchronized boolean addLocalLogger(Logger logger, boolean addDefaultLoggersIfNe // the logger's level is already initialized Level level = owner.getLevelProperty(name + ".level", null); if (level != null && !logger.isLevelInitialized()) { - doSetLevel(logger, level); + logger.setLevel(level); } // instantiation of the handler is done in the LogManager.addLogger @@ -826,7 +763,7 @@ synchronized boolean addLocalLogger(Logger logger, boolean addDefaultLoggersIfNe } if (parent != null) { - doSetParent(logger, parent); + logger.setParent(parent); } // Walk over the children and tell them we are their new parent. node.walkAndSetParent(logger); @@ -855,22 +792,15 @@ synchronized Enumeration getLoggerNames() { // If logger.getUseParentHandlers() returns 'true' and any of the logger's // parents have levels or handlers defined, make sure they are instantiated. - @SuppressWarnings("removal") private void processParentHandlers(final Logger logger, final String name, Predicate visited) { final LogManager owner = getOwner(); - AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Void run() { - if (logger != owner.rootLogger) { - boolean useParent = owner.getBooleanProperty(name + ".useParentHandlers", true); - if (!useParent) { - logger.setUseParentHandlers(false); - } - } - return null; + if (logger != owner.rootLogger) { + boolean useParent = owner.getBooleanProperty(name + ".useParentHandlers", true); + if (!useParent) { + logger.setUseParentHandlers(false); } - }); + } int ix = 1; for (;;) { @@ -898,7 +828,7 @@ LogNode getNode(String name) { return root; } LogNode node = root; - while (name.length() > 0) { + while (!name.isEmpty()) { int ix = name.indexOf('.'); String head; if (ix > 0) { @@ -961,21 +891,10 @@ Logger demandLogger(String name, String resourceBundleName, } // Add new per logger handlers. - // We need to raise privilege here. All our decisions will - // be made based on the logging configuration, which can - // only be modified by trusted code. - @SuppressWarnings("removal") private void loadLoggerHandlers(final Logger logger, final String name, - final String handlersPropertyName) - { - AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Void run() { - setLoggerHandlers(logger, name, handlersPropertyName, - createLoggerHandlers(name, handlersPropertyName)); - return null; - } - }); + final String handlersPropertyName) { + setLoggerHandlers(logger, name, handlersPropertyName, + createLoggerHandlers(name, handlersPropertyName)); } private void setLoggerHandlers(final Logger logger, final String name, @@ -1228,45 +1147,6 @@ private boolean forceLoadHandlers(Logger logger) { && configurationLock.isHeldByCurrentThread(); } - // Private method to set a level on a logger. - // If necessary, we raise privilege before doing the call. - @SuppressWarnings("removal") - private static void doSetLevel(final Logger logger, final Level level) { - SecurityManager sm = System.getSecurityManager(); - if (sm == null) { - // There is no security manager, so things are easy. - logger.setLevel(level); - return; - } - // There is a security manager. Raise privilege before - // calling setLevel. - AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Object run() { - logger.setLevel(level); - return null; - }}); - } - - // Private method to set a parent on a logger. - // If necessary, we raise privilege before doing the setParent call. - @SuppressWarnings("removal") - private static void doSetParent(final Logger logger, final Logger parent) { - SecurityManager sm = System.getSecurityManager(); - if (sm == null) { - // There is no security manager, so things are easy. - logger.setParent(parent); - return; - } - // There is a security manager. Raise privilege before - // calling setParent. - AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Object run() { - logger.setParent(parent); - return null; - }}); - } /** * Method to find a named logger. @@ -1350,7 +1230,6 @@ public Enumeration getLoggerNames() { * @throws IOException if there are IO problems reading the configuration. */ public void readConfiguration() throws IOException { - checkPermission(); // if a configuration class is specified, load it and use it. String cname = System.getProperty("java.util.logging.config.class"); @@ -1383,7 +1262,7 @@ public void readConfiguration() throws IOException { } } - String getConfigurationFileName() throws IOException { + String getConfigurationFileName() { String fname = System.getProperty("java.util.logging.config.file"); if (fname == null) { fname = System.getProperty("java.home"); @@ -1413,7 +1292,6 @@ String getConfigurationFileName() throws IOException { */ public void reset() { - checkPermission(); List persistent; @@ -1518,7 +1396,7 @@ private String[] parseClassNames(String propertyName) { String word = hands.substring(ix, end); ix = end+1; word = word.trim(); - if (word.length() == 0) { + if (word.isEmpty()) { continue; } result.add(word); @@ -1553,7 +1431,6 @@ private String[] parseClassNames(String propertyName) { * {@linkplain java.util.Properties properties file} format. */ public void readConfiguration(InputStream ins) throws IOException { - checkPermission(); // We don't want reset() and readConfiguration() to run // in parallel. @@ -1857,7 +1734,6 @@ static ModType of(String previous, String next) { */ public void updateConfiguration(Function> mapper) throws IOException { - checkPermission(); ensureLogManagerInitialized(); drainLoggerRefQueueBounded(); @@ -2054,7 +1930,6 @@ public void updateConfiguration(Function> mapper) throws IOException { - checkPermission(); ensureLogManagerInitialized(); drainLoggerRefQueueBounded(); @@ -2410,16 +2285,6 @@ private void initializeGlobalHandlers() { } } - static final Permission controlPermission = - new LoggingPermission("control", null); - - void checkPermission() { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) - sm.checkPermission(controlPermission); - } - /** * Does nothing. * @@ -2456,7 +2321,7 @@ void walkAndSetParent(Logger parent) { if (logger == null) { node.walkAndSetParent(parent); } else { - doSetParent(logger, parent); + logger.setParent(parent); } } } @@ -2590,19 +2455,8 @@ public static synchronized LoggingMXBean getLoggingMXBean() { */ public LogManager addConfigurationListener(Runnable listener) { final Runnable r = Objects.requireNonNull(listener); - checkPermission(); - @SuppressWarnings("removal") - final SecurityManager sm = System.getSecurityManager(); - @SuppressWarnings("removal") - final AccessControlContext acc = - sm == null ? null : AccessController.getContext(); - final PrivilegedAction pa = - acc == null ? null : () -> { r.run() ; return null; }; - @SuppressWarnings("removal") - final Runnable pr = - acc == null ? r : () -> AccessController.doPrivileged(pa, acc); // Will do nothing if already registered. - listeners.putIfAbsent(r, pr); + listeners.putIfAbsent(r, r); return this; } @@ -2618,7 +2472,6 @@ public LogManager addConfigurationListener(Runnable listener) { */ public void removeConfigurationListener(Runnable listener) { final Runnable key = Objects.requireNonNull(listener); - checkPermission(); listeners.remove(key); } @@ -2652,8 +2505,7 @@ private void invokeConfigurationListeners() { * behalf of system and application classes. */ private static final class LoggingProviderAccess - implements LoggingProviderImpl.LogManagerAccess, - PrivilegedAction { + implements LoggingProviderImpl.LogManagerAccess { private LoggingProviderAccess() { } @@ -2684,11 +2536,6 @@ public Logger demandLoggerFor(LogManager manager, String name, Module module) { } Objects.requireNonNull(name); Objects.requireNonNull(module); - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPermission(controlPermission); - } if (isSystem(module)) { return manager.demandSystemLogger(name, Logger.SYSTEM_LOGGER_RB_NAME, module); @@ -2697,23 +2544,15 @@ public Logger demandLoggerFor(LogManager manager, String name, Module module) { } } - @Override - public Void run() { + private void init() { LoggingProviderImpl.setLogManagerAccess(INSTANCE); - return null; } static final LoggingProviderAccess INSTANCE = new LoggingProviderAccess(); } static { - initStatic(); - } - - @SuppressWarnings("removal") - private static void initStatic() { - AccessController.doPrivileged(LoggingProviderAccess.INSTANCE, null, - controlPermission); + LoggingProviderAccess.INSTANCE.init(); } } diff --git a/src/java.logging/share/classes/java/util/logging/LogRecord.java b/src/java.logging/share/classes/java/util/logging/LogRecord.java index 9605d348e6848..43d196cd53837 100644 --- a/src/java.logging/share/classes/java/util/logging/LogRecord.java +++ b/src/java.logging/share/classes/java/util/logging/LogRecord.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2024, 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 @@ -28,8 +28,6 @@ import java.util.*; import java.util.concurrent.atomic.AtomicLong; import java.io.*; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.time.Clock; import java.util.function.Predicate; import static jdk.internal.logger.SurrogateLogger.isFilteredFrame; @@ -767,14 +765,10 @@ private void inferCaller() { /* * CallerFinder is a stateful predicate. */ - @SuppressWarnings("removal") static final class CallerFinder implements Predicate { - private static final StackWalker WALKER; - static { - final PrivilegedAction action = - () -> StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE); - WALKER = AccessController.doPrivileged(action); - } + private static final StackWalker WALKER = + StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE); + /** * Returns StackFrame of the caller's frame. diff --git a/src/java.logging/share/classes/java/util/logging/Logger.java b/src/java.logging/share/classes/java/util/logging/Logger.java index 3f192ba9612e7..f40e419c2caf1 100644 --- a/src/java.logging/share/classes/java/util/logging/Logger.java +++ b/src/java.logging/share/classes/java/util/logging/Logger.java @@ -26,8 +26,6 @@ package java.util.logging; import java.lang.ref.WeakReference; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Iterator; import java.util.Locale; @@ -579,7 +577,7 @@ final void mergeWithSystemLogger(Logger system) { // should never come here throw new InternalError("invalid logger merge"); } - checkPermission(); + ensureManagerInitialized(); final ConfigurationData cfg = config; if (cfg != system.config) { config = cfg.merge(system); @@ -614,13 +612,12 @@ void setLogManager(LogManager manager) { this.manager = manager; } - private void checkPermission() throws SecurityException { + private void ensureManagerInitialized() { if (!anonymous) { if (manager == null) { // Complete initialization of the global Logger. manager = LogManager.getLogManager(); } - manager.checkPermission(); } } @@ -633,17 +630,8 @@ private void checkPermission() throws SecurityException { // These system loggers only set the resource bundle to the given // resource bundle name (rather than the default system resource bundle). private static class SystemLoggerHelper { - static boolean disableCallerCheck = getBooleanProperty("sun.util.logging.disableCallerCheck"); - private static boolean getBooleanProperty(final String key) { - @SuppressWarnings("removal") - String s = AccessController.doPrivileged(new PrivilegedAction() { - @Override - public String run() { - return System.getProperty(key); - } - }); - return Boolean.parseBoolean(s); - } + static boolean disableCallerCheck = + Boolean.getBoolean("sun.util.logging.disableCallerCheck"); } private static Logger demandLogger(String name, String resourceBundleName, Class caller) { @@ -930,7 +918,7 @@ public String getResourceBundleName() { * @param newFilter a filter object (may be null) */ public void setFilter(Filter newFilter) { - checkPermission(); + ensureManagerInitialized(); config.setFilter(newFilter); } @@ -1990,7 +1978,7 @@ public void finest(Supplier msgSupplier) { * @param newLevel the new value for the log level (may be null) */ public void setLevel(Level newLevel) { - checkPermission(); + ensureManagerInitialized(); synchronized (treeLock) { config.setLevelObject(newLevel); updateEffectiveLevel(); @@ -2047,7 +2035,7 @@ public String getName() { */ public void addHandler(Handler handler) { Objects.requireNonNull(handler); - checkPermission(); + ensureManagerInitialized(); config.addHandler(handler); } @@ -2059,7 +2047,7 @@ public void addHandler(Handler handler) { * @param handler a logging Handler */ public void removeHandler(Handler handler) { - checkPermission(); + ensureManagerInitialized(); if (handler == null) { return; } @@ -2091,7 +2079,7 @@ Handler[] accessCheckedHandlers() { * logger's parent. */ public void setUseParentHandlers(boolean useParentHandlers) { - checkPermission(); + ensureManagerInitialized(); config.setUseParentHandlers(useParentHandlers); } @@ -2187,11 +2175,8 @@ private synchronized ResourceBundle findResourceBundle(String name, try { // We are called by an unnamed module: try with the // unnamed module class loader: - PrivilegedAction getModuleClassLoader = - () -> callerModule.getClassLoader(); - @SuppressWarnings("removal") - ClassLoader moduleCL = - AccessController.doPrivileged(getModuleClassLoader); + ClassLoader moduleCL = callerModule.getClassLoader(); + // moduleCL can be null if the logger is created by a class // appended to the bootclasspath. // If moduleCL is null we would use cl, but we already tried @@ -2267,7 +2252,7 @@ private synchronized void setupResourceInfo(String name, setCallerModuleRef(callerModule); if (isSystemLogger && (callerModule != null && !isSystem(callerModule))) { - checkPermission(); + ensureManagerInitialized(); } if (name.equals(SYSTEM_LOGGER_RB_NAME)) { @@ -2300,7 +2285,7 @@ private synchronized void setupResourceInfo(String name, * @since 1.8 */ public void setResourceBundle(ResourceBundle bundle) { - checkPermission(); + ensureManagerInitialized(); // Will throw NPE if bundle is null. final String baseName = bundle.getBaseBundleName(); @@ -2359,11 +2344,7 @@ public void setParent(Logger parent) { throw new NullPointerException(); } - // check permission for all loggers, including anonymous loggers - if (manager == null) { - manager = LogManager.getLogManager(); - } - manager.checkPermission(); + ensureManagerInitialized(); doSetParent(parent); } diff --git a/src/java.logging/share/classes/java/util/logging/LoggingPermission.java b/src/java.logging/share/classes/java/util/logging/LoggingPermission.java index 0784bf863eb2c..c48d5ba9f0698 100644 --- a/src/java.logging/share/classes/java/util/logging/LoggingPermission.java +++ b/src/java.logging/share/classes/java/util/logging/LoggingPermission.java @@ -26,7 +26,6 @@ package java.util.logging; -import java.security.*; /** * This class is for logging permissions. Currently there is only one diff --git a/src/java.logging/share/classes/java/util/logging/MemoryHandler.java b/src/java.logging/share/classes/java/util/logging/MemoryHandler.java index f7d67b4cca20e..bd585fe569499 100644 --- a/src/java.logging/share/classes/java/util/logging/MemoryHandler.java +++ b/src/java.logging/share/classes/java/util/logging/MemoryHandler.java @@ -178,21 +178,7 @@ public MemoryHandler(Handler target, int size, Level pushLevel) { * silently ignored and is not published */ @Override - public void publish(LogRecord record) { - if (tryUseLock()) { - try { - publish0(record); - } finally { - unlock(); - } - } else { - synchronized (this) { - publish0(record); - } - } - } - - private void publish0(LogRecord record) { + public synchronized void publish(LogRecord record) { if (!isLoggable(record)) { return; } @@ -214,21 +200,7 @@ private void publish0(LogRecord record) { *

* The buffer is then cleared. */ - public void push() { - if (tryUseLock()) { - try { - push0(); - } finally { - unlock(); - } - } else { - synchronized (this) { - push0(); - } - } - } - - private void push0() { + public synchronized void push() { for (int i = 0; i < count; i++) { int ix = (start+i)%buffer.length; LogRecord record = buffer[ix]; @@ -267,25 +239,10 @@ public void close() { * * @param newLevel the new value of the {@code pushLevel} */ - public void setPushLevel(Level newLevel) { - if (tryUseLock()) { - try { - setPushLevel0(newLevel); - } finally { - unlock(); - } - } else { - synchronized (this) { - setPushLevel0(newLevel); - } - } - } - - private void setPushLevel0(Level newLevel) throws SecurityException { + public synchronized void setPushLevel(Level newLevel) { if (newLevel == null) { throw new NullPointerException(); } - checkPermission(); pushLevel = newLevel; } diff --git a/src/java.logging/share/classes/java/util/logging/SocketHandler.java b/src/java.logging/share/classes/java/util/logging/SocketHandler.java index 570e074cd9d94..380cc20add44f 100644 --- a/src/java.logging/share/classes/java/util/logging/SocketHandler.java +++ b/src/java.logging/share/classes/java/util/logging/SocketHandler.java @@ -146,28 +146,14 @@ private void connect() throws IOException { sock = new Socket(host, port); OutputStream out = sock.getOutputStream(); BufferedOutputStream bout = new BufferedOutputStream(out); - setOutputStreamPrivileged(bout); + setOutputStream(bout); } /** * Close this output stream. */ @Override - public void close() { - if (tryUseLock()) { - try { - close0(); - } finally { - unlock(); - } - } else { - synchronized (this) { - close0(); - } - } - } - - private void close0() throws SecurityException { + public synchronized void close() { super.close(); if (sock != null) { try { @@ -186,21 +172,7 @@ private void close0() throws SecurityException { * silently ignored and is not published */ @Override - public void publish(LogRecord record) { - if (tryUseLock()) { - try { - publish0(record); - } finally { - unlock(); - } - } else { - synchronized (this) { - publish0(record); - } - } - } - - private void publish0(LogRecord record) { + public synchronized void publish(LogRecord record) { if (!isLoggable(record)) { return; } diff --git a/src/java.logging/share/classes/java/util/logging/StreamHandler.java b/src/java.logging/share/classes/java/util/logging/StreamHandler.java index 9dfcf2930419e..31cb6605fbc79 100644 --- a/src/java.logging/share/classes/java/util/logging/StreamHandler.java +++ b/src/java.logging/share/classes/java/util/logging/StreamHandler.java @@ -27,8 +27,6 @@ package java.util.logging; import java.io.*; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.Objects; /** @@ -99,7 +97,7 @@ public StreamHandler(OutputStream out, Formatter formatter) { // configure with default level but use specified formatter super(Level.INFO, null, Objects.requireNonNull(formatter)); - setOutputStreamPrivileged(out); + setOutputStream(out); } /** @@ -120,21 +118,7 @@ public StreamHandler(OutputStream out, Formatter formatter) { * * @param out New output stream. May not be null. */ - protected void setOutputStream(OutputStream out) { - if (tryUseLock()) { - try { - setOutputStream0(out); - } finally { - unlock(); - } - } else { - synchronized (this) { - setOutputStream0(out); - } - } - } - - private void setOutputStream0(OutputStream out) throws SecurityException { + protected synchronized void setOutputStream(OutputStream out) { if (out == null) { throw new NullPointerException(); } @@ -167,22 +151,8 @@ private void setOutputStream0(OutputStream out) throws SecurityException { * not supported. */ @Override - public void setEncoding(String encoding) + public synchronized void setEncoding(String encoding) throws java.io.UnsupportedEncodingException { - if (tryUseLock()) { - try { - setEncoding0(encoding); - } finally { - unlock(); - } - } else { - synchronized (this) { - setEncoding0(encoding); - } - } - } - private void setEncoding0(String encoding) - throws SecurityException, java.io.UnsupportedEncodingException { super.setEncoding(encoding); if (output == null) { return; @@ -214,22 +184,8 @@ private void setEncoding0(String encoding) * silently ignored and is not published */ @Override - public void publish(LogRecord record) { - if (tryUseLock()) { - try { - publish0(record); - } finally { - unlock(); - } - } else { - synchronized (this) { - publish0(record); - } - } - } - - private void publish0(LogRecord record) { - if (!isLoggable(record)) { + public synchronized void publish(LogRecord record) { + if (!isLoggable(record)) { return; } String msg; @@ -280,21 +236,7 @@ public boolean isLoggable(LogRecord record) { * Flush any buffered messages. */ @Override - public void flush() { - if (tryUseLock()) { - try { - flush0(); - } finally { - unlock(); - } - } else { - synchronized (this) { - flush0(); - } - } - } - - private void flush0() { + public synchronized void flush() { Writer writer = this.writer; if (writer != null) { try { @@ -307,8 +249,7 @@ private void flush0() { } } - private void flushAndClose() throws SecurityException { - checkPermission(); + private void flushAndClose() { Writer writer = this.writer; if (writer != null) { try { @@ -338,30 +279,8 @@ private void flushAndClose() throws SecurityException { * "tail" string. */ @Override - public void close() { - if (tryUseLock()) { - try { - flushAndClose(); - } finally { - unlock(); - } - } else { - synchronized (this) { - flushAndClose(); - } - } + public synchronized void close() { + flushAndClose(); } - // Package-private support for setting OutputStream - // with elevated privilege. - @SuppressWarnings("removal") - final void setOutputStreamPrivileged(final OutputStream out) { - AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Void run() { - setOutputStream(out); - return null; - } - }, null, LogManager.controlPermission); - } } diff --git a/src/java.logging/share/classes/sun/util/logging/internal/LoggingProviderImpl.java b/src/java.logging/share/classes/sun/util/logging/internal/LoggingProviderImpl.java index 27a42dea3b5c6..8cccb6e23fa21 100644 --- a/src/java.logging/share/classes/sun/util/logging/internal/LoggingProviderImpl.java +++ b/src/java.logging/share/classes/sun/util/logging/internal/LoggingProviderImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2024, 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 @@ -26,8 +26,6 @@ package sun.util.logging.internal; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.ResourceBundle; import java.util.function.Supplier; import java.lang.System.LoggerFinder; @@ -35,7 +33,6 @@ import java.util.Objects; import java.util.logging.LogManager; import jdk.internal.logger.DefaultLoggerFinder; -import java.util.logging.LoggingPermission; import sun.util.logging.PlatformLogger; import sun.util.logging.PlatformLogger.ConfigurableBridge.LoggerConfiguration; @@ -77,15 +74,9 @@ * */ public final class LoggingProviderImpl extends DefaultLoggerFinder { - static final RuntimePermission LOGGERFINDER_PERMISSION = - new RuntimePermission("loggerFinder"); - private static final LoggingPermission LOGGING_CONTROL_PERMISSION = - new LoggingPermission("control", null); /** * Creates a new instance of LoggingProviderImpl. - * @throws SecurityException if the calling code does not have the - * {@code RuntimePermission("loggerFinder")}. */ public LoggingProviderImpl() { } @@ -147,13 +138,13 @@ public void log(sun.util.logging.PlatformLogger.Level level, String msg) { } @Override - public void log(sun.util.logging.PlatformLogger.Level level, Supplier msgSuppier) { - julLogger.log(toJUL(level), msgSuppier); + public void log(sun.util.logging.PlatformLogger.Level level, Supplier msgSupplier) { + julLogger.log(toJUL(level), msgSupplier); } @Override - public void log(sun.util.logging.PlatformLogger.Level level, Throwable thrown, Supplier msgSuppier) { - julLogger.log(toJUL(level), thrown, msgSuppier); + public void log(sun.util.logging.PlatformLogger.Level level, Throwable thrown, Supplier msgSupplier) { + julLogger.log(toJUL(level), thrown, msgSupplier); } @Override @@ -403,18 +394,10 @@ static JULWrapper of(java.util.logging.Logger logger) { * @param module the module for which the logger should be created. * @return a Logger suitable for use in the given module. */ - @SuppressWarnings("removal") private static java.util.logging.Logger demandJULLoggerFor(final String name, Module module) { final LogManager manager = LogManager.getLogManager(); - final SecurityManager sm = System.getSecurityManager(); - if (sm == null) { - return logManagerAccess.demandLoggerFor(manager, name, module); - } else { - final PrivilegedAction pa = - () -> logManagerAccess.demandLoggerFor(manager, name, module); - return AccessController.doPrivileged(pa, null, LOGGING_CONTROL_PERMISSION); - } + return logManagerAccess.demandLoggerFor(manager, name, module); } /** @@ -425,16 +408,9 @@ private static java.util.logging.Logger demandJULLoggerFor(final String name, * corresponding java.util.logging.Logger backend}. * * @return {@inheritDoc} - * @throws SecurityException if the calling code doesn't have the - * {@code RuntimePermission("loggerFinder")}. */ @Override protected Logger demandLoggerFor(String name, Module module) { - @SuppressWarnings("removal") - final SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPermission(LOGGERFINDER_PERMISSION); - } return JULWrapper.of(demandJULLoggerFor(name,module)); } @@ -445,25 +421,17 @@ java.util.logging.Logger demandLoggerFor(LogManager manager, // Hook for tests public static LogManagerAccess getLogManagerAccess() { - @SuppressWarnings("removal") - final SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPermission(LOGGING_CONTROL_PERMISSION); - } - // Triggers initialization of accessJulLogger if not set. + // Triggers initialization of logManagerAccess if not set. + LogManagerAccess logManagerAccess = LoggingProviderImpl.logManagerAccess; if (logManagerAccess == null) LogManager.getLogManager(); + logManagerAccess = LoggingProviderImpl.logManagerAccess; return logManagerAccess; } private static volatile LogManagerAccess logManagerAccess; - public static void setLogManagerAccess(LogManagerAccess accesLoggers) { - @SuppressWarnings("removal") - final SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPermission(LOGGING_CONTROL_PERMISSION); - } - logManagerAccess = accesLoggers; + public static void setLogManagerAccess(LogManagerAccess accessLoggers) { + logManagerAccess = accessLoggers; } } From 8f22db23a50fe537d8ef369e92f0d5f9970d98f0 Mon Sep 17 00:00:00 2001 From: Coleen Phillimore Date: Thu, 21 Nov 2024 12:14:23 +0000 Subject: [PATCH 68/74] 8330606: Redefinition doesn't but should verify the new klass Reviewed-by: dholmes, jsjolen --- src/hotspot/share/classfile/verifier.cpp | 38 +++---- src/hotspot/share/classfile/verifier.hpp | 1 - src/hotspot/share/oops/method.cpp | 3 +- .../RedefineClasses/RedefineVerifyError.java | 100 ++++++++++++++++++ 4 files changed, 119 insertions(+), 23 deletions(-) create mode 100644 test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineVerifyError.java diff --git a/src/hotspot/share/classfile/verifier.cpp b/src/hotspot/share/classfile/verifier.cpp index ef3caff6476ef..9a36584916d8d 100644 --- a/src/hotspot/share/classfile/verifier.cpp +++ b/src/hotspot/share/classfile/verifier.cpp @@ -105,11 +105,13 @@ static verify_byte_codes_fn_t verify_byte_codes_fn() { // Methods in Verifier +// This method determines whether we run the verifier and class file format checking code. bool Verifier::should_verify_for(oop class_loader) { return class_loader == nullptr ? BytecodeVerificationLocal : BytecodeVerificationRemote; } +// This method determines whether we allow package access in access checks in reflection. bool Verifier::relax_access_for(oop loader) { bool trusted = java_lang_ClassLoader::is_trusted_loader(loader); bool need_verify = @@ -120,6 +122,21 @@ bool Verifier::relax_access_for(oop loader) { return !need_verify; } +// Callers will pass should_verify_class as true, depending on the results of should_verify_for() above, +// or pass true for redefinition of any class. +static bool is_eligible_for_verification(InstanceKlass* klass, bool should_verify_class) { + Symbol* name = klass->name(); + + return (should_verify_class && + // Can not verify the bytecodes for shared classes because they have + // already been rewritten to contain constant pool cache indices, + // which the verifier can't understand. + // Shared classes shouldn't have stackmaps either. + // However, bytecodes for shared old classes can be verified because + // they have not been rewritten. + !(klass->is_shared() && klass->is_rewritten())); +} + void Verifier::trace_class_resolution(Klass* resolve_class, InstanceKlass* verify_class) { assert(verify_class != nullptr, "Unexpected null verify_class"); ResourceMark rm; @@ -273,27 +290,6 @@ bool Verifier::verify(InstanceKlass* klass, bool should_verify_class, TRAPS) { } } -bool Verifier::is_eligible_for_verification(InstanceKlass* klass, bool should_verify_class) { - Symbol* name = klass->name(); - - return (should_verify_class && - // return if the class is a bootstrapping class - // or defineClass specified not to verify by default (flags override passed arg) - // We need to skip the following four for bootstraping - name != vmSymbols::java_lang_Object() && - name != vmSymbols::java_lang_Class() && - name != vmSymbols::java_lang_String() && - name != vmSymbols::java_lang_Throwable() && - - // Can not verify the bytecodes for shared classes because they have - // already been rewritten to contain constant pool cache indices, - // which the verifier can't understand. - // Shared classes shouldn't have stackmaps either. - // However, bytecodes for shared old classes can be verified because - // they have not been rewritten. - !(klass->is_shared() && klass->is_rewritten())); -} - Symbol* Verifier::inference_verify( InstanceKlass* klass, char* message, size_t message_len, TRAPS) { JavaThread* thread = THREAD; diff --git a/src/hotspot/share/classfile/verifier.hpp b/src/hotspot/share/classfile/verifier.hpp index 731d5eb8d3b9f..7857d47270509 100644 --- a/src/hotspot/share/classfile/verifier.hpp +++ b/src/hotspot/share/classfile/verifier.hpp @@ -61,7 +61,6 @@ class Verifier : AllStatic { static void trace_class_resolution(Klass* resolve_class, InstanceKlass* verify_class); private: - static bool is_eligible_for_verification(InstanceKlass* klass, bool should_verify_class); static Symbol* inference_verify( InstanceKlass* klass, char* msg, size_t msg_len, TRAPS); }; diff --git a/src/hotspot/share/oops/method.cpp b/src/hotspot/share/oops/method.cpp index af10efc0f0003..d0b29a4a30992 100644 --- a/src/hotspot/share/oops/method.cpp +++ b/src/hotspot/share/oops/method.cpp @@ -335,7 +335,8 @@ int Method::bci_from(address bcp) const { int Method::validate_bci(int bci) const { - return (bci == 0 || bci < code_size()) ? bci : -1; + // Called from the verifier, and should return -1 if not valid. + return ((is_native() && bci == 0) || (!is_native() && 0 <= bci && bci < code_size())) ? bci : -1; } // Return bci if it appears to be a valid bcp diff --git a/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineVerifyError.java b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineVerifyError.java new file mode 100644 index 0000000000000..ea511c05b5959 --- /dev/null +++ b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineVerifyError.java @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2024, 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. + * + * 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. + */ + +/* + * @test + * @bug 6402717 8330606 + * @summary Redefine VerifyError to get a VerifyError should not throw SOE + * @requires vm.jvmti + * @library /test/lib + * @modules java.base/jdk.internal.misc + * java.base/jdk.internal.org.objectweb.asm + * java.compiler + * java.instrument + * jdk.jartool/sun.tools.jar + * @run main RedefineClassHelper + * @run main/othervm/timeout=180 + * -javaagent:redefineagent.jar + * -Xlog:class+init,exceptions + * RedefineVerifyError + */ + +import jdk.internal.org.objectweb.asm.AnnotationVisitor; +import jdk.internal.org.objectweb.asm.Attribute; +import jdk.internal.org.objectweb.asm.ClassReader; +import jdk.internal.org.objectweb.asm.ClassWriter; +import jdk.internal.org.objectweb.asm.ConstantDynamic; +import jdk.internal.org.objectweb.asm.FieldVisitor; +import jdk.internal.org.objectweb.asm.Handle; +import jdk.internal.org.objectweb.asm.Label; +import jdk.internal.org.objectweb.asm.MethodVisitor; +import jdk.internal.org.objectweb.asm.Opcodes; +import jdk.internal.org.objectweb.asm.RecordComponentVisitor; +import jdk.internal.org.objectweb.asm.Type; +import jdk.internal.org.objectweb.asm.TypePath; + +public class RedefineVerifyError implements Opcodes { + + // This is a redefinition of java.lang.VerifyError with two broken init methods (no bytecodes) + public static byte[] dump () throws Exception { + + ClassWriter classWriter = new ClassWriter(0); + FieldVisitor fieldVisitor; + RecordComponentVisitor recordComponentVisitor; + MethodVisitor methodVisitor; + AnnotationVisitor annotationVisitor0; + + classWriter.visit(52, ACC_SUPER | ACC_PUBLIC, "java/lang/VerifyError", null, "java/lang/LinkageError", null); + { + fieldVisitor = classWriter.visitField(ACC_PRIVATE | ACC_FINAL | ACC_STATIC, "serialVersionUID", "J", null, new Long(7001962396098498785L)); + fieldVisitor.visitEnd(); + } + { + methodVisitor = classWriter.visitMethod(ACC_PUBLIC, "", "()V", null, null); + methodVisitor.visitCode(); + methodVisitor.visitEnd(); + } + + { + methodVisitor = classWriter.visitMethod(ACC_PUBLIC, "", "(Ljava/lang/String;)V", null, null); + methodVisitor.visitCode(); + classWriter.visitEnd(); + } + + return classWriter.toByteArray(); + } + + public static void main(String[] args) throws Exception { + + Class verifyErrorMirror = java.lang.VerifyError.class; + + try { + // The Verifier is called for the redefinition, which will fail because of the broken method above. + RedefineClassHelper.redefineClass(verifyErrorMirror, dump()); + throw new RuntimeException("This should throw VerifyError"); + } catch (VerifyError e) { + // JVMTI recreates the VerifyError so the verification message is lost. + System.out.println("Passed"); + } + } +} From 882d6358074135b2c4fe21b32bd73f40022980bc Mon Sep 17 00:00:00 2001 From: Artur Barashev Date: Thu, 21 Nov 2024 14:14:30 +0000 Subject: [PATCH 69/74] 8245545: Disable TLS_RSA cipher suites Reviewed-by: mullan --- .../share/conf/security/java.security | 2 +- test/jdk/javax/net/ssl/DTLS/CipherSuite.java | 8 +++---- test/jdk/javax/net/ssl/SSLEngine/Basics.java | 5 +++-- .../net/ssl/SSLEngine/EngineCloseOnAlert.java | 8 +++++-- .../net/ssl/TLSv11/GenericBlockCipher.java | 6 ++--- .../javax/net/ssl/TLSv12/ProtocolFilter.java | 7 +++++- .../ssl/ciphersuites/DisabledAlgorithms.java | 12 +++++++--- .../ciphersuites/CheckCipherSuites.java | 22 ++----------------- .../SystemPropCipherSuitesOrder.java | 19 +++++++++++++--- .../ciphersuites/TLSCipherSuitesOrder.java | 4 +++- .../pkcs11/tls/tls12/FipsModeTLS12.java | 5 +++++ .../ssl/ClientHandshaker/LengthCheckTest.java | 6 ++--- .../EngineArgs/DebugReportsOneExtraByte.java | 6 ++--- 13 files changed, 64 insertions(+), 46 deletions(-) diff --git a/src/java.base/share/conf/security/java.security b/src/java.base/share/conf/security/java.security index 6374c1951bd02..0e24dee6ac27a 100644 --- a/src/java.base/share/conf/security/java.security +++ b/src/java.base/share/conf/security/java.security @@ -746,7 +746,7 @@ http.auth.digest.disabledAlgorithms = MD5, SHA-1 # rsa_pkcs1_sha1, secp224r1, TLS_RSA_* jdk.tls.disabledAlgorithms=SSLv3, TLSv1, TLSv1.1, DTLSv1.0, RC4, DES, \ MD5withRSA, DH keySize < 1024, EC keySize < 224, 3DES_EDE_CBC, anon, NULL, \ - ECDH + ECDH, TLS_RSA_* # # Legacy algorithms for Secure Socket Layer/Transport Layer Security (SSL/TLS) diff --git a/test/jdk/javax/net/ssl/DTLS/CipherSuite.java b/test/jdk/javax/net/ssl/DTLS/CipherSuite.java index 7ad8206a37e7d..b96032fd78193 100644 --- a/test/jdk/javax/net/ssl/DTLS/CipherSuite.java +++ b/test/jdk/javax/net/ssl/DTLS/CipherSuite.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2024, 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 @@ -33,16 +33,16 @@ * jdk.crypto.ec * @library /test/lib * @build DTLSOverDatagram - * @run main/othervm CipherSuite TLS_RSA_WITH_AES_128_CBC_SHA + * @run main/othervm CipherSuite TLS_RSA_WITH_AES_128_CBC_SHA re-enable * @run main/othervm CipherSuite TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 - * @run main/othervm CipherSuite TLS_RSA_WITH_AES_128_CBC_SHA256 + * @run main/othervm CipherSuite TLS_RSA_WITH_AES_128_CBC_SHA256 re-enable * @run main/othervm CipherSuite TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 * @run main/othervm CipherSuite TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA * @run main/othervm CipherSuite TLS_DHE_RSA_WITH_AES_128_CBC_SHA * @run main/othervm CipherSuite TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA re-enable * @run main/othervm CipherSuite TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 * @run main/othervm CipherSuite TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 - * @run main/othervm CipherSuite TLS_RSA_WITH_AES_128_GCM_SHA256 + * @run main/othervm CipherSuite TLS_RSA_WITH_AES_128_GCM_SHA256 re-enable * @run main/othervm CipherSuite TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 re-enable * @run main/othervm CipherSuite TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 * @run main/othervm CipherSuite TLS_DHE_DSS_WITH_AES_128_GCM_SHA256 diff --git a/test/jdk/javax/net/ssl/SSLEngine/Basics.java b/test/jdk/javax/net/ssl/SSLEngine/Basics.java index 3239bfd4ce99d..0ee7bfd7738d8 100644 --- a/test/jdk/javax/net/ssl/SSLEngine/Basics.java +++ b/test/jdk/javax/net/ssl/SSLEngine/Basics.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2024, 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 @@ -57,7 +57,8 @@ public class Basics { "/" + TRUSTSTORE_FILE; public static void main(String[] args) throws Exception { - SecurityUtils.removeFromDisabledTlsAlgs("TLSv1.1"); + // Re-enable TLSv1.1 and TLS_RSA_* since test depends on it. + SecurityUtils.removeFromDisabledTlsAlgs("TLSv1.1", "TLS_RSA_*"); runTest("TLSv1.3", "TLS_AES_256_GCM_SHA384"); runTest("TLSv1.2", "TLS_RSA_WITH_AES_256_GCM_SHA384"); diff --git a/test/jdk/javax/net/ssl/SSLEngine/EngineCloseOnAlert.java b/test/jdk/javax/net/ssl/SSLEngine/EngineCloseOnAlert.java index 7a4f71d8171dc..57eda1c2a42e8 100644 --- a/test/jdk/javax/net/ssl/SSLEngine/EngineCloseOnAlert.java +++ b/test/jdk/javax/net/ssl/SSLEngine/EngineCloseOnAlert.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 2024, 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 @@ -26,7 +26,8 @@ * @bug 8133632 * @summary javax.net.ssl.SSLEngine does not properly handle received * SSL fatal alerts - * @run main EngineCloseOnAlert + * @library /test/lib + * @run main/othervm EngineCloseOnAlert */ import java.io.FileInputStream; @@ -36,6 +37,7 @@ import java.util.*; import java.security.*; import static javax.net.ssl.SSLEngineResult.HandshakeStatus.*; +import jdk.test.lib.security.SecurityUtils; public class EngineCloseOnAlert { @@ -61,6 +63,8 @@ public interface TestCase { } public static void main(String[] args) throws Exception { + // Re-enable TLS_RSA_* since test depends on it. + SecurityUtils.removeFromDisabledTlsAlgs("TLS_RSA_*"); int failed = 0; List testMatrix = new LinkedList() {{ add(clientReceivesAlert); diff --git a/test/jdk/javax/net/ssl/TLSv11/GenericBlockCipher.java b/test/jdk/javax/net/ssl/TLSv11/GenericBlockCipher.java index cb67903287e8c..a634424b3d7ee 100644 --- a/test/jdk/javax/net/ssl/TLSv11/GenericBlockCipher.java +++ b/test/jdk/javax/net/ssl/TLSv11/GenericBlockCipher.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 2024, 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 @@ -172,8 +172,8 @@ void doClientSide() throws Exception { volatile Exception clientException = null; public static void main(String[] args) throws Exception { - // Re-enable TLSv1.1 since test depends on it. - SecurityUtils.removeFromDisabledTlsAlgs("TLSv1.1"); + // Re-enable TLSv1.1 and TLS_RSA_* since test depends on it. + SecurityUtils.removeFromDisabledTlsAlgs("TLSv1.1", "TLS_RSA_*"); String keyFilename = System.getProperty("test.src", ".") + "/" + pathToStores + diff --git a/test/jdk/javax/net/ssl/TLSv12/ProtocolFilter.java b/test/jdk/javax/net/ssl/TLSv12/ProtocolFilter.java index ec58bc74d0cf5..3291096af4852 100644 --- a/test/jdk/javax/net/ssl/TLSv12/ProtocolFilter.java +++ b/test/jdk/javax/net/ssl/TLSv12/ProtocolFilter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2024, 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 @@ -28,6 +28,7 @@ * @test * @bug 8052406 * @summary SSLv2Hello protocol may be filter out unexpectedly + * @library /test/lib * @run main/othervm ProtocolFilter */ @@ -35,6 +36,8 @@ import java.net.*; import javax.net.ssl.*; +import jdk.test.lib.security.SecurityUtils; + public class ProtocolFilter { /* @@ -156,6 +159,8 @@ void doClientSide() throws Exception { volatile Exception clientException = null; public static void main(String[] args) throws Exception { + // Re-enable TLS_RSA_* since test depends on it. + SecurityUtils.removeFromDisabledTlsAlgs("TLS_RSA_*"); String keyFilename = System.getProperty("test.src", ".") + "/" + pathToStores + "/" + keyStoreFile; diff --git a/test/jdk/javax/net/ssl/ciphersuites/DisabledAlgorithms.java b/test/jdk/javax/net/ssl/ciphersuites/DisabledAlgorithms.java index 994169a71829d..8db1dfdeac825 100644 --- a/test/jdk/javax/net/ssl/ciphersuites/DisabledAlgorithms.java +++ b/test/jdk/javax/net/ssl/ciphersuites/DisabledAlgorithms.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2024, 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 @@ -23,7 +23,7 @@ /* * @test - * @bug 8076221 8211883 8163327 8279164 + * @bug 8076221 8211883 8163327 8279164 8245545 * @summary Check if weak cipher suites are disabled * @library /javax/net/ssl/templates * @modules jdk.crypto.ec @@ -124,7 +124,13 @@ public class DisabledAlgorithms { "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA", "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA", "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA", - "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA" + "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA", + "TLS_RSA_WITH_AES_256_GCM_SHA384", + "TLS_RSA_WITH_AES_128_GCM_SHA256", + "TLS_RSA_WITH_AES_256_CBC_SHA256", + "TLS_RSA_WITH_AES_128_CBC_SHA256", + "TLS_RSA_WITH_AES_256_CBC_SHA", + "TLS_RSA_WITH_AES_128_CBC_SHA" }; public static void main(String[] args) throws Exception { diff --git a/test/jdk/javax/net/ssl/sanity/ciphersuites/CheckCipherSuites.java b/test/jdk/javax/net/ssl/sanity/ciphersuites/CheckCipherSuites.java index caa96cdb224e2..847c69112a0c3 100644 --- a/test/jdk/javax/net/ssl/sanity/ciphersuites/CheckCipherSuites.java +++ b/test/jdk/javax/net/ssl/sanity/ciphersuites/CheckCipherSuites.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2024, 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 @@ -23,7 +23,7 @@ /* * @test - * @bug 4750141 4895631 8217579 8163326 8279164 + * @bug 4750141 4895631 8217579 8163326 8279164 8245545 * @summary Check enabled and supported ciphersuites are correct * @run main/othervm CheckCipherSuites default * @run main/othervm CheckCipherSuites limited @@ -99,12 +99,6 @@ public class CheckCipherSuites { "TLS_DHE_DSS_WITH_AES_128_CBC_SHA", // deprecated - "TLS_RSA_WITH_AES_256_GCM_SHA384", - "TLS_RSA_WITH_AES_128_GCM_SHA256", - "TLS_RSA_WITH_AES_256_CBC_SHA256", - "TLS_RSA_WITH_AES_128_CBC_SHA256", - "TLS_RSA_WITH_AES_256_CBC_SHA", - "TLS_RSA_WITH_AES_128_CBC_SHA", "TLS_EMPTY_RENEGOTIATION_INFO_SCSV" }; @@ -124,9 +118,6 @@ public class CheckCipherSuites { "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA", "TLS_DHE_RSA_WITH_AES_128_CBC_SHA", "TLS_DHE_DSS_WITH_AES_128_CBC_SHA", - "TLS_RSA_WITH_AES_128_GCM_SHA256", - "TLS_RSA_WITH_AES_128_CBC_SHA256", - "TLS_RSA_WITH_AES_128_CBC_SHA", "TLS_EMPTY_RENEGOTIATION_INFO_SCSV" }; @@ -194,12 +185,6 @@ public class CheckCipherSuites { "TLS_DHE_DSS_WITH_AES_128_CBC_SHA", // deprecated - "TLS_RSA_WITH_AES_256_GCM_SHA384", - "TLS_RSA_WITH_AES_128_GCM_SHA256", - "TLS_RSA_WITH_AES_256_CBC_SHA256", - "TLS_RSA_WITH_AES_128_CBC_SHA256", - "TLS_RSA_WITH_AES_256_CBC_SHA", - "TLS_RSA_WITH_AES_128_CBC_SHA", "TLS_EMPTY_RENEGOTIATION_INFO_SCSV" }; @@ -219,9 +204,6 @@ public class CheckCipherSuites { "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA", "TLS_DHE_RSA_WITH_AES_128_CBC_SHA", "TLS_DHE_DSS_WITH_AES_128_CBC_SHA", - "TLS_RSA_WITH_AES_128_GCM_SHA256", - "TLS_RSA_WITH_AES_128_CBC_SHA256", - "TLS_RSA_WITH_AES_128_CBC_SHA", "TLS_EMPTY_RENEGOTIATION_INFO_SCSV" }; diff --git a/test/jdk/javax/net/ssl/sanity/ciphersuites/SystemPropCipherSuitesOrder.java b/test/jdk/javax/net/ssl/sanity/ciphersuites/SystemPropCipherSuitesOrder.java index 2817e3400ab38..6492e6508de2e 100644 --- a/test/jdk/javax/net/ssl/sanity/ciphersuites/SystemPropCipherSuitesOrder.java +++ b/test/jdk/javax/net/ssl/sanity/ciphersuites/SystemPropCipherSuitesOrder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2024, 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 @@ -21,6 +21,7 @@ * questions. */ import java.util.Arrays; +import java.util.stream.Stream; import javax.net.ssl.SSLServerSocket; import javax.net.ssl.SSLSocket; @@ -86,8 +87,20 @@ public static void main(String[] args) { clientcipherSuites = toArray(System.getProperty("jdk.tls.client.cipherSuites")); System.out.printf("SYSTEM PROPERTIES: ServerProp:%s - ClientProp:%s%n", - Arrays.deepToString(servercipherSuites), - Arrays.deepToString(clientcipherSuites)); + Arrays.deepToString(servercipherSuites), + Arrays.deepToString(clientcipherSuites)); + + // Re-enable TLS_RSA_* cipher suites if needed since test depends on it. + if (Stream.concat( + Arrays.stream( + servercipherSuites == null + ? new String[0] : servercipherSuites), + Arrays.stream( + clientcipherSuites == null + ? new String[0] : clientcipherSuites)) + .anyMatch(s -> s.startsWith("TLS_RSA_"))) { + SecurityUtils.removeFromDisabledTlsAlgs("TLS_RSA_*"); + } try { new SystemPropCipherSuitesOrder(args[0]).run(); diff --git a/test/jdk/javax/net/ssl/sanity/ciphersuites/TLSCipherSuitesOrder.java b/test/jdk/javax/net/ssl/sanity/ciphersuites/TLSCipherSuitesOrder.java index c2171d808891b..2ce46eb847131 100644 --- a/test/jdk/javax/net/ssl/sanity/ciphersuites/TLSCipherSuitesOrder.java +++ b/test/jdk/javax/net/ssl/sanity/ciphersuites/TLSCipherSuitesOrder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2024, 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 @@ -58,6 +58,8 @@ public class TLSCipherSuitesOrder extends SSLSocketTemplate { private final String[] clientcipherSuites; public static void main(String[] args) { + // Re-enable TLS_RSA_* since test depends on it. + SecurityUtils.removeFromDisabledTlsAlgs("TLS_RSA_*"); PROTOCOL protocol = PROTOCOL.valueOf(args[0]); try { new TLSCipherSuitesOrder(protocol.getProtocol(), diff --git a/test/jdk/sun/security/pkcs11/tls/tls12/FipsModeTLS12.java b/test/jdk/sun/security/pkcs11/tls/tls12/FipsModeTLS12.java index e9e4158f20e41..f9e9bd472c763 100644 --- a/test/jdk/sun/security/pkcs11/tls/tls12/FipsModeTLS12.java +++ b/test/jdk/sun/security/pkcs11/tls/tls12/FipsModeTLS12.java @@ -1,5 +1,6 @@ /* * Copyright (c) 2019, Red Hat, Inc. + * Copyright (c) 2024, 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 @@ -63,6 +64,7 @@ import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManagerFactory; +import jdk.test.lib.security.SecurityUtils; import sun.security.internal.spec.TlsMasterSecretParameterSpec; import sun.security.internal.spec.TlsPrfParameterSpec; import sun.security.internal.spec.TlsRsaPremasterSecretParameterSpec; @@ -80,6 +82,9 @@ public final class FipsModeTLS12 extends SecmodTest { private static PublicKey publicKey; public static void main(String[] args) throws Exception { + // Re-enable TLS_RSA_* since test depends on it. + SecurityUtils.removeFromDisabledTlsAlgs("TLS_RSA_*"); + try { initialize(); } catch (Exception e) { diff --git a/test/jdk/sun/security/ssl/ClientHandshaker/LengthCheckTest.java b/test/jdk/sun/security/ssl/ClientHandshaker/LengthCheckTest.java index 6c9dd847ee910..3aecb84bd9408 100644 --- a/test/jdk/sun/security/ssl/ClientHandshaker/LengthCheckTest.java +++ b/test/jdk/sun/security/ssl/ClientHandshaker/LengthCheckTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2024, 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 @@ -270,8 +270,8 @@ public void execTest() throws Exception { * Main entry point for this test. */ public static void main(String args[]) throws Exception { - // Re-enable TLSv1 since test depends on it. - SecurityUtils.removeFromDisabledTlsAlgs("TLSv1"); + // Re-enable TLSv1 and TLS_RSA_* since test depends on it. + SecurityUtils.removeFromDisabledTlsAlgs("TLSv1", "TLS_RSA_*"); List ccsTests = new ArrayList<>(); diff --git a/test/jdk/sun/security/ssl/EngineArgs/DebugReportsOneExtraByte.java b/test/jdk/sun/security/ssl/EngineArgs/DebugReportsOneExtraByte.java index 7632fcf462f9a..1446ad786e4dc 100644 --- a/test/jdk/sun/security/ssl/EngineArgs/DebugReportsOneExtraByte.java +++ b/test/jdk/sun/security/ssl/EngineArgs/DebugReportsOneExtraByte.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2024, 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 @@ -100,8 +100,8 @@ public static void main(String args[]) throws Exception { System.out.println("Test Passed."); } else { - // Re-enable TLSv1 since test depends on it - SecurityUtils.removeFromDisabledTlsAlgs("TLSv1"); + // Re-enable TLSv1 and TLS_RSA_* since test depends on it + SecurityUtils.removeFromDisabledTlsAlgs("TLSv1", "TLS_RSA_*"); DebugReportsOneExtraByte test = new DebugReportsOneExtraByte(); test.runTest(); From eef156180c772a042416fc35d86072e722519f0b Mon Sep 17 00:00:00 2001 From: Phil Race Date: Thu, 21 Nov 2024 16:02:28 +0000 Subject: [PATCH 70/74] 8344569: SwingUtilities2.makeIcon_Unprivileged is obsolete Reviewed-by: psadhukhan --- .../classes/javax/swing/LookAndFeel.java | 2 +- .../classes/sun/swing/SwingUtilities2.java | 36 +------------------ 2 files changed, 2 insertions(+), 36 deletions(-) diff --git a/src/java.desktop/share/classes/javax/swing/LookAndFeel.java b/src/java.desktop/share/classes/javax/swing/LookAndFeel.java index 830fadb1c0ca4..4d31dc9aa0271 100644 --- a/src/java.desktop/share/classes/javax/swing/LookAndFeel.java +++ b/src/java.desktop/share/classes/javax/swing/LookAndFeel.java @@ -469,7 +469,7 @@ public static void loadKeyBindings(InputMap retMap, Object[] keys) { * @see Class#getResourceAsStream(String) */ public static Object makeIcon(final Class baseClass, final String gifFile) { - return SwingUtilities2.makeIcon_Unprivileged(baseClass, baseClass, gifFile); + return SwingUtilities2.makeIcon(baseClass, baseClass, gifFile); } /** diff --git a/src/java.desktop/share/classes/sun/swing/SwingUtilities2.java b/src/java.desktop/share/classes/sun/swing/SwingUtilities2.java index 2613ca326ea49..eb35920aad0f1 100644 --- a/src/java.desktop/share/classes/sun/swing/SwingUtilities2.java +++ b/src/java.desktop/share/classes/sun/swing/SwingUtilities2.java @@ -1671,42 +1671,8 @@ public static String displayPropertiesToCSS(Font font, Color fg) { public static Object makeIcon(final Class baseClass, final Class rootClass, final String imageFile) { - return makeIcon(baseClass, rootClass, imageFile, true); - } - - /** - * Utility method that creates a {@code UIDefaults.LazyValue} that - * creates an {@code ImageIcon} {@code UIResource} for the - * specified image file name. The image is loaded using - * {@code getResourceAsStream}, starting with a call to that method - * on the base class parameter. If it cannot be found, searching will - * continue through the base class' inheritance hierarchy, up to and - * including {@code rootClass}. - * - * Finds an image with a given name without privileges enabled. - * - * @param baseClass the first class to use in searching for the resource - * @param rootClass an ancestor of {@code baseClass} to finish the - * search at - * @param imageFile the name of the file to be found - * @return a lazy value that creates the {@code ImageIcon} - * {@code UIResource} for the image, - * or null if it cannot be found - */ - public static Object makeIcon_Unprivileged(final Class baseClass, - final Class rootClass, - final String imageFile) { - return makeIcon(baseClass, rootClass, imageFile, false); - } - - private static Object makeIcon(final Class baseClass, - final Class rootClass, - final String imageFile, - final boolean enablePrivileges) { return (UIDefaults.LazyValue) (table) -> { - byte[] buffer = enablePrivileges ? - getIconBytes(baseClass, rootClass, imageFile) - : getIconBytes(baseClass, rootClass, imageFile); + byte[] buffer = getIconBytes(baseClass, rootClass, imageFile); if (buffer == null) { return null; From aaf3df7bb80d84d3870d8840c2935d4567f83f3c Mon Sep 17 00:00:00 2001 From: Brian Burkhalter Date: Thu, 21 Nov 2024 16:17:58 +0000 Subject: [PATCH 71/74] 8343823: (fs) Files.createLink: inconsistent behavior when creating link to symbolic link Reviewed-by: alanb --- src/java.base/share/classes/java/nio/file/Files.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/java.base/share/classes/java/nio/file/Files.java b/src/java.base/share/classes/java/nio/file/Files.java index 5dd8d219ba9b3..fa8ff8029e96f 100644 --- a/src/java.base/share/classes/java/nio/file/Files.java +++ b/src/java.base/share/classes/java/nio/file/Files.java @@ -982,7 +982,10 @@ public static Path createSymbolicLink(Path link, Path target, * The {@code existing} parameter is the path to an existing file. This * method creates a new directory entry for the file so that it can be * accessed using {@code link} as the path. On some file systems this is - * known as creating a "hard link". Whether the file attributes are + * known as creating a "hard link". If the {@code existing} parameter + * is the path to a symbolic link, then whether the new link is for the + * target of the symbolic link or for the symbolic link itself is platform + * dependent and therefore not specified. Whether the file attributes are * maintained for the file or for each directory entry is file system * specific and therefore not specified. Typically, a file system requires * that all links (directory entries) for a file be on the same file system. From 87be63f85dbbfd8695817a913ef2b2ae5b0d78e9 Mon Sep 17 00:00:00 2001 From: Brian Burkhalter Date: Thu, 21 Nov 2024 16:18:16 +0000 Subject: [PATCH 72/74] 8344659: Some uses of GetPropertyAction were not removed from java.io and java.nio Reviewed-by: lancea, rriggs, iris, dfuchs --- .../macosx/classes/sun/nio/fs/MacOSXFileSystem.java | 5 ++--- .../classes/sun/nio/fs/MacOSXFileSystemProvider.java | 3 +-- src/java.base/share/classes/java/io/Console.java | 3 +-- src/java.base/share/classes/sun/nio/ch/Poller.java | 5 ++--- src/java.base/share/classes/sun/nio/cs/GB18030.java | 5 ++--- .../share/classes/sun/nio/fs/AbstractWatchKey.java | 3 +-- src/java.base/share/classes/sun/nio/fs/Util.java | 6 +++--- .../windows/classes/sun/nio/ch/FileDispatcherImpl.java | 5 ++--- .../windows/classes/sun/nio/fs/WindowsFileAttributes.java | 7 +++---- 9 files changed, 17 insertions(+), 25 deletions(-) diff --git a/src/java.base/macosx/classes/sun/nio/fs/MacOSXFileSystem.java b/src/java.base/macosx/classes/sun/nio/fs/MacOSXFileSystem.java index 9303c713bf2a0..9b1c50967198e 100644 --- a/src/java.base/macosx/classes/sun/nio/fs/MacOSXFileSystem.java +++ b/src/java.base/macosx/classes/sun/nio/fs/MacOSXFileSystem.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 2024, 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 @@ -26,7 +26,6 @@ package sun.nio.fs; import java.util.regex.Pattern; -import sun.security.action.GetPropertyAction; import static sun.nio.fs.MacOSXNativeDispatcher.*; @@ -43,7 +42,7 @@ class MacOSXFileSystem extends BsdFileSystem { static { final String name = PROPERTY_NORMALIZE_FILE_PATHS; - String value = GetPropertyAction.privilegedGetProperty(name); + String value = System.getProperty(name); NORMALIZE_FILE_PATHS = (value != null) && ("".equals(value) || Boolean.parseBoolean(value)); } diff --git a/src/java.base/macosx/classes/sun/nio/fs/MacOSXFileSystemProvider.java b/src/java.base/macosx/classes/sun/nio/fs/MacOSXFileSystemProvider.java index 256a9b5e613b7..2540478dfca5f 100644 --- a/src/java.base/macosx/classes/sun/nio/fs/MacOSXFileSystemProvider.java +++ b/src/java.base/macosx/classes/sun/nio/fs/MacOSXFileSystemProvider.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 2024, 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 @@ -28,7 +28,6 @@ import java.nio.file.Path; import java.nio.file.spi.FileTypeDetector; import jdk.internal.util.StaticProperty; -import sun.security.action.GetPropertyAction; /** * MacOSX implementation of FileSystemProvider diff --git a/src/java.base/share/classes/java/io/Console.java b/src/java.base/share/classes/java/io/Console.java index 3881b2380ad85..4f919c064b942 100644 --- a/src/java.base/share/classes/java/io/Console.java +++ b/src/java.base/share/classes/java/io/Console.java @@ -33,7 +33,6 @@ import jdk.internal.io.JdkConsoleProvider; import jdk.internal.javac.PreviewFeature; import sun.nio.cs.UTF_8; -import sun.security.action.GetPropertyAction; /** * Methods to access the character-based console device, if any, associated @@ -646,7 +645,7 @@ private static UnsupportedOperationException newUnsupportedOperationException() private static final boolean istty = istty(); static final Charset CHARSET = - Charset.forName(GetPropertyAction.privilegedGetProperty("stdout.encoding"), UTF_8.INSTANCE); + Charset.forName(System.getProperty("stdout.encoding"), UTF_8.INSTANCE); private static final Console cons = instantiateConsole(); static { // Set up JavaIOAccess in SharedSecrets diff --git a/src/java.base/share/classes/sun/nio/ch/Poller.java b/src/java.base/share/classes/sun/nio/ch/Poller.java index ec45a398176c6..d25dfec7f4221 100644 --- a/src/java.base/share/classes/sun/nio/ch/Poller.java +++ b/src/java.base/share/classes/sun/nio/ch/Poller.java @@ -36,7 +36,6 @@ import java.util.concurrent.locks.LockSupport; import java.util.function.BooleanSupplier; import jdk.internal.misc.InnocuousThread; -import sun.security.action.GetPropertyAction; /** * Polls file descriptors. Virtual threads invoke the poll method to park @@ -305,7 +304,7 @@ private static class Pollers { Pollers() throws IOException { PollerProvider provider = PollerProvider.provider(); Poller.Mode mode; - String s = GetPropertyAction.privilegedGetProperty("jdk.pollerMode"); + String s = System.getProperty("jdk.pollerMode"); if (s != null) { if (s.equalsIgnoreCase(Mode.SYSTEM_THREADS.name()) || s.equals("1")) { mode = Mode.SYSTEM_THREADS; @@ -418,7 +417,7 @@ List writePollers() { * is not a power of 2. */ private static int pollerCount(String propName, int defaultCount) { - String s = GetPropertyAction.privilegedGetProperty(propName); + String s = System.getProperty(propName); int count = (s != null) ? Integer.parseInt(s) : defaultCount; // check power of 2 diff --git a/src/java.base/share/classes/sun/nio/cs/GB18030.java b/src/java.base/share/classes/sun/nio/cs/GB18030.java index 362553a5dbba0..2fc58b4ce5e7e 100644 --- a/src/java.base/share/classes/sun/nio/cs/GB18030.java +++ b/src/java.base/share/classes/sun/nio/cs/GB18030.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2024, 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 @@ -36,7 +36,6 @@ import java.nio.charset.CoderResult; import jdk.internal.misc.VM; import sun.nio.cs.Surrogate; -import sun.security.action.GetPropertyAction; public class GB18030 extends Charset @@ -49,7 +48,7 @@ public class GB18030 // as the system property is not ready to be read in that case. static final boolean IS_2000 = VM.initLevel() >= 1 && - "2000".equals(GetPropertyAction.privilegedGetProperty("jdk.charset.GB18030", "")); + "2000".equals(System.getProperty("jdk.charset.GB18030", "")); public GB18030() { super("GB18030", StandardCharsets.aliases_GB18030()); diff --git a/src/java.base/share/classes/sun/nio/fs/AbstractWatchKey.java b/src/java.base/share/classes/sun/nio/fs/AbstractWatchKey.java index bdb7920b20ae6..a598302e16509 100644 --- a/src/java.base/share/classes/sun/nio/fs/AbstractWatchKey.java +++ b/src/java.base/share/classes/sun/nio/fs/AbstractWatchKey.java @@ -29,7 +29,6 @@ import java.util.*; import jdk.internal.util.ArraysSupport; -import sun.security.action.GetPropertyAction; /** * Base implementation class for watch keys. @@ -44,7 +43,7 @@ abstract class AbstractWatchKey implements WatchKey { */ static final int MAX_EVENT_LIST_SIZE; static { - String rawValue = GetPropertyAction.privilegedGetProperty( + String rawValue = System.getProperty( "jdk.nio.file.WatchService.maxEventsPerPoll", String.valueOf(DEFAULT_MAX_EVENT_LIST_SIZE)); int intValue; diff --git a/src/java.base/share/classes/sun/nio/fs/Util.java b/src/java.base/share/classes/sun/nio/fs/Util.java index 94a5def1e853d..01b5238a6b28e 100644 --- a/src/java.base/share/classes/sun/nio/fs/Util.java +++ b/src/java.base/share/classes/sun/nio/fs/Util.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 2024, 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 @@ -28,7 +28,7 @@ import java.util.*; import java.nio.file.*; import java.nio.charset.Charset; -import sun.security.action.GetPropertyAction; +import jdk.internal.util.StaticProperty; /** * Utility methods @@ -38,7 +38,7 @@ class Util { private Util() { } private static final Charset jnuEncoding = Charset.forName( - GetPropertyAction.privilegedGetProperty("sun.jnu.encoding")); + StaticProperty.jnuEncoding()); /** * Returns {@code Charset} corresponding to the sun.jnu.encoding property diff --git a/src/java.base/windows/classes/sun/nio/ch/FileDispatcherImpl.java b/src/java.base/windows/classes/sun/nio/ch/FileDispatcherImpl.java index 6b7a81c2e85ff..146e1c1756414 100644 --- a/src/java.base/windows/classes/sun/nio/ch/FileDispatcherImpl.java +++ b/src/java.base/windows/classes/sun/nio/ch/FileDispatcherImpl.java @@ -31,7 +31,6 @@ import java.nio.CharBuffer; import jdk.internal.access.JavaIOFileDescriptorAccess; import jdk.internal.access.SharedSecrets; -import sun.security.action.GetPropertyAction; class FileDispatcherImpl extends FileDispatcher { private static final int MAP_INVALID = -1; @@ -189,8 +188,8 @@ int setDirectIO(FileDescriptor fd, String path) { } static boolean isFastFileTransferRequested() { - String fileTransferProp = GetPropertyAction - .privilegedGetProperty("jdk.nio.enableFastFileTransfer", "false"); + String fileTransferProp = + System.getProperty("jdk.nio.enableFastFileTransfer", "false"); return fileTransferProp.isEmpty() ? true : Boolean.parseBoolean(fileTransferProp); } diff --git a/src/java.base/windows/classes/sun/nio/fs/WindowsFileAttributes.java b/src/java.base/windows/classes/sun/nio/fs/WindowsFileAttributes.java index e442c49eadf1c..6e544b1c926ca 100644 --- a/src/java.base/windows/classes/sun/nio/fs/WindowsFileAttributes.java +++ b/src/java.base/windows/classes/sun/nio/fs/WindowsFileAttributes.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 2024, 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 @@ -28,7 +28,6 @@ import java.nio.file.attribute.*; import java.util.concurrent.TimeUnit; import jdk.internal.misc.Unsafe; -import sun.security.action.GetPropertyAction; import static sun.nio.fs.WindowsNativeDispatcher.*; import static sun.nio.fs.WindowsConstants.*; @@ -115,8 +114,8 @@ class WindowsFileAttributes // indicates if accurate metadata is required (interesting on NTFS only) private static final boolean ensureAccurateMetadata; static { - String propValue = GetPropertyAction.privilegedGetProperty( - "sun.nio.fs.ensureAccurateMetadata", "false"); + String propValue = + System.getProperty("sun.nio.fs.ensureAccurateMetadata", "false"); ensureAccurateMetadata = propValue.isEmpty() ? true : Boolean.parseBoolean(propValue); } From dfa18fe6b395171c821cde02f081e12dd1565ba5 Mon Sep 17 00:00:00 2001 From: Alan Bateman Date: Thu, 21 Nov 2024 16:25:43 +0000 Subject: [PATCH 73/74] 8344328: (dc) DatagramChannelImpl.blockingReceive can now synchronize on packet Reviewed-by: dfuchs, jpai --- .../sun/nio/ch/DatagramChannelImpl.java | 73 ++++++++----------- .../sun/nio/ch/DatagramSocketAdaptor.java | 8 +- 2 files changed, 37 insertions(+), 44 deletions(-) diff --git a/src/java.base/share/classes/sun/nio/ch/DatagramChannelImpl.java b/src/java.base/share/classes/sun/nio/ch/DatagramChannelImpl.java index 74c541052016f..33948afbcb03d 100644 --- a/src/java.base/share/classes/sun/nio/ch/DatagramChannelImpl.java +++ b/src/java.base/share/classes/sun/nio/ch/DatagramChannelImpl.java @@ -599,8 +599,7 @@ public SocketAddress receive(ByteBuffer dst) throws IOException { * @throws SocketTimeoutException if the timeout elapses */ void blockingReceive(DatagramPacket p, long nanos) throws IOException { - Objects.requireNonNull(p); - assert nanos >= 0; + assert Thread.holdsLock(p) && nanos >= 0; readLock.lock(); try { @@ -615,37 +614,31 @@ void blockingReceive(DatagramPacket p, long nanos) throws IOException { configureSocketNonBlockingIfVirtualThread(); } - // p.bufLength is the maximum size of the datagram that can be received - int bufLength; - synchronized (p) { - bufLength = DatagramPackets.getBufLength(p); - } - boolean completed = false; try { SocketAddress remote = beginRead(true, false); boolean connected = (remote != null); + + // p.bufLength is the maximum size of the datagram that can be received + int bufLength = DatagramPackets.getBufLength(p); ByteBuffer dst = tryBlockingReceive(connected, bufLength, nanos); if (dst != null) { - // if datagram received then get sender and copy to DatagramPacket + // copy to DatagramPacket, set length and sender try { - SocketAddress sender = sourceSocketAddress(); - synchronized (p) { - // copy bytes to the DatagramPacket, and set length and sender. - // Need to re-read p.bufLength in case DatagramPacket changed - int len = Math.min(dst.limit(), DatagramPackets.getBufLength(p)); - dst.get(p.getData(), p.getOffset(), len); - DatagramPackets.setLength(p, len); - p.setSocketAddress(sender); - } + int len = dst.limit(); + dst.get(p.getData(), p.getOffset(), len); + DatagramPackets.setLength(p, len); + p.setSocketAddress(sourceSocketAddress()); } finally { Util.offerFirstTemporaryDirectBuffer(dst); } completed = true; } + } finally { endRead(true, completed); } + } finally { readLock.unlock(); } @@ -835,7 +828,7 @@ public int send(ByteBuffer src, SocketAddress target) * @throws IllegalBlockingModeException if the channel is non-blocking */ void blockingSend(DatagramPacket p) throws IOException { - Objects.requireNonNull(p); + assert Thread.holdsLock(p); writeLock.lock(); try { @@ -843,38 +836,34 @@ void blockingSend(DatagramPacket p) throws IOException { if (!isBlocking()) throw new IllegalBlockingModeException(); - ByteBuffer src = null; + int len = p.getLength(); + ByteBuffer src = Util.getTemporaryDirectBuffer(len); try { + // copy bytes to temporary direct buffer + src.put(p.getData(), p.getOffset(), len); + src.flip(); + + // target address InetSocketAddress target; - synchronized (p) { - int len = p.getLength(); - src = Util.getTemporaryDirectBuffer(len); - - // copy bytes to temporary direct buffer - src.put(p.getData(), p.getOffset(), len); - src.flip(); - - // target address - if (p.getAddress() == null) { - InetSocketAddress remote = remoteAddress(); - if (remote == null) { - throw new IllegalArgumentException("Address not set"); - } - // set address/port to be compatible with long standing behavior - p.setAddress(remote.getAddress()); - p.setPort(remote.getPort()); - target = remote; - } else { - target = (InetSocketAddress) p.getSocketAddress(); + if (p.getAddress() == null) { + InetSocketAddress remote = remoteAddress(); + if (remote == null) { + throw new IllegalArgumentException("Address not set"); } + // set address/port to be compatible with long-standing behavior + p.setAddress(remote.getAddress()); + p.setPort(remote.getPort()); + target = remote; + } else { + target = (InetSocketAddress) p.getSocketAddress(); } // send the datagram (does not block) send(src, target); - } finally { - if (src != null) Util.offerFirstTemporaryDirectBuffer(src); + Util.offerFirstTemporaryDirectBuffer(src); } + } finally { writeLock.unlock(); } diff --git a/src/java.base/share/classes/sun/nio/ch/DatagramSocketAdaptor.java b/src/java.base/share/classes/sun/nio/ch/DatagramSocketAdaptor.java index 6ea20ec6270b2..4930e1447a3aa 100644 --- a/src/java.base/share/classes/sun/nio/ch/DatagramSocketAdaptor.java +++ b/src/java.base/share/classes/sun/nio/ch/DatagramSocketAdaptor.java @@ -174,7 +174,9 @@ public SocketAddress getLocalSocketAddress() { @Override public void send(DatagramPacket p) throws IOException { try { - dc.blockingSend(p); + synchronized (p) { + dc.blockingSend(p); + } } catch (AlreadyConnectedException e) { throw new IllegalArgumentException("Connected and packet address differ"); } catch (ClosedChannelException e) { @@ -185,7 +187,9 @@ public void send(DatagramPacket p) throws IOException { @Override public void receive(DatagramPacket p) throws IOException { try { - dc.blockingReceive(p, MILLISECONDS.toNanos(timeout)); + synchronized (p) { + dc.blockingReceive(p, MILLISECONDS.toNanos(timeout)); + } } catch (SocketTimeoutException | ClosedByInterruptException e) { throw e; } catch (InterruptedIOException e) { From 395e404666e51f76270de4de1899aa681ba889c9 Mon Sep 17 00:00:00 2001 From: Abhishek Kumar Date: Thu, 21 Nov 2024 17:39:44 +0000 Subject: [PATCH 74/74] 8344066: Remove SecurityManager uses from the jdk.accessibility module Reviewed-by: prr --- .../accessibility/util/AWTEventMonitor.java | 37 -------- .../accessibility/util/EventQueueMonitor.java | 26 ++---- .../accessibility/util/SwingEventMonitor.java | 89 ------------------- .../accessibility/internal/AccessBridge.java | 29 +----- 4 files changed, 12 insertions(+), 169 deletions(-) diff --git a/src/jdk.accessibility/share/classes/com/sun/java/accessibility/util/AWTEventMonitor.java b/src/jdk.accessibility/share/classes/com/sun/java/accessibility/util/AWTEventMonitor.java index b1b93d795e4a5..0ba0c5123f20e 100644 --- a/src/jdk.accessibility/share/classes/com/sun/java/accessibility/util/AWTEventMonitor.java +++ b/src/jdk.accessibility/share/classes/com/sun/java/accessibility/util/AWTEventMonitor.java @@ -29,7 +29,6 @@ import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; -import sun.awt.AWTPermissions; /** *

The {@code AWTEventMonitor} implements a suite of listeners that are @@ -85,17 +84,6 @@ public static Component getComponentWithFocus() { return componentWithFocus; } - /* - * Check permissions - */ - private static void checkInstallPermission() { - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); - if (security != null) { - security.checkPermission(AWTPermissions.ALL_AWT_EVENTS_PERMISSION); - } - } - /** * Adds the specified listener to receive all {@link EventID#COMPONENT COMPONENT} * events on each component instance in the Java Virtual Machine as they occur. @@ -108,7 +96,6 @@ private static void checkInstallPermission() { */ public static void addComponentListener(ComponentListener l) { if (componentListener == null) { - checkInstallPermission(); awtListener.installListeners(EventID.COMPONENT); } componentListener = AWTEventMulticaster.add(componentListener, l); @@ -190,7 +177,6 @@ public static void removeFocusListener(FocusListener l) { */ public static void addKeyListener(KeyListener l) { if (keyListener == null) { - checkInstallPermission(); awtListener.installListeners(EventID.KEY); } keyListener = AWTEventMulticaster.add(keyListener, l); @@ -222,7 +208,6 @@ public static void removeKeyListener(KeyListener l) { */ public static void addMouseListener(MouseListener l) { if (mouseListener == null) { - checkInstallPermission(); awtListener.installListeners(EventID.MOUSE); } mouseListener = AWTEventMulticaster.add(mouseListener, l); @@ -254,7 +239,6 @@ public static void removeMouseListener(MouseListener l) { */ public static void addMouseMotionListener(MouseMotionListener l) { if (mouseMotionListener == null) { - checkInstallPermission(); awtListener.installListeners(EventID.MOTION); } mouseMotionListener = AWTEventMulticaster.add(mouseMotionListener, l); @@ -286,7 +270,6 @@ public static void removeMouseMotionListener(MouseMotionListener l) { */ public static void addWindowListener(WindowListener l) { if (windowListener == null) { - checkInstallPermission(); awtListener.installListeners(EventID.WINDOW); } windowListener = AWTEventMulticaster.add(windowListener, l); @@ -318,7 +301,6 @@ public static void removeWindowListener(WindowListener l) { */ public static void addActionListener(ActionListener l) { if (actionListener == null) { - checkInstallPermission(); awtListener.installListeners(EventID.ACTION); } actionListener = AWTEventMulticaster.add(actionListener, l); @@ -351,7 +333,6 @@ public static void removeActionListener(ActionListener l) { */ public static void addAdjustmentListener(AdjustmentListener l) { if (adjustmentListener == null) { - checkInstallPermission(); awtListener.installListeners(EventID.ADJUSTMENT); } adjustmentListener = AWTEventMulticaster.add(adjustmentListener, l); @@ -383,7 +364,6 @@ public static void removeAdjustmentListener(AdjustmentListener l) { */ public static void addItemListener(ItemListener l) { if (itemListener == null) { - checkInstallPermission(); awtListener.installListeners(EventID.ITEM); } itemListener = AWTEventMulticaster.add(itemListener, l); @@ -415,7 +395,6 @@ public static void removeItemListener(ItemListener l) { */ public static void addTextListener(TextListener l) { if (textListener == null) { - checkInstallPermission(); awtListener.installListeners(EventID.TEXT); } textListener = AWTEventMulticaster.add(textListener, l); @@ -668,8 +647,6 @@ protected void installListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } break; @@ -714,8 +691,6 @@ protected void installListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } // [PK] CheckboxMenuItem isn't a component but it does // implement Interface ItemSelectable!! @@ -755,8 +730,6 @@ protected void installListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } break; @@ -776,8 +749,6 @@ protected void installListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } break; @@ -881,8 +852,6 @@ protected void removeListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } break; @@ -921,8 +890,6 @@ protected void removeListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } // [PK] CheckboxMenuItem isn't a component but it does // implement Interface ItemSelectable!! @@ -955,8 +922,6 @@ protected void removeListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } break; @@ -973,8 +938,6 @@ protected void removeListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } break; diff --git a/src/jdk.accessibility/share/classes/com/sun/java/accessibility/util/EventQueueMonitor.java b/src/jdk.accessibility/share/classes/com/sun/java/accessibility/util/EventQueueMonitor.java index cb630223c49b7..9ef9482e3ec25 100644 --- a/src/jdk.accessibility/share/classes/com/sun/java/accessibility/util/EventQueueMonitor.java +++ b/src/jdk.accessibility/share/classes/com/sun/java/accessibility/util/EventQueueMonitor.java @@ -29,8 +29,6 @@ import java.awt.*; import java.awt.event.*; import javax.accessibility.*; -import java.security.AccessController; -import java.security.PrivilegedAction; /** * The {@code EventQueueMonitor} class provides key core functionality for Assistive @@ -142,24 +140,16 @@ static void queueComponentEvent(ComponentEvent e) { /** * Tell the {@code EventQueueMonitor} to start listening for events. */ - @SuppressWarnings("removal") public static void maybeInitialize() { if (cedt == null) { - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Void run() { - try { - long eventMask = AWTEvent.WINDOW_EVENT_MASK | - AWTEvent.FOCUS_EVENT_MASK | - AWTEvent.MOUSE_MOTION_EVENT_MASK; - - Toolkit.getDefaultToolkit().addAWTEventListener(new EventQueueMonitor(), eventMask); - } catch (Exception e) { - } - return null; - } - } - ); + try { + long eventMask = AWTEvent.WINDOW_EVENT_MASK | + AWTEvent.FOCUS_EVENT_MASK | + AWTEvent.MOUSE_MOTION_EVENT_MASK; + + Toolkit.getDefaultToolkit().addAWTEventListener(new EventQueueMonitor(), eventMask); + } catch (Exception e) { + } } } diff --git a/src/jdk.accessibility/share/classes/com/sun/java/accessibility/util/SwingEventMonitor.java b/src/jdk.accessibility/share/classes/com/sun/java/accessibility/util/SwingEventMonitor.java index df14d2c0da65b..f6f3bb686b184 100644 --- a/src/jdk.accessibility/share/classes/com/sun/java/accessibility/util/SwingEventMonitor.java +++ b/src/jdk.accessibility/share/classes/com/sun/java/accessibility/util/SwingEventMonitor.java @@ -976,8 +976,6 @@ protected void installListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } break; @@ -1001,8 +999,6 @@ protected void installListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } // Look for components which support CellEditor listeners @@ -1023,8 +1019,6 @@ protected void installListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } break; @@ -1050,8 +1044,6 @@ protected void installListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } // Look for components which support the getModel method @@ -1078,10 +1070,7 @@ protected void installListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } - break; case EventID.COLUMNMODEL: @@ -1101,8 +1090,6 @@ protected void installListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } break; @@ -1126,8 +1113,6 @@ protected void installListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } // Look for components which support Document listeners @@ -1148,8 +1133,6 @@ protected void installListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } // Add the monitor as a PropertyChangeListener for document // change events from text components. @@ -1174,8 +1157,6 @@ protected void installListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } } break; @@ -1210,8 +1191,6 @@ protected void installListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } break; @@ -1234,8 +1213,6 @@ protected void installListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } // Look for selection models which support ListSelectionListeners @@ -1257,8 +1234,6 @@ protected void installListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } break; @@ -1278,8 +1253,6 @@ protected void installListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } break; @@ -1302,8 +1275,6 @@ protected void installListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } // Look for components which support getPopupMenu @@ -1329,8 +1300,6 @@ protected void installListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } break; @@ -1350,8 +1319,6 @@ protected void installListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } break; @@ -1371,8 +1338,6 @@ protected void installListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } break; @@ -1396,8 +1361,6 @@ protected void installListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } // Look for components which support UndoableEdit listeners @@ -1418,8 +1381,6 @@ protected void installListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } break; @@ -1442,8 +1403,6 @@ protected void installListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } break; @@ -1466,8 +1425,6 @@ protected void installListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } // Look for components which support the getSelectionModel method @@ -1489,8 +1446,6 @@ protected void installListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } break; @@ -1622,8 +1577,6 @@ protected void removeListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } break; @@ -1646,8 +1599,6 @@ protected void removeListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } // Look for components which support CellEditor listeners @@ -1665,8 +1616,6 @@ protected void removeListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } break; @@ -1689,8 +1638,6 @@ protected void removeListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } // Look for components which support the getModel method @@ -1714,8 +1661,6 @@ protected void removeListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } break; @@ -1735,8 +1680,6 @@ protected void removeListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } break; @@ -1759,8 +1702,6 @@ protected void removeListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } // Look for components which support Document listeners @@ -1778,8 +1719,6 @@ protected void removeListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } break; @@ -1810,8 +1749,6 @@ protected void removeListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } break; @@ -1831,8 +1768,6 @@ protected void removeListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } // Look for selection models which support @@ -1853,8 +1788,6 @@ protected void removeListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } break; @@ -1871,8 +1804,6 @@ protected void removeListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } break; @@ -1892,8 +1823,6 @@ protected void removeListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } // Look for components which support getPopupMenu @@ -1916,8 +1845,6 @@ protected void removeListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } break; @@ -1934,8 +1861,6 @@ protected void removeListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } break; @@ -1952,8 +1877,6 @@ protected void removeListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } break; @@ -1976,8 +1899,6 @@ protected void removeListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } // Look for components which support UndoableEdit listeners @@ -1995,8 +1916,6 @@ protected void removeListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } break; @@ -2013,8 +1932,6 @@ protected void removeListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } break; @@ -2034,8 +1951,6 @@ protected void removeListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } // Look for components which support the getSelectionModel @@ -2056,8 +1971,6 @@ protected void removeListeners(Component c, int eventID) { } } catch (NoSuchMethodException e) { // System.out.println("Exception: " + e.toString()); - } catch (SecurityException e) { - System.out.println("Exception: " + e.toString()); } break; @@ -2512,8 +2425,6 @@ public void propertyChange(PropertyChangeEvent e) { } } catch (NoSuchMethodException e2) { // System.out.println("Exception: " + e2.toString()); - } catch (SecurityException e2) { - System.out.println("Exception: " + e2.toString()); } } diff --git a/src/jdk.accessibility/windows/classes/com/sun/java/accessibility/internal/AccessBridge.java b/src/jdk.accessibility/windows/classes/com/sun/java/accessibility/internal/AccessBridge.java index b5a5943d2d907..e6792b3ef10b4 100644 --- a/src/jdk.accessibility/windows/classes/com/sun/java/accessibility/internal/AccessBridge.java +++ b/src/jdk.accessibility/windows/classes/com/sun/java/accessibility/internal/AccessBridge.java @@ -160,44 +160,23 @@ public final class AccessBridge { initStatic(); } - @SuppressWarnings({"removal", "restricted"}) + @SuppressWarnings("restricted") private static void initStatic() { // Load the appropriate DLLs boolean is32on64 = false; if (System.getProperty("os.arch").equals("x86")) { // 32 bit JRE // Load jabsysinfo.dll so can determine Win bitness - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Void run() { - System.loadLibrary("jabsysinfo"); - return null; - } - }, null, new java.lang.RuntimePermission("loadLibrary.jabsysinfo") - ); + System.loadLibrary("jabsysinfo"); if (isSysWow()) { // 32 bit JRE on 64 bit OS is32on64 = true; - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Void run() { - System.loadLibrary("javaaccessbridge-32"); - return null; - } - }, null, new java.lang.RuntimePermission("loadLibrary.javaaccessbridge-32") - ); + System.loadLibrary("javaaccessbridge-32"); } } if (!is32on64) { // 32 bit JRE on 32 bit OS or 64 bit JRE on 64 bit OS - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Void run() { - System.loadLibrary("javaaccessbridge"); - return null; - } - }, null, new java.lang.RuntimePermission("loadLibrary.javaaccessbridge") - ); + System.loadLibrary("javaaccessbridge"); } }