From cf1eb58d6723ca3856687bf52167455eece2a260 Mon Sep 17 00:00:00 2001 From: Matthias Baesken Date: Wed, 4 Dec 2024 08:11:33 +0000 Subject: [PATCH 01/43] 8344935: [ubsan]: javaThread.hpp:1241:52: runtime error: load of value 9831830, which is not a valid value for type 'freeze_result' Co-authored-by: Richard Reingruber Reviewed-by: rrich, pchilanomate --- src/hotspot/share/runtime/continuationFreezeThaw.cpp | 7 ++++++- src/hotspot/share/runtime/javaThread.cpp | 6 +++++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/src/hotspot/share/runtime/continuationFreezeThaw.cpp b/src/hotspot/share/runtime/continuationFreezeThaw.cpp index 18beb10f0b4..a6c8e64e55e 100644 --- a/src/hotspot/share/runtime/continuationFreezeThaw.cpp +++ b/src/hotspot/share/runtime/continuationFreezeThaw.cpp @@ -256,7 +256,9 @@ class Config { using OopT = std::conditional_t; static freeze_result freeze(JavaThread* thread, intptr_t* const sp) { - return freeze_internal(thread, sp); + freeze_result res = freeze_internal(thread, sp); + JFR_ONLY(assert((res == freeze_ok) || (res == thread->last_freeze_fail_result()), "freeze failure not set")); + return res; } static freeze_result freeze_preempt(JavaThread* thread, intptr_t* const sp) { @@ -1722,6 +1724,9 @@ static inline freeze_result freeze_internal(JavaThread* current, intptr_t* const log_develop_debug(continuations)("PINNED due to critical section/hold monitor"); verify_continuation(cont.continuation()); freeze_result res = entry->is_pinned() ? freeze_pinned_cs : freeze_pinned_monitor; + if (!preempt) { + JFR_ONLY(current->set_last_freeze_fail_result(res);) + } log_develop_trace(continuations)("=== end of freeze (fail %d)", res); // Avoid Thread.yield() loops without safepoint polls. if (SafepointMechanism::should_process(current) && !preempt) { diff --git a/src/hotspot/share/runtime/javaThread.cpp b/src/hotspot/share/runtime/javaThread.cpp index fd9f75c41b4..5123ab69ff3 100644 --- a/src/hotspot/share/runtime/javaThread.cpp +++ b/src/hotspot/share/runtime/javaThread.cpp @@ -518,6 +518,10 @@ JavaThread::JavaThread(MemTag mem_tag) : _SleepEvent(ParkEvent::Allocate(this)), +#if INCLUDE_JFR + _last_freeze_fail_result(freeze_ok), +#endif + _lock_stack(this), _om_cache(this) { set_jni_functions(jni_functions()); @@ -2361,4 +2365,4 @@ void JavaThread::post_vthread_pinned_event(EventVirtualThreadPinned* event, cons event->commit(); } } -#endif \ No newline at end of file +#endif From 38927fc5900184d6231f3da08dca9fc30711816c Mon Sep 17 00:00:00 2001 From: Tom Rodriguez Date: Wed, 4 Dec 2024 08:31:55 +0000 Subject: [PATCH 02/43] 8343213: TEST_BUG: [Graal] java/lang/ref/Basic.java fails Reviewed-by: mchung --- test/jdk/java/lang/ref/Basic.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/jdk/java/lang/ref/Basic.java b/test/jdk/java/lang/ref/Basic.java index deb9ec34826..abed7fdcd64 100644 --- a/test/jdk/java/lang/ref/Basic.java +++ b/test/jdk/java/lang/ref/Basic.java @@ -46,8 +46,8 @@ protected void finalize() { }; protected void finalize() { - Basic.finalized = true; System.err.println("Finalized " + this); + Basic.finalized = true; } public static class Sub { }; From 3d49665b85619038c082566b0bc38c0ebe5f752e Mon Sep 17 00:00:00 2001 From: Jaikiran Pai Date: Wed, 4 Dec 2024 09:23:57 +0000 Subject: [PATCH 03/43] 8345286: Remove use of SecurityManager API from misc areas Reviewed-by: alanb, kevinw, sgehwolf --- .../platform/CgroupSubsystemController.java | 19 ++-- .../platform/CgroupSubsystemFactory.java | 12 +-- .../jdk/internal/platform/CgroupUtil.java | 92 ------------------- .../platform/cgroupv2/CgroupV2Subsystem.java | 13 +-- .../share/classes/java/io/FilePermission.java | 1 - .../share/classes/java/lang/String.java | 2 - .../share/classes/java/lang/System.java | 2 - .../java/lang/invoke/ClassSpecializer.java | 1 - .../java/lang/reflect/ProxyGenerator.java | 1 - .../share/classes/java/net/URLConnection.java | 1 - .../javax/crypto/JceSecurity.java.template | 1 - .../jdk/internal/loader/NativeLibraries.java | 11 +-- .../jdk/internal/logger/LazyLoggers.java | 2 - .../jdk/internal/misc/InnocuousThread.java | 3 +- .../share/classes/jdk/internal/perf/Perf.java | 64 +------------ .../jdk/internal/perf/PerfCounter.java | 7 +- .../classes/jdk/internal/ref/Cleaner.java | 18 ++-- .../internal/reflect/ReflectionFactory.java | 17 ---- .../sun/net/www/http/KeepAliveStream.java | 1 - .../sun/management/VMManagementImpl.java | 16 +--- .../incubator/vector/VectorIntrinsics.java | 9 +- .../protocol/local/PerfDataBuffer.java | 11 +-- 22 files changed, 43 insertions(+), 261 deletions(-) delete mode 100644 src/java.base/linux/classes/jdk/internal/platform/CgroupUtil.java diff --git a/src/java.base/linux/classes/jdk/internal/platform/CgroupSubsystemController.java b/src/java.base/linux/classes/jdk/internal/platform/CgroupSubsystemController.java index 38be8628fb4..17bc60ef863 100644 --- a/src/java.base/linux/classes/jdk/internal/platform/CgroupSubsystemController.java +++ b/src/java.base/linux/classes/jdk/internal/platform/CgroupSubsystemController.java @@ -1,5 +1,6 @@ /* * Copyright (c) 2020, 2022, 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 @@ -28,8 +29,8 @@ import java.io.IOException; import java.io.UncheckedIOException; import java.math.BigInteger; +import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Optional; @@ -61,13 +62,13 @@ public interface CgroupSubsystemController { public static String getStringValue(CgroupSubsystemController controller, String param) { if (controller == null) return null; - try { - return CgroupUtil.readStringValue(controller, param); - } - catch (IOException e) { + Path filePath = Path.of(controller.path(), param); + try (Stream lines = Files.lines(filePath)) { + Optional firstLine = lines.findFirst(); + return firstLine.orElse(null); + } catch (UncheckedIOException | IOException e) { return null; } - } /** @@ -92,8 +93,8 @@ public static long getLongValueMatchingLine(CgroupSubsystemController controller return retval; } try { - Path filePath = Paths.get(controller.path(), param); - List lines = CgroupUtil.readAllLinesPrivileged(filePath); + Path filePath = Path.of(controller.path(), param); + List lines = Files.readAllLines(filePath); for (String line : lines) { if (line.startsWith(match)) { retval = conversion.apply(line); @@ -161,7 +162,7 @@ public static double getDoubleValue(CgroupSubsystemController controller, String public static long getLongEntry(CgroupSubsystemController controller, String param, String entryname, long defaultRetval) { if (controller == null) return defaultRetval; - try (Stream lines = CgroupUtil.readFilePrivileged(Paths.get(controller.path(), param))) { + try (Stream lines = Files.lines(Path.of(controller.path(), param))) { Optional result = lines.map(line -> line.split(" ")) .filter(line -> (line.length == 2 && diff --git a/src/java.base/linux/classes/jdk/internal/platform/CgroupSubsystemFactory.java b/src/java.base/linux/classes/jdk/internal/platform/CgroupSubsystemFactory.java index 0a6d9958d11..d963c46f079 100644 --- a/src/java.base/linux/classes/jdk/internal/platform/CgroupSubsystemFactory.java +++ b/src/java.base/linux/classes/jdk/internal/platform/CgroupSubsystemFactory.java @@ -1,5 +1,6 @@ /* * Copyright (c) 2020, 2022, 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 @@ -29,8 +30,8 @@ import java.io.UncheckedIOException; import java.lang.System.Logger; import java.lang.System.Logger.Level; +import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Collections; import java.util.HashMap; import java.util.List; @@ -140,7 +141,7 @@ public static Optional determineType(String mountInfo, String cgroups, String selfCgroup) throws IOException { final Map infos = new HashMap<>(); - List lines = CgroupUtil.readAllLinesPrivileged(Paths.get(cgroups)); + List lines = Files.readAllLines(Path.of(cgroups)); for (String line : lines) { if (line.startsWith("#")) { continue; @@ -180,7 +181,7 @@ public static Optional determineType(String mountInfo, // However, continuing in that case does not make sense as we'd need // information from mountinfo for the mounted controller paths which we wouldn't // find anyway in that case. - lines = CgroupUtil.readAllLinesPrivileged(Paths.get(mountInfo)); + lines = Files.readAllLines(Path.of(mountInfo)); boolean anyCgroupMounted = false; for (String line: lines) { boolean cgroupsControllerFound = amendCgroupInfos(line, infos, isCgroupsV2); @@ -196,8 +197,7 @@ public static Optional determineType(String mountInfo, // See: // setCgroupV1Path() for the action run for cgroups v1 systems // setCgroupV2Path() for the action run for cgroups v2 systems - try (Stream selfCgroupLines = - CgroupUtil.readFilePrivileged(Paths.get(selfCgroup))) { + try (Stream selfCgroupLines = Files.lines(Path.of(selfCgroup))) { Consumer action = (tokens -> setCgroupV1Path(infos, tokens)); if (isCgroupsV2) { action = (tokens -> setCgroupV2Path(infos, tokens)); @@ -311,7 +311,7 @@ private static boolean amendCgroupInfos(String mntInfoLine, String mountPath = lineMatcher.group(2); String fsType = lineMatcher.group(3); if (fsType.equals("cgroup")) { - Path p = Paths.get(mountPath); + Path p = Path.of(mountPath); String[] controllerNames = p.getFileName().toString().split(","); for (String controllerName: controllerNames) { switch (controllerName) { diff --git a/src/java.base/linux/classes/jdk/internal/platform/CgroupUtil.java b/src/java.base/linux/classes/jdk/internal/platform/CgroupUtil.java deleted file mode 100644 index dbe8a85b2b2..00000000000 --- a/src/java.base/linux/classes/jdk/internal/platform/CgroupUtil.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (c) 2020, Red Hat Inc. - * 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.platform; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.UncheckedIOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.security.AccessController; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; -import java.util.List; -import java.util.stream.Stream; - -public final class CgroupUtil { - - @SuppressWarnings("removal") - public static Stream readFilePrivileged(Path path) throws IOException { - try { - PrivilegedExceptionAction> pea = () -> Files.lines(path); - return AccessController.doPrivileged(pea); - } catch (PrivilegedActionException e) { - unwrapIOExceptionAndRethrow(e); - throw new InternalError(e.getCause()); - } catch (UncheckedIOException e) { - throw e.getCause(); - } - } - - static void unwrapIOExceptionAndRethrow(PrivilegedActionException pae) throws IOException { - Throwable x = pae.getCause(); - if (x instanceof IOException) - throw (IOException) x; - if (x instanceof RuntimeException) - throw (RuntimeException) x; - if (x instanceof Error) - throw (Error) x; - } - - static String readStringValue(CgroupSubsystemController controller, String param) throws IOException { - PrivilegedExceptionAction pea = () -> - Files.newBufferedReader(Paths.get(controller.path(), param)); - try (@SuppressWarnings("removal") BufferedReader bufferedReader = - AccessController.doPrivileged(pea)) { - String line = bufferedReader.readLine(); - return line; - } catch (PrivilegedActionException e) { - unwrapIOExceptionAndRethrow(e); - throw new InternalError(e.getCause()); - } catch (UncheckedIOException e) { - throw e.getCause(); - } - } - - @SuppressWarnings("removal") - public static List readAllLinesPrivileged(Path path) throws IOException { - try { - PrivilegedExceptionAction> pea = () -> Files.readAllLines(path); - return AccessController.doPrivileged(pea); - } catch (PrivilegedActionException e) { - unwrapIOExceptionAndRethrow(e); - throw new InternalError(e.getCause()); - } catch (UncheckedIOException e) { - throw e.getCause(); - } - } -} diff --git a/src/java.base/linux/classes/jdk/internal/platform/cgroupv2/CgroupV2Subsystem.java b/src/java.base/linux/classes/jdk/internal/platform/cgroupv2/CgroupV2Subsystem.java index ddb4d8e2718..aa618766b38 100644 --- a/src/java.base/linux/classes/jdk/internal/platform/cgroupv2/CgroupV2Subsystem.java +++ b/src/java.base/linux/classes/jdk/internal/platform/cgroupv2/CgroupV2Subsystem.java @@ -1,5 +1,6 @@ /* * Copyright (c) 2020, 2022, 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 @@ -27,15 +28,16 @@ import java.io.IOException; import java.io.UncheckedIOException; -import java.nio.file.Paths; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.stream.Collectors; +import java.util.stream.Stream; import jdk.internal.platform.CgroupInfo; import jdk.internal.platform.CgroupSubsystem; import jdk.internal.platform.CgroupSubsystemController; -import jdk.internal.platform.CgroupUtil; public class CgroupV2Subsystem implements CgroupSubsystem { @@ -328,10 +330,9 @@ public long getBlkIOServiced() { } private long sumTokensIOStat(Function mapFunc) { - try { - return CgroupUtil.readFilePrivileged(Paths.get(unified.path(), "io.stat")) - .map(mapFunc) - .collect(Collectors.summingLong(e -> e)); + try (Stream lines = Files.lines(Path.of(unified.path(), "io.stat"))) { + return lines.map(mapFunc) + .collect(Collectors.summingLong(e -> e)); } catch (UncheckedIOException | IOException e) { return CgroupSubsystem.LONG_RETVAL_UNLIMITED; } diff --git a/src/java.base/share/classes/java/io/FilePermission.java b/src/java.base/share/classes/java/io/FilePermission.java index 30fa3978638..1330766b078 100644 --- a/src/java.base/share/classes/java/io/FilePermission.java +++ b/src/java.base/share/classes/java/io/FilePermission.java @@ -283,7 +283,6 @@ public FilePermission newPermUsingAltPath(FilePermission input) { * @param mask the actions mask to use. * */ - @SuppressWarnings("removal") private void init(int mask) { if ((mask & ALL) != mask) throw new IllegalArgumentException("invalid actions mask"); diff --git a/src/java.base/share/classes/java/lang/String.java b/src/java.base/share/classes/java/lang/String.java index e497e8faa6c..033d32611b0 100644 --- a/src/java.base/share/classes/java/lang/String.java +++ b/src/java.base/share/classes/java/lang/String.java @@ -549,7 +549,6 @@ public String(byte[] bytes, int offset, int length, Charset charset) { * Important: parameter order of this method is deliberately changed in order to * disambiguate it against other similar methods of this class. */ - @SuppressWarnings("removal") private String(Charset charset, byte[] bytes, int offset, int length) { if (length == 0) { this.value = "".value; @@ -787,7 +786,6 @@ static String newStringNoRepl(byte[] src, Charset cs) throws CharacterCodingExce } } - @SuppressWarnings("removal") private static String newStringNoRepl1(byte[] src, Charset cs) { int len = src.length; if (len == 0) { diff --git a/src/java.base/share/classes/java/lang/System.java b/src/java.base/share/classes/java/lang/System.java index 11c77d48bf0..87aca3e1ffd 100644 --- a/src/java.base/share/classes/java/lang/System.java +++ b/src/java.base/share/classes/java/lang/System.java @@ -1379,7 +1379,6 @@ public static LoggerFinder getLoggerFinder() { private static volatile LoggerFinder service; - @SuppressWarnings("removal") static LoggerFinder accessProvider() { // We do not need to synchronize: LoggerFinderLoader will // always return the same instance, so if we don't have it, @@ -1483,7 +1482,6 @@ public static Logger getLogger(String name) { * * @since 9 */ - @SuppressWarnings("removal") @CallerSensitive public static Logger getLogger(String name, ResourceBundle bundle) { final ResourceBundle rb = Objects.requireNonNull(bundle); diff --git a/src/java.base/share/classes/java/lang/invoke/ClassSpecializer.java b/src/java.base/share/classes/java/lang/invoke/ClassSpecializer.java index 8f934d6d67c..e03504a749b 100644 --- a/src/java.base/share/classes/java/lang/invoke/ClassSpecializer.java +++ b/src/java.base/share/classes/java/lang/invoke/ClassSpecializer.java @@ -578,7 +578,6 @@ S loadSpecies(S speciesData) { * @param speciesData what species we are generating * @return the generated concrete TopClass class */ - @SuppressWarnings("removal") Class generateConcreteSpeciesCode(String className, ClassSpecializer.SpeciesData speciesData) { byte[] classFile = generateConcreteSpeciesCodeFile(className, speciesData); var lookup = new MethodHandles.Lookup(topClass); diff --git a/src/java.base/share/classes/java/lang/reflect/ProxyGenerator.java b/src/java.base/share/classes/java/lang/reflect/ProxyGenerator.java index 96e0a7e729f..3b34453bc3f 100644 --- a/src/java.base/share/classes/java/lang/reflect/ProxyGenerator.java +++ b/src/java.base/share/classes/java/lang/reflect/ProxyGenerator.java @@ -103,7 +103,6 @@ final class ProxyGenerator { /** * debugging flag for saving generated class files */ - @SuppressWarnings("removal") private static final boolean SAVE_GENERATED_FILES = Boolean.getBoolean("jdk.proxy.ProxyGenerator.saveGeneratedFiles"); diff --git a/src/java.base/share/classes/java/net/URLConnection.java b/src/java.base/share/classes/java/net/URLConnection.java index 209b84de200..69f71942561 100644 --- a/src/java.base/share/classes/java/net/URLConnection.java +++ b/src/java.base/share/classes/java/net/URLConnection.java @@ -1388,7 +1388,6 @@ private ContentHandler lookupContentHandlerClassFor(String contentType) { return UnknownContentHandler.INSTANCE; } - @SuppressWarnings("removal") private ContentHandler lookupContentHandlerViaProvider(String contentType) { ClassLoader cl = ClassLoader.getSystemClassLoader(); diff --git a/src/java.base/share/classes/javax/crypto/JceSecurity.java.template b/src/java.base/share/classes/javax/crypto/JceSecurity.java.template index 8b64b452b11..01282394b57 100644 --- a/src/java.base/share/classes/javax/crypto/JceSecurity.java.template +++ b/src/java.base/share/classes/javax/crypto/JceSecurity.java.template @@ -290,7 +290,6 @@ final class JceSecurity { } } - // This is called from within an doPrivileged block. private static void setupJurisdictionPolicies() throws Exception { // Sanity check the crypto.policy Security property. Single diff --git a/src/java.base/share/classes/jdk/internal/loader/NativeLibraries.java b/src/java.base/share/classes/jdk/internal/loader/NativeLibraries.java index 02dc79f0288..44eaab0e83a 100644 --- a/src/java.base/share/classes/jdk/internal/loader/NativeLibraries.java +++ b/src/java.base/share/classes/jdk/internal/loader/NativeLibraries.java @@ -30,8 +30,6 @@ import java.io.File; import java.io.IOException; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.ArrayDeque; import java.util.Deque; import java.util.function.BiFunction; @@ -323,18 +321,13 @@ boolean open() { return load(this, name, isBuiltin, throwExceptionIfFail()); } - @SuppressWarnings("removal") private boolean throwExceptionIfFail() { if (loadLibraryOnlyIfPresent) return true; // If the file exists but fails to load, UnsatisfiedLinkException thrown by the VM // will include the error message from dlopen to provide diagnostic information - return AccessController.doPrivileged(new PrivilegedAction<>() { - public Boolean run() { - File file = new File(name); - return file.exists(); - } - }); + File file = new File(name); + return file.exists(); } /* 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 885e2e8c4d7..628d768d9ce 100644 --- a/src/java.base/share/classes/jdk/internal/logger/LazyLoggers.java +++ b/src/java.base/share/classes/jdk/internal/logger/LazyLoggers.java @@ -342,8 +342,6 @@ private static LoggerFinder accessLoggerFinder() { // no need to lock: it doesn't matter if we call // getLoggerFinder() twice - since LoggerFinder already caches // the result. - // This is just an optimization to avoid the cost of calling - // doPrivileged every time. prov = LoggerFinder.getLoggerFinder(); if (prov instanceof TemporaryLoggerFinder) return prov; provider = prov; diff --git a/src/java.base/share/classes/jdk/internal/misc/InnocuousThread.java b/src/java.base/share/classes/jdk/internal/misc/InnocuousThread.java index ca2fcf11e99..4f7811faf34 100644 --- a/src/java.base/share/classes/jdk/internal/misc/InnocuousThread.java +++ b/src/java.base/share/classes/jdk/internal/misc/InnocuousThread.java @@ -28,10 +28,9 @@ import java.util.concurrent.atomic.AtomicInteger; /** - * A thread that has no permissions, is not a member of any user-defined + * A thread that is not a member of any user-defined * ThreadGroup and supports the ability to erase ThreadLocals. */ -@SuppressWarnings("removal") public final class InnocuousThread extends Thread { private static final jdk.internal.misc.Unsafe UNSAFE; private static final long THREAD_LOCALS; diff --git a/src/java.base/share/classes/jdk/internal/perf/Perf.java b/src/java.base/share/classes/jdk/internal/perf/Perf.java index e764fe79273..ada89dcf2e0 100644 --- a/src/java.base/share/classes/jdk/internal/perf/Perf.java +++ b/src/java.base/share/classes/jdk/internal/perf/Perf.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 @@ -25,8 +25,6 @@ package jdk.internal.perf; import java.nio.ByteBuffer; -import java.security.Permission; -import java.security.PrivilegedAction; import java.io.IOException; import sun.nio.cs.UTF_8; @@ -49,7 +47,6 @@ * @author Brian Doherty * @since 1.4.2 * @see #getPerf - * @see jdk.internal.perf.Perf.GetPerfAction * @see java.nio.ByteBuffer */ public final class Perf { @@ -58,46 +55,6 @@ public final class Perf { private Perf() { } // prevent instantiation - /** - * The GetPerfAction class is a convenience class for acquiring access - * to the singleton Perf instance using the - * AccessController.doPrivileged() method. - *

- * An instance of this class can be used as the argument to - * AccessController.doPrivileged(PrivilegedAction). - *

Here is a suggested idiom for use of this class: - * - *

{@code
-     * class MyTrustedClass {
-     *   private static final Perf perf =
-     *       AccessController.doPrivileged(new Perf.GetPerfAction());
-     *   ...
-     * }
-     * }
- *

- * In the presence of a security manager, the MyTrustedClass - * class in the above example will need to be granted the - * "sun.misc.Perf.getPerf" RuntimePermission - * permission in order to successfully acquire the singleton Perf instance. - *

- * Please note that the "sun.misc.Perf.getPerf" permission - * is not a JDK specified permission. - * - * @see java.security.AccessController#doPrivileged(PrivilegedAction) - * @see java.lang.RuntimePermission - */ - public static class GetPerfAction implements PrivilegedAction - { - /** - * Run the Perf.getPerf() method in a privileged context. - * - * @see #getPerf - */ - public Perf run() { - return getPerf(); - } - } - /** * Return a reference to the singleton Perf instance. *

@@ -106,11 +63,6 @@ public Perf run() { * for accessing the instrumentation buffer for this or another local * Java virtual machine. *

- * If a security manager is installed, its checkPermission - * method is called with a RuntimePermission with a target - * of "sun.misc.Perf.getPerf". A security exception will result - * if the caller has not been granted this permission. - *

* Access to the returned Perf object should be protected * by its caller and not passed on to untrusted code. This object can * be used to attach to the instrumentation buffer provided by this Java @@ -119,26 +71,12 @@ public Perf run() { * information. API's built on top of this interface may want to provide * finer grained access control to the contents of individual * instrumentation objects contained within the buffer. - *

- * Please note that the "sun.misc.Perf.getPerf" permission - * is not a JDK specified permission. * * @return A reference to the singleton Perf instance. - * @throws SecurityException if a security manager exists and its - * checkPermission method doesn't allow access - * to the "jdk.internal.perf.Perf.getPerf"" target. - * @see java.lang.RuntimePermission * @see #attach */ public static Perf getPerf() { - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); - if (security != null) { - Permission perm = new RuntimePermission("jdk.internal.perf.Perf.getPerf"); - security.checkPermission(perm); - } - return instance; } diff --git a/src/java.base/share/classes/jdk/internal/perf/PerfCounter.java b/src/java.base/share/classes/jdk/internal/perf/PerfCounter.java index b0a87c207b1..dfe67ce849c 100644 --- a/src/java.base/share/classes/jdk/internal/perf/PerfCounter.java +++ b/src/java.base/share/classes/jdk/internal/perf/PerfCounter.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 @@ -28,7 +28,6 @@ import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.LongBuffer; -import java.security.AccessController; /** * Performance counter support for internal JRE classes. @@ -48,9 +47,7 @@ * */ public class PerfCounter { - @SuppressWarnings("removal") - private static final Perf perf = - AccessController.doPrivileged(new Perf.GetPerfAction()); + private static final Perf perf = Perf.getPerf(); // Must match values defined in hotspot/src/share/vm/runtime/perfdata.hpp private static final int V_Constant = 1; diff --git a/src/java.base/share/classes/jdk/internal/ref/Cleaner.java b/src/java.base/share/classes/jdk/internal/ref/Cleaner.java index 3a02605577b..ecd1c32167f 100644 --- a/src/java.base/share/classes/jdk/internal/ref/Cleaner.java +++ b/src/java.base/share/classes/jdk/internal/ref/Cleaner.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 @@ -26,8 +26,6 @@ package jdk.internal.ref; import java.lang.ref.*; -import java.security.AccessController; -import java.security.PrivilegedAction; /** @@ -136,21 +134,17 @@ public static Cleaner create(Object ob, Runnable thunk) { /** * Runs this cleaner, if it has not been run before. */ - @SuppressWarnings("removal") public void clean() { if (!remove(this)) return; try { thunk.run(); } catch (final Throwable x) { - AccessController.doPrivileged(new PrivilegedAction<>() { - public Void run() { - if (System.err != null) - new Error("Cleaner terminated abnormally", x) - .printStackTrace(); - System.exit(1); - return null; - }}); + if (System.err != null) { + new Error("Cleaner terminated abnormally", x) + .printStackTrace(); + } + System.exit(1); } } } 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 687e32cdf61..20b390855c9 100644 --- a/src/java.base/share/classes/jdk/internal/reflect/ReflectionFactory.java +++ b/src/java.base/share/classes/jdk/internal/reflect/ReflectionFactory.java @@ -41,7 +41,6 @@ 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; @@ -75,22 +74,6 @@ private ReflectionFactory() { this.langReflectAccess = SharedSecrets.getJavaLangReflectAccess(); } - /** - * A convenience class for acquiring the capability to instantiate - * reflective objects. Use this instead of a raw call to {@link - * #getReflectionFactory} in order to avoid being limited by the - * permissions of your callers. - * - *

An instance of this class can be used as the argument of - * AccessController.doPrivileged. - */ - public static final class GetReflectionFactoryAction - implements PrivilegedAction { - public ReflectionFactory run() { - return getReflectionFactory(); - } - } - /** * Provides the caller with the capability to instantiate reflective * objects. diff --git a/src/java.base/share/classes/sun/net/www/http/KeepAliveStream.java b/src/java.base/share/classes/sun/net/www/http/KeepAliveStream.java index 4ec81e42c37..de7aa016ea3 100644 --- a/src/java.base/share/classes/sun/net/www/http/KeepAliveStream.java +++ b/src/java.base/share/classes/sun/net/www/http/KeepAliveStream.java @@ -154,7 +154,6 @@ public boolean hurry() { } } - @SuppressWarnings("removal") private static void queueForCleanup(KeepAliveCleanerEntry kace) { queue.lock(); try { diff --git a/src/java.management/share/classes/sun/management/VMManagementImpl.java b/src/java.management/share/classes/sun/management/VMManagementImpl.java index 4e2fc26c850..7e1e870acb4 100644 --- a/src/java.management/share/classes/sun/management/VMManagementImpl.java +++ b/src/java.management/share/classes/sun/management/VMManagementImpl.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 @@ -35,8 +35,6 @@ import java.util.List; import java.util.Arrays; import java.util.Collections; -import java.security.AccessController; -import java.security.PrivilegedAction; /** * Implementation of VMManagement interface that accesses the management @@ -203,14 +201,7 @@ public synchronized List getVmArguments() { // Compilation Subsystem public String getCompilerName() { - @SuppressWarnings("removal") - String name = AccessController.doPrivileged( - new PrivilegedAction<>() { - public String run() { - return System.getProperty("sun.management.compiler"); - } - }); - return name; + return System.getProperty("sun.management.compiler"); } public native long getTotalCompileTime(); @@ -255,8 +246,7 @@ private synchronized PerfInstrumentation getPerfInstrumentation() { } // construct PerfInstrumentation object - @SuppressWarnings("removal") - Perf perf = AccessController.doPrivileged(new Perf.GetPerfAction()); + Perf perf = Perf.getPerf(); try { ByteBuffer bb = perf.attach(0); if (bb.capacity() == 0) { diff --git a/src/jdk.incubator.vector/share/classes/jdk/incubator/vector/VectorIntrinsics.java b/src/jdk.incubator.vector/share/classes/jdk/incubator/vector/VectorIntrinsics.java index c0e70ca58e6..266a843083a 100644 --- a/src/jdk.incubator.vector/share/classes/jdk/incubator/vector/VectorIntrinsics.java +++ b/src/jdk.incubator.vector/share/classes/jdk/incubator/vector/VectorIntrinsics.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2022, 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 @@ -26,14 +26,11 @@ import jdk.internal.vm.annotation.ForceInline; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.Objects; /*non-public*/ class VectorIntrinsics { - @SuppressWarnings("removal") - static final int VECTOR_ACCESS_OOB_CHECK = AccessController.doPrivileged((PrivilegedAction) () -> - Integer.getInteger("jdk.incubator.vector.VECTOR_ACCESS_OOB_CHECK", 2)); + static final int VECTOR_ACCESS_OOB_CHECK = + Integer.getInteger("jdk.incubator.vector.VECTOR_ACCESS_OOB_CHECK", 2); @ForceInline static void requireLength(int haveLength, int length) { diff --git a/src/jdk.internal.jvmstat/share/classes/sun/jvmstat/perfdata/monitor/protocol/local/PerfDataBuffer.java b/src/jdk.internal.jvmstat/share/classes/sun/jvmstat/perfdata/monitor/protocol/local/PerfDataBuffer.java index 056671d7841..3c128c6b6b3 100644 --- a/src/jdk.internal.jvmstat/share/classes/sun/jvmstat/perfdata/monitor/protocol/local/PerfDataBuffer.java +++ b/src/jdk.internal.jvmstat/share/classes/sun/jvmstat/perfdata/monitor/protocol/local/PerfDataBuffer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2022, 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 @@ -28,12 +28,8 @@ import jdk.internal.perf.Perf; import sun.jvmstat.monitor.*; import sun.jvmstat.perfdata.monitor.*; -import java.util.*; import java.io.*; import java.nio.ByteBuffer; -import java.nio.channels.FileChannel; -import java.lang.reflect.Constructor; -import java.security.AccessController; /** * The concrete PerfDataBuffer implementation for the local: @@ -45,11 +41,8 @@ * @author Brian Doherty * @since 1.5 */ -// Suppreess unchecked conversion warning at line 34. -//@SuppressWarnings("unchecked") public class PerfDataBuffer extends AbstractPerfDataBuffer { - @SuppressWarnings("removal") - private static final Perf perf = AccessController.doPrivileged(new Perf.GetPerfAction()); + private static final Perf perf = Perf.getPerf(); /** * Create a PerfDataBuffer instance for accessing the specified From 994504c3e1440401a22ad3bdb30413f9db8a7780 Mon Sep 17 00:00:00 2001 From: Fredrik Bredberg Date: Wed, 4 Dec 2024 09:32:33 +0000 Subject: [PATCH 04/43] 8329351: Add runtime/Monitor/TestRecursiveLocking.java for recursive Java monitor stress testing Co-authored-by: Daniel D. Daugherty Reviewed-by: dcubed, coleenp, aboldtch --- test/hotspot/jtreg/TEST.groups | 3 + ...tressWrapper_TestRecursiveLocking_36M.java | 207 +++++++ .../runtime/Monitor/TestRecursiveLocking.java | 568 ++++++++++++++++++ 3 files changed, 778 insertions(+) create mode 100644 test/hotspot/jtreg/runtime/Monitor/StressWrapper_TestRecursiveLocking_36M.java create mode 100644 test/hotspot/jtreg/runtime/Monitor/TestRecursiveLocking.java diff --git a/test/hotspot/jtreg/TEST.groups b/test/hotspot/jtreg/TEST.groups index d68c015496c..4cb84e9f599 100644 --- a/test/hotspot/jtreg/TEST.groups +++ b/test/hotspot/jtreg/TEST.groups @@ -397,6 +397,8 @@ tier1_runtime = \ -runtime/Metaspace/FragmentMetaspace.java \ -runtime/Metaspace/FragmentMetaspaceSimple.java \ -runtime/MirrorFrame/Test8003720.java \ + -runtime/Monitor/StressWrapper_TestRecursiveLocking_36M.java \ + -runtime/Monitor/TestRecursiveLocking.java \ -runtime/modules/LoadUnloadModuleStress.java \ -runtime/modules/ModuleStress/ExportModuleStressTest.java \ -runtime/modules/ModuleStress/ModuleStressGC.java \ @@ -664,6 +666,7 @@ hotspot_tier2_runtime = \ -runtime/CommandLine/OptionsValidation/TestOptionsWithRanges.java \ -runtime/CompressedOops/UseCompressedOops.java \ -runtime/InvocationTests \ + -runtime/Monitor/StressWrapper_TestRecursiveLocking_36M.java \ -runtime/Thread/TestThreadDumpMonitorContention.java \ -:tier1_runtime \ -:hotspot_tier2_runtime_platform_agnostic \ diff --git a/test/hotspot/jtreg/runtime/Monitor/StressWrapper_TestRecursiveLocking_36M.java b/test/hotspot/jtreg/runtime/Monitor/StressWrapper_TestRecursiveLocking_36M.java new file mode 100644 index 00000000000..34bf5da64d9 --- /dev/null +++ b/test/hotspot/jtreg/runtime/Monitor/StressWrapper_TestRecursiveLocking_36M.java @@ -0,0 +1,207 @@ +/* + * 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 id=Xint_outer_inner + * @requires vm.flagless + * @summary Tests recursive locking in -Xint in outer then inner mode. + * @library /testlibrary /test/lib + * @build jdk.test.whitebox.WhiteBox + * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox + * + * @run main/othervm/timeout=240 -Xbootclasspath/a:. + * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI + * -Xint + * -XX:LockingMode=0 + * -ms256m -mx256m + * TestRecursiveLocking 120 1 + * + * @run main/othervm/timeout=240 -Xbootclasspath/a:. + * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI + * -Xint + * -XX:LockingMode=1 + * -ms256m -mx256m + * TestRecursiveLocking 120 1 + * + * @run main/othervm/timeout=240 -Xbootclasspath/a:. + * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI + * -Xint + * -XX:LockingMode=2 + * -ms256m -mx256m + * TestRecursiveLocking 120 1 + */ + +/* + * @test id=Xint_alternate_AB + * @requires vm.flagless + * @summary Tests recursive locking in -Xint in alternate A and B mode. + * @library /testlibrary /test/lib + * @build jdk.test.whitebox.WhiteBox + * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox + * + * @run main/othervm/timeout=240 -Xbootclasspath/a:. + * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI + * -Xint + * -XX:LockingMode=0 + * -ms256m -mx256m + * TestRecursiveLocking 120 2 + * + * @run main/othervm/timeout=240 -Xbootclasspath/a:. + * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI + * -Xint + * -XX:LockingMode=1 + * -ms256m -mx256m + * TestRecursiveLocking 120 2 + * + * @run main/othervm/timeout=240 -Xbootclasspath/a:. + * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI + * -Xint + * -XX:LockingMode=2 + * -ms256m -mx256m + * TestRecursiveLocking 120 2 + */ + +/* + * @test id=C1_outer_inner + * @requires vm.flagless + * @requires vm.compiler1.enabled + * @summary Tests recursive locking in C1 in outer then inner mode. + * @library /testlibrary /test/lib + * @build jdk.test.whitebox.WhiteBox + * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox + * + * @run main/othervm/timeout=240 -Xbootclasspath/a:. + * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI + * -XX:TieredStopAtLevel=1 + * -XX:LockingMode=0 + * -ms256m -mx256m + * TestRecursiveLocking 120 1 + * + * @run main/othervm/timeout=240 -Xbootclasspath/a:. + * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI + * -XX:TieredStopAtLevel=1 + * -XX:LockingMode=1 + * -ms256m -mx256m + * TestRecursiveLocking 120 1 + * + * @run main/othervm/timeout=240 -Xbootclasspath/a:. + * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI + * -XX:TieredStopAtLevel=1 + * -XX:LockingMode=2 + * -ms256m -mx256m + * TestRecursiveLocking 120 1 + */ + +/* + * @test id=C1_alternate_AB + * @requires vm.flagless + * @requires vm.compiler1.enabled + * @summary Tests recursive locking in C1 in alternate A and B mode. + * @library /testlibrary /test/lib + * @build jdk.test.whitebox.WhiteBox + * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox + * + * @run main/othervm/timeout=240 -Xbootclasspath/a:. + * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI + * -XX:TieredStopAtLevel=1 + * -XX:LockingMode=0 + * -ms256m -mx256m + * TestRecursiveLocking 120 2 + * + * @run main/othervm/timeout=240 -Xbootclasspath/a:. + * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI + * -XX:TieredStopAtLevel=1 + * -XX:LockingMode=1 + * -ms256m -mx256m + * TestRecursiveLocking 120 2 + * + * @run main/othervm/timeout=240 -Xbootclasspath/a:. + * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI + * -XX:TieredStopAtLevel=1 + * -XX:LockingMode=2 + * -ms256m -mx256m + * TestRecursiveLocking 120 2 + */ + +/* + * @test id=C2_outer_inner + * @requires vm.flagless + * @requires vm.compiler2.enabled + * @summary Tests recursive locking in C2 in outer then inner mode. + * @library /testlibrary /test/lib + * @build jdk.test.whitebox.WhiteBox + * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox + * + * @run main/othervm/timeout=240 -Xbootclasspath/a:. + * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI + * -XX:-EliminateNestedLocks + * -XX:LockingMode=0 + * -ms256m -mx256m + * TestRecursiveLocking 120 1 + * + * @run main/othervm/timeout=240 -Xbootclasspath/a:. + * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI + * -XX:-EliminateNestedLocks + * -XX:LockingMode=1 + * -ms256m -mx256m + * TestRecursiveLocking 120 1 + * + * @run main/othervm/timeout=240 -Xbootclasspath/a:. + * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI + * -XX:-EliminateNestedLocks + * -XX:LockingMode=2 + * -ms256m -mx256m + * TestRecursiveLocking 120 1 + */ + +/* + * @test id=C2_alternate_AB + * @requires vm.flagless + * @requires vm.compiler2.enabled + * @summary Tests recursive locking in C2 in alternate A and B mode. + * @library /testlibrary /test/lib + * @build jdk.test.whitebox.WhiteBox + * + * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox + * @run main/othervm/timeout=240 -Xbootclasspath/a:. + * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI + * -XX:LockingMode=0 + * -XX:-EliminateNestedLocks + * -ms256m -mx256m + * TestRecursiveLocking 120 2 + * + * @run main/othervm/timeout=240 -Xbootclasspath/a:. + * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI + * -XX:LockingMode=1 + * -XX:-EliminateNestedLocks + * -ms256m -mx256m + * TestRecursiveLocking 120 2 + * + * @run main/othervm/timeout=240 -Xbootclasspath/a:. + * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI + * -XX:LockingMode=2 + * -XX:-EliminateNestedLocks + * -ms256m -mx256m + * TestRecursiveLocking 120 2 + */ diff --git a/test/hotspot/jtreg/runtime/Monitor/TestRecursiveLocking.java b/test/hotspot/jtreg/runtime/Monitor/TestRecursiveLocking.java new file mode 100644 index 00000000000..f9193b6eeb5 --- /dev/null +++ b/test/hotspot/jtreg/runtime/Monitor/TestRecursiveLocking.java @@ -0,0 +1,568 @@ +/* + * 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 id=Xint_outer_inner + * @requires vm.flagless + * @summary Tests recursive locking in -Xint in outer then inner mode. + * @library /testlibrary /test/lib + * @build jdk.test.whitebox.WhiteBox + * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox + * + * @run main/othervm -Xbootclasspath/a:. + * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI + * -Xint + * -XX:LockingMode=0 + * -ms256m -mx256m + * TestRecursiveLocking 5 1 + * + * @run main/othervm -Xbootclasspath/a:. + * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI + * -Xint + * -XX:LockingMode=1 + * -ms256m -mx256m + * TestRecursiveLocking 5 1 + * + * @run main/othervm -Xbootclasspath/a:. + * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI + * -Xint + * -XX:LockingMode=2 + * -ms256m -mx256m + * TestRecursiveLocking 5 1 + */ + +/* + * @test id=Xint_alternate_AB + * @requires vm.flagless + * @summary Tests recursive locking in -Xint in alternate A and B mode. + * @library /testlibrary /test/lib + * @build jdk.test.whitebox.WhiteBox + * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox + * + * @run main/othervm -Xbootclasspath/a:. + * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI + * -Xint + * -XX:LockingMode=0 + * -ms256m -mx256m + * TestRecursiveLocking 5 2 + * + * @run main/othervm -Xbootclasspath/a:. + * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI + * -Xint + * -XX:LockingMode=1 + * -ms256m -mx256m + * TestRecursiveLocking 5 2 + * + * @run main/othervm -Xbootclasspath/a:. + * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI + * -Xint + * -XX:LockingMode=2 + * -ms256m -mx256m + * TestRecursiveLocking 5 2 + */ + +/* + * @test id=C1_outer_inner + * @requires vm.flagless + * @requires vm.compiler1.enabled + * @summary Tests recursive locking in C1 in outer then inner mode. + * @library /testlibrary /test/lib + * @build jdk.test.whitebox.WhiteBox + * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox + * + * @run main/othervm -Xbootclasspath/a:. + * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI + * -XX:TieredStopAtLevel=1 + * -XX:LockingMode=0 + * -ms256m -mx256m + * TestRecursiveLocking 5 1 + * + * @run main/othervm -Xbootclasspath/a:. + * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI + * -XX:TieredStopAtLevel=1 + * -XX:LockingMode=1 + * -ms256m -mx256m + * TestRecursiveLocking 5 1 + * + * @run main/othervm -Xbootclasspath/a:. + * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI + * -XX:TieredStopAtLevel=1 + * -XX:LockingMode=2 + * -ms256m -mx256m + * TestRecursiveLocking 5 1 + */ + +/* + * @test id=C1_alternate_AB + * @requires vm.flagless + * @requires vm.compiler1.enabled + * @summary Tests recursive locking in C1 in alternate A and B mode. + * @library /testlibrary /test/lib + * @build jdk.test.whitebox.WhiteBox + * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox + * + * @run main/othervm -Xbootclasspath/a:. + * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI + * -XX:TieredStopAtLevel=1 + * -XX:LockingMode=0 + * -ms256m -mx256m + * TestRecursiveLocking 5 2 + * + * @run main/othervm -Xbootclasspath/a:. + * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI + * -XX:TieredStopAtLevel=1 + * -XX:LockingMode=1 + * -ms256m -mx256m + * TestRecursiveLocking 5 2 + * + * @run main/othervm -Xbootclasspath/a:. + * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI + * -XX:TieredStopAtLevel=1 + * -XX:LockingMode=2 + * -ms256m -mx256m + * TestRecursiveLocking 5 2 + */ + +/* + * @test id=C2_outer_inner + * @requires vm.flagless + * @requires vm.compiler2.enabled + * @summary Tests recursive locking in C2 in outer then inner mode. + * @library /testlibrary /test/lib + * @build jdk.test.whitebox.WhiteBox + * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox + * + * @run main/othervm -Xbootclasspath/a:. + * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI + * -XX:-EliminateNestedLocks + * -XX:LockingMode=0 + * -ms256m -mx256m + * TestRecursiveLocking 5 1 + * + * @run main/othervm -Xbootclasspath/a:. + * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI + * -XX:-EliminateNestedLocks + * -XX:LockingMode=1 + * -ms256m -mx256m + * TestRecursiveLocking 5 1 + * + * @run main/othervm -Xbootclasspath/a:. + * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI + * -XX:-EliminateNestedLocks + * -XX:LockingMode=2 + * -ms256m -mx256m + * TestRecursiveLocking 5 1 + */ + +/* + * @test id=C2_alternate_AB + * @requires vm.flagless + * @requires vm.compiler2.enabled + * @summary Tests recursive locking in C2 in alternate A and B mode. + * @library /testlibrary /test/lib + * @build jdk.test.whitebox.WhiteBox + * + * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox + * @run main/othervm -Xbootclasspath/a:. + * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI + * -XX:LockingMode=0 + * -XX:-EliminateNestedLocks + * -ms256m -mx256m + * TestRecursiveLocking 5 2 + * + * @run main/othervm -Xbootclasspath/a:. + * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI + * -XX:LockingMode=1 + * -XX:-EliminateNestedLocks + * -ms256m -mx256m + * TestRecursiveLocking 5 2 + * + * @run main/othervm -Xbootclasspath/a:. + * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI + * -XX:LockingMode=2 + * -XX:-EliminateNestedLocks + * -ms256m -mx256m + * TestRecursiveLocking 5 2 + */ + +import jdk.test.lib.Asserts; +import jdk.test.whitebox.WhiteBox; +import jtreg.SkippedException; + +public class TestRecursiveLocking { + static final WhiteBox WB = WhiteBox.getWhiteBox(); + static final int flagLockingMode = WB.getIntVMFlag("LockingMode").intValue(); + static final int constLockStackCapacity = WB.getLockStackCapacity(); + static final int LM_MONITOR = 0; + static final int LM_LEGACY = 1; + static final int LM_LIGHTWEIGHT = 2; + static final int def_mode = 2; + static final int def_n_secs = 30; + static final SyncThread syncThread = new SyncThread(); + + // This SynchronizedObject class and the OUTER followed by INNER testing + // model is adapted from runtime/lockStack/TestLockStackCapacity.java. + static class SynchronizedObject { + private int counter; + + synchronized void runInner(int depth, SynchronizedObject outer) { + counter++; + + // Legacy mode has no lock stack, i.e., there is no limit + // on recursion, so for legacy mode we can't say that + // "outer" must be inflated here, which we can say for all + // the other locking modes. + if (flagLockingMode != LM_LEGACY) { + outer.assertInflated(); + } + + // We haven't reached the stack lock capacity (recursion + // level), so we shouldn't be inflated here. Except for + // monitor mode, which is always inflated. + if (flagLockingMode != LM_MONITOR) { + assertNotInflated(); + } + if (depth == 1) { + return; + } else { + runInner(depth - 1, outer); + } + if (flagLockingMode != LM_MONITOR) { + assertNotInflated(); + } + } + + synchronized void runOuter(int depth, SynchronizedObject inner) { + counter++; + + if (flagLockingMode != LM_MONITOR) { + assertNotInflated(); + } + if (depth == 1) { + inner.runInner(constLockStackCapacity, this); + } else { + runOuter(depth - 1, inner); + } + if (flagLockingMode != LM_LEGACY) { + assertInflated(); + } + } + + // This test nests x recursive locks of INNER, in x recursive + // locks of OUTER. The number x is taken from the max number + // of elements in the lock stack. + public void runOuterInnerTest() { + final SynchronizedObject OUTER = new SynchronizedObject(); + final SynchronizedObject INNER = new SynchronizedObject(); + + // Just checking since they are new objects: + OUTER.assertNotInflated(); + INNER.assertNotInflated(); + + synchronized (OUTER) { + OUTER.counter++; + + if (flagLockingMode != LM_MONITOR) { + OUTER.assertNotInflated(); + } + INNER.assertNotInflated(); + OUTER.runOuter(constLockStackCapacity - 1, INNER); + + if (flagLockingMode != LM_LEGACY) { + OUTER.assertInflated(); + } + if (flagLockingMode != LM_MONITOR) { + INNER.assertNotInflated(); + } + } + + // Verify that the nested monitors have been properly released: + syncThread.verifyCanBeSynced(OUTER); + syncThread.verifyCanBeSynced(INNER); + + Asserts.assertEquals(OUTER.counter, constLockStackCapacity); + Asserts.assertEquals(INNER.counter, constLockStackCapacity); + } + + synchronized void runA(int depth, SynchronizedObject B) { + counter++; + + if (flagLockingMode == LM_LIGHTWEIGHT) { + // First time we lock A, A is the only one on the lock + // stack. + if (counter == 1) { + assertNotInflated(); + } else { + // Second time we want to lock A, the lock stack + // looks like this [A, B]. Lightweight locking + // doesn't allow interleaving ([A, B, A]), instead + // it inflates A and removes it from the lock + // stack. Which leaves us with only [B] on the + // lock stack. After more recursions it will grow + // to [B, B ... B]. + assertInflated(); + } + } else if (flagLockingMode == LM_MONITOR) { + assertInflated(); + } + + // Call runB() at the same depth as runA's depth: + B.runB(depth, this); + } + + synchronized void runB(int depth, SynchronizedObject A) { + counter++; + + if (flagLockingMode != LM_MONITOR) { + // Legacy tolerates endless recursions. While testing + // lightweight we don't go deeper than the size of the + // lock stack, which in this test case will be filled + // with a number of B-elements. See comment in runA() + // above for more info. + assertNotInflated(); + } else { + assertInflated(); + } + + if (depth == 1) { + // Reached LockStackCapacity in depth so we're done. + return; + } else { + A.runA(depth - 1, this); + } + } + + // This test alternates by locking A and B. + public void runAlternateABTest() { + final SynchronizedObject A = new SynchronizedObject(); + final SynchronizedObject B = new SynchronizedObject(); + + // Just checking since they are new objects: + A.assertNotInflated(); + B.assertNotInflated(); + + A.runA(constLockStackCapacity, B); + + // Verify that the nested monitors have been properly released: + syncThread.verifyCanBeSynced(A); + syncThread.verifyCanBeSynced(B); + + Asserts.assertEquals(A.counter, constLockStackCapacity); + Asserts.assertEquals(B.counter, constLockStackCapacity); + if (flagLockingMode == LM_LEGACY) { + A.assertNotInflated(); + } + // Implied else: for LM_MONITOR or LM_LIGHTWEIGHT it can be + // either inflated or not because A is not locked anymore + // and subject to deflation. + + if (flagLockingMode != LM_MONITOR) { + B.assertNotInflated(); + } + } + + void assertNotInflated() { + Asserts.assertFalse(WB.isMonitorInflated(this)); + } + + void assertInflated() { + Asserts.assertTrue(WB.isMonitorInflated(this)); + } + } + + static void usage() { + System.err.println(); + System.err.println("Usage: java TestRecursiveLocking [n_secs]"); + System.err.println(" java TestRecursiveLocking n_secs [mode]"); + System.err.println(); + System.err.println("where:"); + System.err.println(" n_secs ::= > 0"); + System.err.println(" Default n_secs is " + def_n_secs + "."); + System.err.println(" mode ::= 1 - outer and inner"); + System.err.println(" ::= 2 - alternate A and B"); + System.err.println(" Default mode is " + def_mode + "."); + System.exit(1); + } + + public static void main(String... argv) throws Exception { + int mode = def_mode; + int n_secs = def_n_secs; + + if (argv.length != 0 && argv.length != 1 && argv.length != 2) { + usage(); + } else if (argv.length > 0) { + try { + n_secs = Integer.parseInt(argv[0]); + if (n_secs <= 0) { + throw new NumberFormatException("Not > 0: '" + argv[0] + + "'"); + } + } catch (NumberFormatException nfe) { + System.err.println(); + System.err.println(nfe); + System.err.println("ERROR: '" + argv[0] + + "': invalid n_secs value."); + usage(); + } + + if (argv.length > 1) { + try { + mode = Integer.parseInt(argv[1]); + if (mode != 1 && mode != 2) { + throw new NumberFormatException("Not 1 -> 2: '" + + argv[1] + "'"); + } + } catch (NumberFormatException nfe) { + System.err.println(); + System.err.println(nfe); + System.err.println("ERROR: '" + argv[1] + + "': invalid mode value."); + usage(); + } + } + } + + System.out.println("INFO: LockingMode=" + flagLockingMode); + System.out.println("INFO: LockStackCapacity=" + constLockStackCapacity); + System.out.println("INFO: n_secs=" + n_secs); + System.out.println("INFO: mode=" + mode); + + long loopCount = 0; + long endTime = System.currentTimeMillis() + n_secs * 1000; + + syncThread.waitForStart(); + + while (System.currentTimeMillis() < endTime) { + loopCount++; + SynchronizedObject syncObj = new SynchronizedObject(); + switch (mode) { + case 1: + syncObj.runOuterInnerTest(); + break; + + case 2: + syncObj.runAlternateABTest(); + break; + + default: + throw new RuntimeException("bad mode parameter: " + mode); + } + } + + syncThread.setDone(); + try { + syncThread.join(); + } catch (InterruptedException ie) { + // This should not happen. + ie.printStackTrace(); + } + + System.out.println("INFO: main executed " + loopCount + " loops in " + + n_secs + " seconds."); + } +} + +class SyncThread extends Thread { + static final boolean verbose = false; // set to true for debugging + private boolean done = false; + private boolean haveWork = false; + private Object obj; + private Object waiter = new Object(); + + public void run() { + if (verbose) System.out.println("SyncThread: running."); + synchronized (waiter) { + // Let main know that we are running: + if (verbose) System.out.println("SyncThread: notify main running."); + waiter.notify(); + + while (!done) { + if (verbose) System.out.println("SyncThread: waiting."); + try { + waiter.wait(); + } catch (InterruptedException ie) { + // This should not happen. + ie.printStackTrace(); + } + if (haveWork) { + if (verbose) System.out.println("SyncThread: working."); + synchronized (obj) { + } + if (verbose) System.out.println("SyncThread: worked."); + haveWork = false; + waiter.notify(); + if (verbose) System.out.println("SyncThread: notified."); + } + else if (verbose) { + System.out.println("SyncThread: notified without work."); + } + } + } + if (verbose) System.out.println("SyncThread: exiting."); + } + + public void setDone() { + synchronized (waiter) { + if (verbose) System.out.println("main: set done."); + done = true; + waiter.notify(); + } + } + + public void verifyCanBeSynced(Object obj) { + synchronized (waiter) { + if (verbose) System.out.println("main: queueing up work."); + this.obj = obj; + haveWork = true; + if (verbose) System.out.println("main: notifying SyncThread."); + waiter.notify(); + if (verbose) System.out.println("main: waiting for SyncThread."); + while (haveWork) { + try { + waiter.wait(); + } catch (InterruptedException ie) { + // This should not happen. + ie.printStackTrace(); + } + } + if (verbose) System.out.println("main: waited for SyncThread."); + } + } + + public void waitForStart() { + synchronized (waiter) { + this.start(); + + // Wait for SyncThread to actually get running: + if (verbose) System.out.println("main: wait for SyncThread start."); + try { + waiter.wait(); + } catch (InterruptedException ie) { + // This should not happen. + ie.printStackTrace(); + } + if (verbose) System.out.println("main: waited for SyncThread start."); + } + } +} From 56d315da480dcd2198e2000ead301c3be8b27d84 Mon Sep 17 00:00:00 2001 From: Jan Lahoda Date: Wed, 4 Dec 2024 09:47:40 +0000 Subject: [PATCH 05/43] 8343540: Report preview error for inherited effectively-preview methods Reviewed-by: vromero --- .../com/sun/tools/javac/comp/Attr.java | 2 +- .../com/sun/tools/javac/comp/Check.java | 31 +- .../tools/javac/preview/PreviewTest.java | 435 +++++++++++++++++- 3 files changed, 449 insertions(+), 19 deletions(-) diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java index 62c12334629..62f7c15a95f 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java @@ -4728,7 +4728,7 @@ else if (ownOuter.hasTag(CLASS) && site != ownOuter) { chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym); chk.checkSunAPI(tree.pos(), sym); chk.checkProfile(tree.pos(), sym); - chk.checkPreview(tree.pos(), env.info.scope.owner, sym); + chk.checkPreview(tree.pos(), env.info.scope.owner, site, sym); } if (pt.isErroneous()) { diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Check.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Check.java index 5a442bac302..08084b5abed 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Check.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Check.java @@ -1845,7 +1845,8 @@ void checkOverride(JCTree tree, } if (shouldCheckPreview(m, other, origin)) { - checkPreview(tree.pos(), m, other); + checkPreview(TreeInfo.diagnosticPositionFor(m, tree), + m, origin.type, other); } Type mt = types.memberType(origin.type, m); @@ -1925,7 +1926,8 @@ else if (unhandledUnerased.nonEmpty()) { private boolean shouldCheckPreview(MethodSymbol m, MethodSymbol other, ClassSymbol origin) { if (m.owner != origin || //performance - only do the expensive checks when the overridden method is a Preview API: - (other.flags() & PREVIEW_API) == 0) { + ((other.flags() & PREVIEW_API) == 0 && + (other.owner.flags() & PREVIEW_API) == 0)) { return false; } @@ -3828,8 +3830,29 @@ void checkProfile(final DiagnosticPosition pos, final Symbol s) { } void checkPreview(DiagnosticPosition pos, Symbol other, Symbol s) { - if ((s.flags() & PREVIEW_API) != 0 && !preview.participatesInPreview(syms, other, s) && !disablePreviewCheck) { - if ((s.flags() & PREVIEW_REFLECTIVE) == 0) { + checkPreview(pos, other, Type.noType, s); + } + + void checkPreview(DiagnosticPosition pos, Symbol other, Type site, Symbol s) { + boolean sIsPreview; + Symbol previewSymbol; + if ((s.flags() & PREVIEW_API) != 0) { + sIsPreview = true; + previewSymbol= s; + } else if ((s.kind == Kind.MTH || s.kind == Kind.VAR) && + site.tsym != null && + (site.tsym.flags() & PREVIEW_API) == 0 && + (s.owner.flags() & PREVIEW_API) != 0) { + //calling a method, or using a field, whose owner is a preview, but + //using a site that is not a preview. Also produce an error or warning: + sIsPreview = true; + previewSymbol = s.owner; + } else { + sIsPreview = false; + previewSymbol = null; + } + if (sIsPreview && !preview.participatesInPreview(syms, other, s) && !disablePreviewCheck) { + if ((previewSymbol.flags() & PREVIEW_REFLECTIVE) == 0) { if (!preview.isEnabled()) { log.error(pos, Errors.IsPreview(s)); } else { diff --git a/test/langtools/tools/javac/preview/PreviewTest.java b/test/langtools/tools/javac/preview/PreviewTest.java index 24cb3d57dde..ad67ef8ac87 100644 --- a/test/langtools/tools/javac/preview/PreviewTest.java +++ b/test/langtools/tools/javac/preview/PreviewTest.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 @@ -23,7 +23,7 @@ /* * @test - * @bug 8282823 + * @bug 8282823 8343540 * @library /tools/lib * @enablePreview * @modules @@ -229,13 +229,13 @@ public default void test() {} .getOutputLines(Task.OutputKind.DIRECT); List expected = - List.of("IUseIntf2P.java:3:8: compiler.err.is.preview: test()", - "IUseIntfDef2P.java:3:8: compiler.err.is.preview: test()", + List.of("IUseIntf2P.java:4:25: compiler.err.is.preview: test()", + "IUseIntfDef2P.java:4:25: compiler.err.is.preview: test()", "UseClass2P.java:4:17: compiler.err.is.preview: test()", - "UseIntf2P.java:3:8: compiler.err.is.preview: test()", - "UseIntfDef2P.java:3:8: compiler.err.is.preview: test()", + "UseIntf2P.java:4:17: compiler.err.is.preview: test()", + "UseIntfDef2P.java:4:17: compiler.err.is.preview: test()", "UseSubClass12P.java:3:17: compiler.err.is.preview: test()", - "UseSubIntfDef12P.java:2:8: compiler.err.is.preview: test()", + "UseSubIntfDef12P.java:3:17: compiler.err.is.preview: test()", "7 errors"); if (!log.equals(expected)) @@ -257,13 +257,13 @@ public default void test() {} .getOutputLines(Task.OutputKind.DIRECT); expected = - List.of("IUseIntf2P.java:3:8: compiler.warn.is.preview: test()", - "IUseIntfDef2P.java:3:8: compiler.warn.is.preview: test()", + List.of("IUseIntf2P.java:4:25: compiler.warn.is.preview: test()", + "IUseIntfDef2P.java:4:25: compiler.warn.is.preview: test()", "UseClass2P.java:4:17: compiler.warn.is.preview: test()", - "UseIntf2P.java:3:8: compiler.warn.is.preview: test()", - "UseIntfDef2P.java:3:8: compiler.warn.is.preview: test()", + "UseIntf2P.java:4:17: compiler.warn.is.preview: test()", + "UseIntfDef2P.java:4:17: compiler.warn.is.preview: test()", "UseSubClass12P.java:3:17: compiler.warn.is.preview: test()", - "UseSubIntfDef12P.java:2:8: compiler.warn.is.preview: test()", + "UseSubIntfDef12P.java:3:17: compiler.warn.is.preview: test()", "7 warnings"); if (!log.equals(expected)) @@ -392,7 +392,7 @@ public void test() {} .getOutputLines(Task.OutputKind.DIRECT); List expected = - List.of("AbstractP.java:3:17: compiler.err.is.preview: test()", + List.of("AbstractP.java:4:26: compiler.err.is.preview: test()", "ReabstractP.java:4:26: compiler.err.is.preview: test()", "2 errors"); @@ -415,7 +415,7 @@ public void test() {} .getOutputLines(Task.OutputKind.DIRECT); expected = - List.of("AbstractP.java:3:17: compiler.warn.is.preview: test()", + List.of("AbstractP.java:4:26: compiler.warn.is.preview: test()", "ReabstractP.java:4:26: compiler.warn.is.preview: test()", "2 warnings"); @@ -463,6 +463,413 @@ public void test() {} } } + @Test //JDK-8343540: + public void nonPreviewImplementsPreview(Path base) throws Exception { + Path apiSrc = base.resolve("api-src"); + tb.writeJavaFiles(apiSrc, + """ + package preview.api; + @jdk.internal.javac.PreviewFeature(feature=jdk.internal.javac.PreviewFeature.Feature.TEST) + public interface Preview { + public static final int FIELD = 0; + public default void test() {} + } + """, + """ + package preview.api; + @jdk.internal.javac.PreviewFeature(feature=jdk.internal.javac.PreviewFeature.Feature.TEST, + reflective=true) + public interface ReflectivePreview { + public default void test() {} + } + """, + """ + package preview.api; + public interface NonPreviewIntf extends Preview { + } + """, + """ + package preview.api; + public class NonPreview implements Preview { + } + """, + """ + package preview.api; + public class ReflectiveNonPreview implements ReflectivePreview { + } + """); + Path apiClasses = base.resolve("api-classes"); + + new JavacTask(tb, Task.Mode.CMDLINE) + .outdir(apiClasses) + .options("--patch-module", "java.base=" + apiSrc.toString(), + "-Werror") + .files(tb.findJavaFiles(apiSrc)) + .run() + .writeAll() + .getOutputLines(Task.OutputKind.DIRECT); + + Path testSrc = base.resolve("test-src"); + tb.writeJavaFiles(testSrc, + """ + package test; + import preview.api.NonPreview; + import preview.api.NonPreviewIntf; + import preview.api.Preview; + import preview.api.ReflectiveNonPreview; + public class Test { + public void test(NonPreview np, + Produce prod) { + np.test(); + acceptRunnable(np::test); + accept(NonPreview::test); + prod.produce().test(); + acceptRunnable(prod.produce()::test); + int i = np.FIELD; + } + public void test(T1 t1, T2 t2, T3 t3) { + t1.test(); + t2.test(); + t3.test(); + } + public void test(ReflectiveNonPreview np) { + np.test(); + } + public void test(Preview p) { + p.test(); + acceptRunnable(p::test); + accept(Preview::test); + } + private static class ExtendsNonPreview extends NonPreview { + public void test() {} //error/warning here: + } + private static class ImplementsPreview implements Preview { + //no error/warning (already was on Preview after implements) + public void test() {} + } + private static class ImplicitReceiver extends NonPreview { + public void g() { + test(); //implicit this - error/warning + int i = FIELD; //implicit this - error/warning + } + } + private void acceptRunnable(Runnable r) {} + private void accept(Accept accept) {} + interface Accept { + public void accept(T t); + } + interface Produce { + public T produce(); + } + } + """); + Path testClasses = base.resolve("test-classes"); + List log = new JavacTask(tb, Task.Mode.CMDLINE) + .outdir(testClasses) + .options("--patch-module", "java.base=" + apiClasses.toString(), + "--add-exports", "java.base/preview.api=ALL-UNNAMED", + "-XDrawDiagnostics") + .files(tb.findJavaFiles(testSrc)) + .run(Task.Expect.FAIL) + .writeAll() + .getOutputLines(Task.OutputKind.DIRECT); + + List expected = + List.of("Test.java:4:19: compiler.err.is.preview: preview.api.Preview", + "Test.java:26:22: compiler.err.is.preview: preview.api.Preview", + "Test.java:34:55: compiler.err.is.preview: preview.api.Preview", + "Test.java:9:11: compiler.err.is.preview: test()", + "Test.java:10:24: compiler.err.is.preview: test()", + "Test.java:11:16: compiler.err.is.preview: test()", + "Test.java:12:23: compiler.err.is.preview: test()", + "Test.java:13:24: compiler.err.is.preview: test()", + "Test.java:14:19: compiler.err.is.preview: FIELD", + "Test.java:19:11: compiler.err.is.preview: test()", + "Test.java:20:11: compiler.err.is.preview: test()", + "Test.java:21:11: compiler.err.is.preview: test()", + "Test.java:24:11: compiler.warn.is.preview.reflective: test()", + "Test.java:29:16: compiler.err.is.preview: preview.api.Preview", + "Test.java:32:21: compiler.err.is.preview: test()", + "Test.java:36:21: compiler.err.is.preview: test()", + "Test.java:40:13: compiler.err.is.preview: test()", + "Test.java:41:21: compiler.err.is.preview: FIELD", + "17 errors", + "1 warning"); + + if (!log.equals(expected)) + throw new Exception("expected output not found" + log); + } + + @Test //JDK-8343540: + public void nonPreviewImplementsPreview2(Path base) throws Exception { + Path apiSrc = base.resolve("api-src"); + tb.writeJavaFiles(apiSrc, + """ + package preview.api; + @jdk.internal.javac.PreviewFeature(feature=jdk.internal.javac.PreviewFeature.Feature.TEST) + public interface Preview { + public default void test() {} + } + """, + """ + package preview.api; + public interface NonPreviewIntf extends Preview { + public default void test() {} + } + """, + """ + package preview.api; + public class NonPreview implements Preview { + public void test() {} + } + """); + Path apiClasses = base.resolve("api-classes"); + + new JavacTask(tb, Task.Mode.CMDLINE) + .outdir(apiClasses) + .options("--patch-module", "java.base=" + apiSrc.toString(), + "-Werror") + .files(tb.findJavaFiles(apiSrc)) + .run() + .writeAll() + .getOutputLines(Task.OutputKind.DIRECT); + + Path testSrc = base.resolve("test-src"); + tb.writeJavaFiles(testSrc, + """ + package test; + import preview.api.NonPreview; + import preview.api.NonPreviewIntf; + public class Test { + public void test(NonPreview np1, + NonPreviewIntf np2) { + np1.test(); + np2.test(); + } + } + """); + Path testClasses = base.resolve("test-classes"); + List log = new JavacTask(tb, Task.Mode.CMDLINE) + .outdir(testClasses) + .options("--patch-module", "java.base=" + apiClasses.toString(), + "--add-exports", "java.base/preview.api=ALL-UNNAMED", + "-XDrawDiagnostics") + .files(tb.findJavaFiles(testSrc)) + .run(Task.Expect.SUCCESS) + .writeAll() + .getOutputLines(Task.OutputKind.DIRECT); + } + + @Test //JDK-8343540: + public void nonPreviewImplementsPreview3(Path base) throws Exception { + Path apiSrc = base.resolve("api-src"); + tb.writeJavaFiles(apiSrc, + """ + package preview.api; + @jdk.internal.javac.PreviewFeature(feature=jdk.internal.javac.PreviewFeature.Feature.TEST) + public class Preview { + public int field; + public static void test() {} + } + """, + """ + package preview.api; + public class NonPreview extends Preview { + } + """); + Path apiClasses = base.resolve("api-classes"); + + new JavacTask(tb, Task.Mode.CMDLINE) + .outdir(apiClasses) + .options("--patch-module", "java.base=" + apiSrc.toString(), + "-Werror") + .files(tb.findJavaFiles(apiSrc)) + .run() + .writeAll() + .getOutputLines(Task.OutputKind.DIRECT); + + Path testSrc = base.resolve("test-src"); + tb.writeJavaFiles(testSrc, + """ + package test; + import preview.api.NonPreview; + import preview.api.Preview; + public class Test { + public void test(NonPreview np, Preview p) { + NonPreview.test(); + Preview.test(); + int i1 = np.field; + int i2 = p.field; + } + } + """); + Path testClasses = base.resolve("test-classes"); + List log = new JavacTask(tb, Task.Mode.CMDLINE) + .outdir(testClasses) + .options("--patch-module", "java.base=" + apiClasses.toString(), + "--add-exports", "java.base/preview.api=ALL-UNNAMED", + "-XDrawDiagnostics") + .files(tb.findJavaFiles(testSrc)) + .run(Task.Expect.FAIL) + .writeAll() + .getOutputLines(Task.OutputKind.DIRECT); + + List expected = + List.of("Test.java:3:19: compiler.err.is.preview: preview.api.Preview", + "Test.java:5:37: compiler.err.is.preview: preview.api.Preview", + "Test.java:6:19: compiler.err.is.preview: test()", + "Test.java:7:9: compiler.err.is.preview: preview.api.Preview", + "Test.java:8:20: compiler.err.is.preview: field", + "5 errors"); + + if (!log.equals(expected)) + throw new Exception("expected output not found" + log); + } + + @Test //JDK-8343540: + public void nonPreviewImplementsPreview4(Path base) throws Exception { + Path apiSrc = base.resolve("api-src"); + tb.writeJavaFiles(apiSrc, + """ + package preview.api; + @jdk.internal.javac.PreviewFeature(feature=jdk.internal.javac.PreviewFeature.Feature.TEST) + public class Preview { + public int field; + public static void test() {} + } + """, + """ + package preview.api; + public class NonPreview extends Preview { + public int field; + public static void test() {} + } + """); + Path apiClasses = base.resolve("api-classes"); + + new JavacTask(tb, Task.Mode.CMDLINE) + .outdir(apiClasses) + .options("--patch-module", "java.base=" + apiSrc.toString(), + "-Werror") + .files(tb.findJavaFiles(apiSrc)) + .run() + .writeAll() + .getOutputLines(Task.OutputKind.DIRECT); + + Path testSrc = base.resolve("test-src"); + tb.writeJavaFiles(testSrc, + """ + package test; + import preview.api.NonPreview; + import preview.api.Preview; + public class Test { + public void test(NonPreview np, Preview p) { + NonPreview.test(); + Preview.test(); + int i1 = np.field; + int i2 = p.field; + } + } + """); + Path testClasses = base.resolve("test-classes"); + List log = new JavacTask(tb, Task.Mode.CMDLINE) + .outdir(testClasses) + .options("--patch-module", "java.base=" + apiClasses.toString(), + "--add-exports", "java.base/preview.api=ALL-UNNAMED", + "-XDrawDiagnostics") + .files(tb.findJavaFiles(testSrc)) + .run(Task.Expect.FAIL) + .writeAll() + .getOutputLines(Task.OutputKind.DIRECT); + + List expected = + List.of("Test.java:3:19: compiler.err.is.preview: preview.api.Preview", + "Test.java:5:37: compiler.err.is.preview: preview.api.Preview", + "Test.java:7:9: compiler.err.is.preview: preview.api.Preview", + "3 errors"); + + if (!log.equals(expected)) + throw new Exception("expected output not found" + log); + } + + @Test //JDK-8343540: + public void nonPreviewImplementsPreview5(Path base) throws Exception { + Path apiSrc = base.resolve("api-src"); + tb.writeJavaFiles(apiSrc, + """ + package preview.api; + @jdk.internal.javac.PreviewFeature(feature=jdk.internal.javac.PreviewFeature.Feature.TEST) + public interface Preview { + public static final int CONST1 = 0; + public static final int CONST2 = 0; + } + """, + """ + package preview.api; + public interface NonPreviewIntf extends Preview { + public static final int CONST2 = 0; + } + """, + """ + package preview.api; + public class NonPreview implements Preview { + public static final int CONST2 = 0; + } + """); + Path apiClasses = base.resolve("api-classes"); + + new JavacTask(tb, Task.Mode.CMDLINE) + .outdir(apiClasses) + .options("--patch-module", "java.base=" + apiSrc.toString(), + "-Werror") + .files(tb.findJavaFiles(apiSrc)) + .run() + .writeAll() + .getOutputLines(Task.OutputKind.DIRECT); + + Path testSrc = base.resolve("test-src"); + tb.writeJavaFiles(testSrc, + """ + package test; + import preview.api.NonPreview; + import preview.api.NonPreviewIntf; + import preview.api.Preview; + public class Test { + public void test() { + int i1 = NonPreview.CONST1; + int i2 = NonPreviewIntf.CONST1; + int i3 = Preview.CONST1; + int i4 = NonPreview.CONST2; + int i5 = NonPreviewIntf.CONST2; + int i6 = Preview.CONST2; + } + } + """); + Path testClasses = base.resolve("test-classes"); + List log = new JavacTask(tb, Task.Mode.CMDLINE) + .outdir(testClasses) + .options("--patch-module", "java.base=" + apiClasses.toString(), + "--add-exports", "java.base/preview.api=ALL-UNNAMED", + "-XDrawDiagnostics") + .files(tb.findJavaFiles(testSrc)) + .run(Task.Expect.FAIL) + .writeAll() + .getOutputLines(Task.OutputKind.DIRECT); + + List expected = + List.of("Test.java:4:19: compiler.err.is.preview: preview.api.Preview", + "Test.java:7:28: compiler.err.is.preview: CONST1", + "Test.java:8:32: compiler.err.is.preview: CONST1", + "Test.java:9:18: compiler.err.is.preview: preview.api.Preview", + "Test.java:12:18: compiler.err.is.preview: preview.api.Preview", + "5 errors"); + + if (!log.equals(expected)) + throw new Exception("expected output not found" + log); + } + private int verifyPreviewClassfiles(Path directory) throws Exception { Path[] classfiles = tb.findFiles("class", directory); From 0c7451ae5abb90e59293cdcb5f2318e3bc5193a2 Mon Sep 17 00:00:00 2001 From: Aleksei Efimov Date: Wed, 4 Dec 2024 11:34:41 +0000 Subject: [PATCH 06/43] 8332686: InetAddress.ofLiteral can throw StringIndexOutOfBoundsException Reviewed-by: dfuchs, jpai --- .../share/classes/java/net/Inet6Address.java | 6 +++++- .../share/classes/java/net/InetAddress.java | 3 +++ test/jdk/java/net/InetAddress/OfLiteralTest.java | 15 +++++++++++++-- 3 files changed, 21 insertions(+), 3 deletions(-) diff --git a/src/java.base/share/classes/java/net/Inet6Address.java b/src/java.base/share/classes/java/net/Inet6Address.java index ca73a6e1cc1..06a74ca3adc 100644 --- a/src/java.base/share/classes/java/net/Inet6Address.java +++ b/src/java.base/share/classes/java/net/Inet6Address.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 @@ -554,6 +554,10 @@ public static InetAddress ofLiteral(String ipv6AddressLiteral) { */ static InetAddress parseAddressString(String addressLiteral, boolean removeSqBrackets) throws UnknownHostException { + // Empty strings are not parseable + if (addressLiteral.isEmpty()) { + return null; + } // Remove trailing and leading square brackets if requested if (removeSqBrackets && addressLiteral.charAt(0) == '[' && addressLiteral.length() > 2 && diff --git a/src/java.base/share/classes/java/net/InetAddress.java b/src/java.base/share/classes/java/net/InetAddress.java index e94df5a9e0a..4bceebdcd0e 100644 --- a/src/java.base/share/classes/java/net/InetAddress.java +++ b/src/java.base/share/classes/java/net/InetAddress.java @@ -1618,6 +1618,9 @@ static InetAddress[] getAllByName0(String host) throws UnknownHostException { */ public static InetAddress ofLiteral(String ipAddressLiteral) { Objects.requireNonNull(ipAddressLiteral); + if (ipAddressLiteral.isEmpty()) { + throw IPAddressUtil.invalidIpAddressLiteral(ipAddressLiteral); + } InetAddress inetAddress; try { // First try to parse the input as an IPv4 address literal diff --git a/test/jdk/java/net/InetAddress/OfLiteralTest.java b/test/jdk/java/net/InetAddress/OfLiteralTest.java index 090523a9ee9..f9f6cdb500f 100644 --- a/test/jdk/java/net/InetAddress/OfLiteralTest.java +++ b/test/jdk/java/net/InetAddress/OfLiteralTest.java @@ -22,7 +22,7 @@ */ /* @test - * @bug 8272215 8315767 + * @bug 8272215 8315767 8332686 * @summary Test for ofLiteral, ofPosixLiteral APIs in InetAddress classes * @run junit/othervm -Djdk.net.hosts.file=nonExistingHostsFile.txt * OfLiteralTest @@ -373,7 +373,18 @@ private static Stream invalidLiteralArguments() { Arguments.of(InetAddressClass.INET4_ADDRESS_POSIX, ""), // empty Arguments.of(InetAddressClass.INET4_ADDRESS_POSIX, "0x1FFFFFFFF"), // 2^33 - 1 is too large Arguments.of(InetAddressClass.INET4_ADDRESS_POSIX, "0x100000000"), // 2^32 is too large - Arguments.of(InetAddressClass.INET4_ADDRESS_POSIX, "040000000000") + Arguments.of(InetAddressClass.INET4_ADDRESS_POSIX, "040000000000"), + + // Empty literals + Arguments.of(InetAddressClass.INET_ADDRESS, ""), + Arguments.of(InetAddressClass.INET4_ADDRESS, ""), + Arguments.of(InetAddressClass.INET6_ADDRESS, ""), + + // Blank literals + Arguments.of(InetAddressClass.INET_ADDRESS, " "), + Arguments.of(InetAddressClass.INET4_ADDRESS, " "), + Arguments.of(InetAddressClass.INET6_ADDRESS, " "), + Arguments.of(InetAddressClass.INET4_ADDRESS_POSIX, " ") ); // Construct arguments for a test case with IPv6-scoped address with scope-id // specified as a string with non-existing network interface name From 4000e923e8b4472fe022f1fd78a1c42b2045683f Mon Sep 17 00:00:00 2001 From: Aleksey Shipilev Date: Wed, 4 Dec 2024 11:36:23 +0000 Subject: [PATCH 07/43] 8343704: Bad GC parallelism with processing Cleaner queues Reviewed-by: bchristi, vklang, ogillespie, kdnilsen --- .../classes/jdk/internal/ref/CleanerImpl.java | 149 ++++++++++++++++-- .../jdk/internal/ref/PhantomCleanable.java | 79 +++------- .../ref/Cleaner/CleanableListTest.java | 136 ++++++++++++++++ .../internal/ref/CleanableListTestHelper.java | 66 ++++++++ .../jdk/internal/ref/TestCleanable.java | 39 +++++ .../bench/java/lang/ref/CleanerChurn.java | 58 +++++++ .../bench/java/lang/ref/CleanerGC.java | 68 ++++++++ 7 files changed, 525 insertions(+), 70 deletions(-) create mode 100644 test/jdk/jdk/internal/ref/Cleaner/CleanableListTest.java create mode 100644 test/jdk/jdk/internal/ref/Cleaner/java.base/jdk/internal/ref/CleanableListTestHelper.java create mode 100644 test/jdk/jdk/internal/ref/Cleaner/java.base/jdk/internal/ref/TestCleanable.java create mode 100644 test/micro/org/openjdk/bench/java/lang/ref/CleanerChurn.java create mode 100644 test/micro/org/openjdk/bench/java/lang/ref/CleanerGC.java diff --git a/src/java.base/share/classes/jdk/internal/ref/CleanerImpl.java b/src/java.base/share/classes/jdk/internal/ref/CleanerImpl.java index b4565daa466..bb7293e5d2b 100644 --- a/src/java.base/share/classes/jdk/internal/ref/CleanerImpl.java +++ b/src/java.base/share/classes/jdk/internal/ref/CleanerImpl.java @@ -48,9 +48,9 @@ public final class CleanerImpl implements Runnable { private static Function cleanerImplAccess = null; /** - * Heads of a CleanableList for each reference type. + * Currently active PhantomCleanable-s. */ - final PhantomCleanable phantomCleanableList; + final CleanableList activeList; // The ReferenceQueue of pending cleaning actions final ReferenceQueue queue; @@ -82,7 +82,7 @@ static CleanerImpl getCleanerImpl(Cleaner cleaner) { */ public CleanerImpl() { queue = new ReferenceQueue<>(); - phantomCleanableList = new PhantomCleanableRef(); + activeList = new CleanableList(); } /** @@ -129,7 +129,7 @@ public void run() { InnocuousThread mlThread = (t instanceof InnocuousThread) ? (InnocuousThread) t : null; - while (!phantomCleanableList.isListEmpty()) { + while (!activeList.isEmpty()) { if (mlThread != null) { // Clear the thread locals mlThread.eraseThreadLocals(); @@ -165,14 +165,6 @@ public PhantomCleanableRef(Object obj, Cleaner cleaner, Runnable action) { this.action = action; } - /** - * Constructor used only for root of phantom cleanable list. - */ - PhantomCleanableRef() { - super(); - this.action = null; - } - @Override protected void performCleanup() { action.run(); @@ -231,4 +223,137 @@ protected void performCleanup() { // no action } } + + /** + * A specialized implementation that tracks phantom cleanables. + */ + static final class CleanableList { + /** + * Capacity for a single node in the list. + * This balances memory overheads vs locality vs GC walking costs. + */ + static final int NODE_CAPACITY = 4096; + + /** + * Head node. This is the only node where PhantomCleanables are + * added to or removed from. This is the only node with variable size, + * all other nodes linked from the head are always at full capacity. + */ + private Node head; + + /** + * Cached node instance to provide better behavior near NODE_CAPACITY + * threshold: if list size flips around NODE_CAPACITY, it would reuse + * the cached node instead of wasting and re-allocating a new node all + * the time. + */ + private Node cache; + + public CleanableList() { + reset(); + } + + /** + * Testing support: reset list to initial state. + */ + synchronized void reset() { + this.head = new Node(); + } + + /** + * Returns true if cleanable list is empty. + * + * @return true if the list is empty + */ + public synchronized boolean isEmpty() { + // Head node size is zero only when the entire list is empty. + return head.size == 0; + } + + /** + * Insert this PhantomCleanable in the list. + */ + public synchronized void insert(PhantomCleanable phc) { + if (head.size == NODE_CAPACITY) { + // Head node is full, insert new one. + // If possible, pick a pre-allocated node from cache. + Node newHead; + if (cache != null) { + newHead = cache; + cache = null; + } else { + newHead = new Node(); + } + newHead.next = head; + head = newHead; + } + assert head.size < NODE_CAPACITY; + + // Put the incoming object in head node and record indexes. + final int lastIndex = head.size; + phc.node = head; + phc.index = lastIndex; + head.arr[lastIndex] = phc; + head.size++; + } + + /** + * Remove this PhantomCleanable from the list. + * + * @return true if Cleanable was removed or false if not because + * it had already been removed before + */ + public synchronized boolean remove(PhantomCleanable phc) { + if (phc.node == null) { + // Not in the list. + return false; + } + assert phc.node.arr[phc.index] == phc; + + // Replace with another element from the head node, as long + // as it is not the same element. This keeps all non-head + // nodes at full capacity. + final int lastIndex = head.size - 1; + assert lastIndex >= 0; + if (head != phc.node || (phc.index != lastIndex)) { + PhantomCleanable mover = head.arr[lastIndex]; + mover.node = phc.node; + mover.index = phc.index; + phc.node.arr[phc.index] = mover; + } + + // Now we can unlink the removed element. + phc.node = null; + + // Remove the last element from the head node. + head.arr[lastIndex] = null; + head.size--; + + // If head node becomes empty after this, and there are + // nodes that follow it, replace the head node with another + // full one. If needed, stash the now free node in cache. + if (head.size == 0 && head.next != null) { + Node newHead = head.next; + if (cache == null) { + cache = head; + cache.next = null; + } + head = newHead; + } + + return true; + } + + /** + * Segment node. + */ + static class Node { + // Array of tracked cleanables, and the amount of elements in it. + final PhantomCleanable[] arr = new PhantomCleanable[NODE_CAPACITY]; + int size; + + // Linked list structure. + Node next; + } + } } diff --git a/src/java.base/share/classes/jdk/internal/ref/PhantomCleanable.java b/src/java.base/share/classes/jdk/internal/ref/PhantomCleanable.java index 24db6d8ef9a..3564a16d0a0 100644 --- a/src/java.base/share/classes/jdk/internal/ref/PhantomCleanable.java +++ b/src/java.base/share/classes/jdk/internal/ref/PhantomCleanable.java @@ -44,14 +44,21 @@ public abstract class PhantomCleanable extends PhantomReference implements Cleaner.Cleanable { /** - * Links to previous and next in a doubly-linked list. + * The list of PhantomCleanable; synchronizes insert and remove. */ - PhantomCleanable prev = this, next = this; + private final CleanerImpl.CleanableList list; /** - * The list of PhantomCleanable; synchronizes insert and remove. + * Node for this PhantomCleanable in the list. + * Synchronized by the same lock as the list itself. */ - private final PhantomCleanable list; + CleanerImpl.CleanableList.Node node; + + /** + * Index of this PhantomCleanable in the list node. + * Synchronized by the same lock as the list itself. + */ + int index; /** * Constructs new {@code PhantomCleanable} with @@ -62,73 +69,29 @@ public abstract class PhantomCleanable extends PhantomReference * @param referent the referent to track * @param cleaner the {@code Cleaner} to register with */ + @SuppressWarnings("this-escape") public PhantomCleanable(T referent, Cleaner cleaner) { super(Objects.requireNonNull(referent), CleanerImpl.getCleanerImpl(cleaner).queue); - this.list = CleanerImpl.getCleanerImpl(cleaner).phantomCleanableList; - insert(); + index = -1; + list = CleanerImpl.getCleanerImpl(cleaner).activeList; + list.insert(this); + + // Check that list insertion populated the backlinks. + assert node != null; + assert index >= 0; // Ensure referent and cleaner remain accessible Reference.reachabilityFence(referent); Reference.reachabilityFence(cleaner); } - /** - * Construct a new root of the list; not inserted. - */ - PhantomCleanable() { - super(null, null); - this.list = this; - } - - /** - * Insert this PhantomCleanable after the list head. - */ - private void insert() { - synchronized (list) { - prev = list; - next = list.next; - next.prev = this; - list.next = this; - } - } - - /** - * Remove this PhantomCleanable from the list. - * - * @return true if Cleanable was removed or false if not because - * it had already been removed before - */ - private boolean remove() { - synchronized (list) { - if (next != this) { - next.prev = prev; - prev.next = next; - prev = this; - next = this; - return true; - } - return false; - } - } - - /** - * Returns true if the list's next reference refers to itself. - * - * @return true if the list is empty - */ - boolean isListEmpty() { - synchronized (list) { - return list == list.next; - } - } - /** * Unregister this PhantomCleanable and invoke {@link #performCleanup()}, * ensuring at-most-once semantics. */ @Override public final void clean() { - if (remove()) { + if (list.remove(this)) { super.clear(); performCleanup(); } @@ -140,7 +103,7 @@ public final void clean() { */ @Override public void clear() { - if (remove()) { + if (list.remove(this)) { super.clear(); } } diff --git a/test/jdk/jdk/internal/ref/Cleaner/CleanableListTest.java b/test/jdk/jdk/internal/ref/Cleaner/CleanableListTest.java new file mode 100644 index 00000000000..eedd21d3f53 --- /dev/null +++ b/test/jdk/jdk/internal/ref/Cleaner/CleanableListTest.java @@ -0,0 +1,136 @@ +/* + * Copyright Amazon.com Inc. 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 8343704 + * @key randomness + * @library /test/lib + * @compile/module=java.base jdk/internal/ref/CleanableListTestHelper.java jdk/internal/ref/TestCleanable.java + * @modules java.base/jdk.internal.ref + * @run testng/othervm CleanableListTest + */ + +import java.util.ArrayList; +import java.util.BitSet; +import java.util.List; +import java.util.Random; + +import jdk.internal.ref.CleanableListTestHelper; +import jdk.internal.ref.TestCleanable; +import jdk.test.lib.RandomFactory; + +import org.testng.Assert; +import org.testng.annotations.Test; +import org.testng.annotations.Ignore; + +public class CleanableListTest { + + static final int SINGLE_NODE_CAPACITY = CleanableListTestHelper.NODE_CAPACITY; + static final int MULTI_NODE_CAPACITY = CleanableListTestHelper.NODE_CAPACITY * 4; + + static final Random RND = RandomFactory.getRandom(); + static final int RANDOM_ITERATIONS = 10_000_000; + + @Test + public void testSingle() { + CleanableListTestHelper list = new CleanableListTestHelper(); + Assert.assertTrue(list.isEmpty()); + TestCleanable tc = list.newCleanable(); + Assert.assertFalse(list.isEmpty()); + Assert.assertTrue(list.remove(tc)); + Assert.assertTrue(list.isEmpty()); + Assert.assertFalse(list.remove(tc)); + } + + @Test + public void testSequential_Single() { + doSequential(SINGLE_NODE_CAPACITY); + } + + @Test + public void testSequential_Multi() { + doSequential(MULTI_NODE_CAPACITY); + } + + private void doSequential(int size) { + CleanableListTestHelper list = new CleanableListTestHelper(); + Assert.assertTrue(list.isEmpty()); + + List tcs = new ArrayList<>(); + for (int c = 0; c < size; c++) { + tcs.add(list.newCleanable()); + } + Assert.assertFalse(list.isEmpty()); + + for (TestCleanable tc : tcs) { + Assert.assertTrue(list.remove(tc)); + } + Assert.assertTrue(list.isEmpty()); + } + + @Test + public void testRandom_Single() { + doRandom(SINGLE_NODE_CAPACITY); + } + + @Test + public void testRandom_Multi() { + doRandom(MULTI_NODE_CAPACITY); + } + + private void doRandom(int size) { + CleanableListTestHelper list = new CleanableListTestHelper(); + Assert.assertTrue(list.isEmpty()); + + BitSet bs = new BitSet(size); + + List tcs = new ArrayList<>(); + for (int c = 0; c < size; c++) { + tcs.add(list.newCleanable()); + bs.set(c, true); + } + Assert.assertFalse(list.isEmpty()); + + for (int t = 0; t < RANDOM_ITERATIONS; t++) { + int idx = RND.nextInt(size); + TestCleanable tc = tcs.get(idx); + if (bs.get(idx)) { + Assert.assertTrue(list.remove(tc)); + bs.set(idx, false); + } else { + Assert.assertFalse(list.remove(tc)); + list.insert(tc); + bs.set(idx, true); + } + } + + for (int c = 0; c < size; c++) { + if (bs.get(c)) { + TestCleanable tc = tcs.get(c); + Assert.assertTrue(list.remove(tc)); + } + } + } + +} diff --git a/test/jdk/jdk/internal/ref/Cleaner/java.base/jdk/internal/ref/CleanableListTestHelper.java b/test/jdk/jdk/internal/ref/Cleaner/java.base/jdk/internal/ref/CleanableListTestHelper.java new file mode 100644 index 00000000000..d3ee187a097 --- /dev/null +++ b/test/jdk/jdk/internal/ref/Cleaner/java.base/jdk/internal/ref/CleanableListTestHelper.java @@ -0,0 +1,66 @@ +/* + * Copyright Amazon.com Inc. 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.internal.ref; + +import java.lang.ref.Cleaner; +import jdk.internal.ref.PhantomCleanable; +import jdk.internal.ref.CleanerImpl; +import jdk.internal.ref.CleanerImpl.CleanableList; + +/** + * This class provides package-private access to CleanableList internals. + */ +public class CleanableListTestHelper { + + public static final int NODE_CAPACITY = CleanableList.NODE_CAPACITY; + + final Cleaner cleaner; + final CleanableList list; + + public CleanableListTestHelper() { + cleaner = Cleaner.create(); + list = CleanerImpl.getCleanerImpl(cleaner).activeList; + + // List contains CleanerCleanable for Cleaner itself. + // For testing empty list paths, we want to drop it. + list.reset(); + } + + public TestCleanable newCleanable() { + return new TestCleanable(cleaner); + } + + public void insert(PhantomCleanable cl) { + list.insert(cl); + } + + public boolean remove(PhantomCleanable cl) { + return list.remove(cl); + } + + public boolean isEmpty() { + return list.isEmpty(); + } + +} diff --git a/test/jdk/jdk/internal/ref/Cleaner/java.base/jdk/internal/ref/TestCleanable.java b/test/jdk/jdk/internal/ref/Cleaner/java.base/jdk/internal/ref/TestCleanable.java new file mode 100644 index 00000000000..9e8da6f4830 --- /dev/null +++ b/test/jdk/jdk/internal/ref/Cleaner/java.base/jdk/internal/ref/TestCleanable.java @@ -0,0 +1,39 @@ +/* + * Copyright Amazon.com Inc. 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.internal.ref; + +import java.lang.ref.Cleaner; + +public class TestCleanable extends PhantomCleanable { + static final Object TARGET = new Object(); + + public TestCleanable(Cleaner cleaner) { + super(TARGET, cleaner); + } + + @Override + protected void performCleanup() { + // no action + } +} diff --git a/test/micro/org/openjdk/bench/java/lang/ref/CleanerChurn.java b/test/micro/org/openjdk/bench/java/lang/ref/CleanerChurn.java new file mode 100644 index 00000000000..eab4c0f59d0 --- /dev/null +++ b/test/micro/org/openjdk/bench/java/lang/ref/CleanerChurn.java @@ -0,0 +1,58 @@ +/* + * Copyright Amazon.com Inc. 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.java.lang.ref; + +import java.lang.ref.Cleaner; +import java.lang.ref.Cleaner.Cleanable; +import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.TimeUnit; +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.infra.Blackhole; + +@OutputTimeUnit(TimeUnit.NANOSECONDS) +@State(Scope.Thread) +@BenchmarkMode(Mode.AverageTime) +@Warmup(iterations = 3, time = 1, timeUnit = TimeUnit.SECONDS) +@Measurement(iterations = 3, time = 1, timeUnit = TimeUnit.SECONDS) +@Fork(value = 3, jvmArgs = {"-Xmx256m", "-Xms256m", "-XX:+AlwaysPreTouch"}) +public class CleanerChurn { + + @Param({"128", "256", "512", "1024", "2048"}) + int recipFreq; + + @Benchmark + public Object test() { + boolean register = ThreadLocalRandom.current().nextInt(recipFreq) == 0; + return new Target(register); + } + + static class Target { + private static final Cleaner CLEANER = Cleaner.create(); + public Target(boolean register) { + if (register) { + CLEANER.register(this, () -> {}); + } + } + } + +} diff --git a/test/micro/org/openjdk/bench/java/lang/ref/CleanerGC.java b/test/micro/org/openjdk/bench/java/lang/ref/CleanerGC.java new file mode 100644 index 00000000000..8d43f25c6c6 --- /dev/null +++ b/test/micro/org/openjdk/bench/java/lang/ref/CleanerGC.java @@ -0,0 +1,68 @@ +/* + * Copyright Amazon.com Inc. 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.java.lang.ref; + +import java.lang.ref.Cleaner; +import java.lang.ref.Cleaner.Cleanable; +import java.util.ArrayList; +import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.TimeUnit; +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.infra.Blackhole; + +@OutputTimeUnit(TimeUnit.MILLISECONDS) +@State(Scope.Thread) +@BenchmarkMode(Mode.AverageTime) +@Warmup(iterations = 3, time = 1, timeUnit = TimeUnit.SECONDS) +@Measurement(iterations = 3, time = 1, timeUnit = TimeUnit.SECONDS) +@Fork(value = 3, jvmArgs = {"-Xmx1g", "-Xms1g", "-XX:+AlwaysPreTouch"}) +public class CleanerGC { + + @Param({"16384", "65536", "262144", "1048576", "4194304"}) + int count; + + // Make sure all targets are reachable and available for GC in scalable manner. + // This exposes the potential GC problem in Cleaner lists. + ArrayList targets; + + @Setup + public void setup() { + targets = new ArrayList<>(); + for (int c = 0; c < count; c++) { + targets.add(new Target()); + } + } + + @Benchmark + public void test() { + System.gc(); + } + + static class Target { + private static final Cleaner CLEANER = Cleaner.create(); + public Target() { + CLEANER.register(this, () -> {}); + } + } + +} From e13206d3a16a67a604076faecded88cbed85db1a Mon Sep 17 00:00:00 2001 From: Sean Mullan Date: Wed, 4 Dec 2024 12:44:23 +0000 Subject: [PATCH 08/43] 8345065: Cleanup DomainCombiner, SubjectDomainCombiner, Subject, and PrivilegedAction specifications Reviewed-by: weijun --- .../share/classes/java/security/DomainCombiner.java | 5 +---- .../classes/java/security/PrivilegedAction.java | 8 ++++---- .../java/security/PrivilegedActionException.java | 8 ++++---- .../java/security/PrivilegedExceptionAction.java | 8 ++++---- .../share/classes/javax/security/auth/Subject.java | 4 ++-- .../javax/security/auth/SubjectDomainCombiner.java | 13 ++++--------- 6 files changed, 19 insertions(+), 27 deletions(-) diff --git a/src/java.base/share/classes/java/security/DomainCombiner.java b/src/java.base/share/classes/java/security/DomainCombiner.java index 704c6315bb1..1594a48783f 100644 --- a/src/java.base/share/classes/java/security/DomainCombiner.java +++ b/src/java.base/share/classes/java/security/DomainCombiner.java @@ -46,8 +46,7 @@ public interface DomainCombiner { * set of Permissions, for example). * * @param currentDomains the ProtectionDomains associated with the - * current execution thread, up to the most recent - * privileged {@code ProtectionDomain}. + * current execution thread. * The ProtectionDomains are listed in order of execution, * with the most recently executing {@code ProtectionDomain} * residing at the beginning of the array. This parameter may @@ -55,8 +54,6 @@ public interface DomainCombiner { * has no associated ProtectionDomains. * * @param assignedDomains an array of inherited ProtectionDomains. - * ProtectionDomains may be inherited from a parent thread, - * or from a privileged {@code AccessControlContext}. * This parameter may be {@code null} * if there are no inherited ProtectionDomains. * diff --git a/src/java.base/share/classes/java/security/PrivilegedAction.java b/src/java.base/share/classes/java/security/PrivilegedAction.java index 39db3492c01..56f7878bc6a 100644 --- a/src/java.base/share/classes/java/security/PrivilegedAction.java +++ b/src/java.base/share/classes/java/security/PrivilegedAction.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 @@ -27,8 +27,8 @@ /** - * A computation to be performed with privileges enabled. The computation is - * performed by invoking {@code AccessController.doPrivileged} on the + * A computation to be performed by invoking + * {@code AccessController.doPrivileged} on the * {@code PrivilegedAction} object. This interface is used only for * computations that do not throw checked exceptions; computations that * throw checked exceptions must use {@code PrivilegedExceptionAction} @@ -44,7 +44,7 @@ public interface PrivilegedAction { /** * Performs the computation. This method will be called by - * {@code AccessController.doPrivileged} after enabling privileges. + * {@code AccessController.doPrivileged}. * * @return a class-dependent value that may represent the results of the * computation. Each class that implements diff --git a/src/java.base/share/classes/java/security/PrivilegedActionException.java b/src/java.base/share/classes/java/security/PrivilegedActionException.java index 9c52d8739b8..1c1418f4267 100644 --- a/src/java.base/share/classes/java/security/PrivilegedActionException.java +++ b/src/java.base/share/classes/java/security/PrivilegedActionException.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 @@ -63,7 +63,7 @@ public PrivilegedActionException(Exception exception) { } /** - * Returns the exception thrown by the privileged computation that + * Returns the exception thrown by the computation that * resulted in this {@code PrivilegedActionException}. * * @apiNote @@ -71,7 +71,7 @@ public PrivilegedActionException(Exception exception) { * The {@link Throwable#getCause()} method is now the preferred means of * obtaining this information. * - * @return the exception thrown by the privileged computation that + * @return the exception thrown by the computation that * resulted in this {@code PrivilegedActionException}. * @see PrivilegedExceptionAction * @see AccessController#doPrivileged(PrivilegedExceptionAction) @@ -90,7 +90,7 @@ public String toString() { /** - * The exception thrown by the privileged computation that resulted + * The exception thrown by the computation that resulted * in this {@code PrivilegedActionException}. * * @serialField exception Exception the thrown Exception diff --git a/src/java.base/share/classes/java/security/PrivilegedExceptionAction.java b/src/java.base/share/classes/java/security/PrivilegedExceptionAction.java index 00863ddf4a1..d875a2a4159 100644 --- a/src/java.base/share/classes/java/security/PrivilegedExceptionAction.java +++ b/src/java.base/share/classes/java/security/PrivilegedExceptionAction.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 @@ -27,8 +27,8 @@ /** - * A computation to be performed with privileges enabled, that throws one or - * more checked exceptions. The computation is performed by invoking + * A computation to be performed that throws one or more checked exceptions. + * The computation is performed by invoking * {@code AccessController.doPrivileged} on the * {@code PrivilegedExceptionAction} object. This interface is * used only for computations that throw checked exceptions; @@ -47,7 +47,7 @@ public interface PrivilegedExceptionAction { /** * Performs the computation. This method will be called by - * {@code AccessController.doPrivileged} after enabling privileges. + * {@code AccessController.doPrivileged}. * * @return a class-dependent value that may represent the results of the * computation. Each class that implements diff --git a/src/java.base/share/classes/javax/security/auth/Subject.java b/src/java.base/share/classes/javax/security/auth/Subject.java index 97ab672e1cc..ceb860e653a 100644 --- a/src/java.base/share/classes/javax/security/auth/Subject.java +++ b/src/java.base/share/classes/javax/security/auth/Subject.java @@ -453,7 +453,7 @@ public static T doAs(final Subject subject, } /** - * Perform privileged work as a particular {@code Subject}. + * Perform work as a particular {@code Subject}. * *

This method launches {@code action} and binds {@code subject} to * the period of its execution. @@ -513,7 +513,7 @@ public static T doAsPrivileged(final Subject subject, } /** - * Perform privileged work as a particular {@code Subject}. + * Perform work as a particular {@code Subject}. * *

This method launches {@code action} and binds {@code subject} to * the period of its execution. diff --git a/src/java.base/share/classes/javax/security/auth/SubjectDomainCombiner.java b/src/java.base/share/classes/javax/security/auth/SubjectDomainCombiner.java index bab2c5b9da9..643aea9e93c 100644 --- a/src/java.base/share/classes/javax/security/auth/SubjectDomainCombiner.java +++ b/src/java.base/share/classes/javax/security/auth/SubjectDomainCombiner.java @@ -112,21 +112,16 @@ public Subject getSubject() { * In addition, caching of ProtectionDomains may be permitted. * * @param currentDomains the ProtectionDomains associated with the - * current execution Thread, up to the most recent - * privileged {@code ProtectionDomain}. + * current execution Thread. * The ProtectionDomains are listed in order of execution, * with the most recently executing {@code ProtectionDomain} * residing at the beginning of the array. This parameter may * be {@code null} if the current execution Thread * has no associated ProtectionDomains. * - * @param assignedDomains the ProtectionDomains inherited from the - * parent Thread, or the ProtectionDomains from the - * privileged {@code context}, if a call to - * {@code AccessController.doPrivileged(..., context)} - * had occurred This parameter may be {@code null} - * if there were no ProtectionDomains inherited from the - * parent Thread, or from the privileged {@code context}. + * @param assignedDomains the inherited ProtectionDomains. + * This parameter may be {@code null} + * if there were no inherited ProtectionDomains. * * @return a new array consisting of the updated ProtectionDomains, * or {@code null}. From 6fa5cea984c31fbb74b39e1eec68daffea22ca92 Mon Sep 17 00:00:00 2001 From: Alexey Ivanov Date: Wed, 4 Dec 2024 13:29:53 +0000 Subject: [PATCH 09/43] 8341982: Simplify JButton/bug4323121.java Reviewed-by: abhiscxk, honkar, dnguyen, achung --- test/jdk/javax/swing/JButton/bug4323121.java | 106 ++++++++----------- 1 file changed, 45 insertions(+), 61 deletions(-) diff --git a/test/jdk/javax/swing/JButton/bug4323121.java b/test/jdk/javax/swing/JButton/bug4323121.java index 0b352ce57eb..f23cfe43f6a 100644 --- a/test/jdk/javax/swing/JButton/bug4323121.java +++ b/test/jdk/javax/swing/JButton/bug4323121.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 @@ -24,59 +24,81 @@ /* * @test * @bug 4323121 - * @summary Tests whether any button that extends JButton always - returns true for isArmed() + * @summary Tests whether a button model always returns true for isArmed() + * when mouse hovers over the button * @key headful * @run main bug4323121 */ -import java.awt.Graphics; import java.awt.Point; import java.awt.Robot; +import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.awt.event.MouseMotionListener; +import java.util.concurrent.CountDownLatch; + import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.SwingUtilities; -public class bug4323121 { +import static java.util.concurrent.TimeUnit.SECONDS; + +public final class bug4323121 { static JFrame frame; - static testButton button; - static volatile Point pt; - static volatile int buttonW; - static volatile int buttonH; - static volatile boolean failed = false; + static JButton button; + + static volatile Point buttonCenter; + + private static final CountDownLatch mouseEntered = new CountDownLatch(1); + + // Usage of this flag is thread-safe because of using the mouseEntered latch + private static boolean modelArmed; public static void main(String[] args) throws Exception { Robot robot = new Robot(); robot.setAutoDelay(100); + try { SwingUtilities.invokeAndWait(() -> { + button = new JButton("gotcha"); + button.addMouseListener(new MouseAdapter() { + @Override + public void mouseEntered(MouseEvent e) { + if (button.getModel().isArmed()) { + modelArmed = true; + } + mouseEntered.countDown(); + } + }); + frame = new JFrame("bug4323121"); - button = new testButton("gotcha"); frame.getContentPane().add(button); + frame.pack(); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); + robot.waitForIdle(); - robot.delay(1000); + SwingUtilities.invokeAndWait(() -> { - pt = button.getLocationOnScreen(); - buttonW = button.getSize().width; - buttonH = button.getSize().height; + Point location = button.getLocationOnScreen(); + buttonCenter = new Point(location.x + button.getWidth() / 2, + location.y + button.getHeight() / 2); }); - robot.mouseMove(pt.x + buttonW / 2, pt.y + buttonH / 2); - robot.waitForIdle(); - if (failed) { - throw new RuntimeException("Any created button returns " + - "true for isArmed()"); + + robot.mouseMove(buttonCenter.x, buttonCenter.y); + + if (!mouseEntered.await(1, SECONDS)) { + throw new RuntimeException("Mouse entered event wasn't received"); + } + if (modelArmed) { + throw new RuntimeException("getModel().isArmed() returns true " + + "when mouse hovers over the button"); } } finally { - SwingUtilities.invokeAndWait(() -> { + SwingUtilities.invokeAndWait(() -> { if (frame != null) { frame.dispose(); } @@ -84,42 +106,4 @@ public static void main(String[] args) throws Exception { } } - static class testButton extends JButton implements MouseMotionListener, MouseListener { - public testButton(String label) { - super(label); - addMouseMotionListener(this); - addMouseListener(this); - } - - protected void paintComponent(Graphics g) { - super.paintComponent(g); - } - - protected void paintBorder(Graphics g) { - } - - public void mousePressed(MouseEvent e) { - } - - public void mouseDragged(MouseEvent e) { - } - - public void mouseMoved(MouseEvent e) { - } - - public void mouseReleased(MouseEvent e) { - } - - public void mouseEntered(MouseEvent e) { - if (getModel().isArmed()) { - failed = true; - } - } - - public void mouseExited(MouseEvent e) { - } - - public void mouseClicked(MouseEvent e) { - } - } } From 39cdadfb6ac8db7c84cf3259802d1f6ab26df8bf Mon Sep 17 00:00:00 2001 From: Per Minborg Date: Wed, 4 Dec 2024 14:17:00 +0000 Subject: [PATCH 10/43] 8345186: Incorrect @throws doc for MemorySegment::getString Reviewed-by: mcimadamore, jvernee --- .../java/lang/foreign/MemorySegment.java | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/src/java.base/share/classes/java/lang/foreign/MemorySegment.java b/src/java.base/share/classes/java/lang/foreign/MemorySegment.java index cd38bd19227..024dfacb71b 100644 --- a/src/java.base/share/classes/java/lang/foreign/MemorySegment.java +++ b/src/java.base/share/classes/java/lang/foreign/MemorySegment.java @@ -1277,9 +1277,9 @@ MemorySegment reinterpret(long newSize, * @throws IllegalArgumentException if the size of the string is greater than the * largest string supported by the platform * @throws IndexOutOfBoundsException if {@code offset < 0} - * @throws IndexOutOfBoundsException if {@code offset > byteSize() - (B + 1)}, where - * {@code B} is the size, in bytes, of the string encoded using UTF-8 charset - * {@code str.getBytes(StandardCharsets.UTF_8).length}) + * @throws IndexOutOfBoundsException if no string terminator (e.g. {@code '\0'}) is + * present in this segment between the given {@code offset} and the end of + * this segment. * @throws IllegalStateException if the {@linkplain #scope() scope} associated with * this segment is not {@linkplain Scope#isAlive() alive} * @throws WrongThreadException if this method is called from a thread {@code T}, @@ -1315,14 +1315,11 @@ MemorySegment reinterpret(long newSize, * @throws IllegalArgumentException if the size of the string is greater than the * largest string supported by the platform * @throws IndexOutOfBoundsException if {@code offset < 0} - * @throws IndexOutOfBoundsException if {@code offset > byteSize() - (B + N)}, where: - *

    - *
  • {@code B} is the size, in bytes, of the string encoded using the - * provided charset (e.g. {@code str.getBytes(charset).length});
  • - *
  • {@code N} is the size (in bytes) of the terminator char according - * to the provided charset. For instance, this is 1 for - * {@link StandardCharsets#US_ASCII} and 2 for {@link StandardCharsets#UTF_16}.
  • - *
+ * @throws IndexOutOfBoundsException if no string terminator (e.g. {@code '\0'}) is + * present in this segment between the given {@code offset} and the end of + * this segment. The byte size of the string terminator depends on the + * selected {@code charset}. For instance, this is 1 for + * {@link StandardCharsets#US_ASCII} and 2 for {@link StandardCharsets#UTF_16} * @throws IllegalStateException if the {@linkplain #scope() scope} associated with * this segment is not {@linkplain Scope#isAlive() alive} * @throws WrongThreadException if this method is called from a thread {@code T}, From bd6d911cbe4b04221e52120cd0f8f04e219eca4d Mon Sep 17 00:00:00 2001 From: Kevin Walls Date: Wed, 4 Dec 2024 14:23:08 +0000 Subject: [PATCH 11/43] 8344177: Remove SecurityManager and related calls from java.management Reviewed-by: dfuchs --- .../DefaultMBeanServerInterceptor.java | 298 +----------------- .../ClassLoaderRepositorySupport.java | 19 +- .../DefaultMXBeanMappingFactory.java | 5 - .../jmx/mbeanserver/GetPropertyAction.java | 46 --- .../com/sun/jmx/mbeanserver/Introspector.java | 19 +- .../sun/jmx/mbeanserver/JmxMBeanServer.java | 102 +----- .../jmx/mbeanserver/MBeanInstantiator.java | 62 +--- .../jmx/mbeanserver/MBeanIntrospector.java | 4 +- .../com/sun/jmx/mbeanserver/MBeanSupport.java | 4 +- .../com/sun/jmx/mbeanserver/MXBeanLookup.java | 7 +- .../ObjectInputStreamWithLoader.java | 4 +- .../com/sun/jmx/mbeanserver/PerInterface.java | 13 +- .../internal/ArrayNotificationBuffer.java | 79 +---- .../remote/internal/ClientNotifForwarder.java | 47 +-- .../remote/internal/ServerNotifForwarder.java | 87 +---- .../jmx/remote/security/FileLoginModule.java | 33 +- .../security/HashedPasswordManager.java | 11 +- .../security/JMXPluggableAuthenticator.java | 40 +-- .../security/JMXSubjectDomainCombiner.java | 107 ------- .../security/MBeanServerAccessController.java | 76 ++--- .../com/sun/jmx/remote/util/EnvHelp.java | 11 +- .../jmx/remote/util/OrderClassLoaders.java | 5 +- .../lang/management/ManagementFactory.java | 76 ++--- .../java/lang/management/RuntimeMXBean.java | 6 +- .../management/ClassAttributeValueExp.java | 4 - .../share/classes/javax/management/JMX.java | 3 +- .../javax/management/MBeanAttributeInfo.java | 2 - .../classes/javax/management/MBeanInfo.java | 31 +- .../classes/javax/management/MBeanServer.java | 7 - .../javax/management/MBeanServerFactory.java | 65 +--- .../javax/management/Notification.java | 4 - .../javax/management/NumericValueExp.java | 5 - .../classes/javax/management/ObjectName.java | 2 - .../javax/management/StandardMBean.java | 18 +- .../modelmbean/DescriptorSupport.java | 5 - .../InvalidTargetObjectTypeException.java | 3 - .../modelmbean/ModelMBeanAttributeInfo.java | 2 - .../modelmbean/ModelMBeanConstructorInfo.java | 2 - .../modelmbean/ModelMBeanInfoSupport.java | 2 - .../ModelMBeanNotificationInfo.java | 2 - .../modelmbean/ModelMBeanOperationInfo.java | 2 - .../modelmbean/RequiredModelMBean.java | 160 +++------- .../modelmbean/XMLParseException.java | 3 - .../javax/management/monitor/Monitor.java | 35 +- .../OpenMBeanAttributeInfoSupport.java | 9 - .../javax/management/openmbean/OpenType.java | 25 +- .../openmbean/TabularDataSupport.java | 7 +- .../MBeanServerNotificationFilter.java | 2 - .../relation/RelationNotification.java | 3 - .../relation/RelationTypeSupport.java | 3 - .../javax/management/relation/Role.java | 3 - .../javax/management/relation/RoleInfo.java | 4 - .../javax/management/relation/RoleResult.java | 5 - .../management/relation/RoleUnresolved.java | 3 - .../remote/JMXConnectorFactory.java | 31 +- .../sun/management/ClassLoadingImpl.java | 4 +- .../management/ManagementFactoryHelper.java | 76 ++--- .../sun/management/MappedMXBeanType.java | 22 +- .../classes/sun/management/MemoryImpl.java | 4 +- .../sun/management/MemoryPoolImpl.java | 8 +- .../classes/sun/management/RuntimeImpl.java | 3 +- .../classes/sun/management/ThreadImpl.java | 13 - .../share/classes/sun/management/Util.java | 31 +- .../sun/management/VMManagementImpl.java | 2 +- 64 files changed, 213 insertions(+), 1563 deletions(-) delete mode 100644 src/java.management/share/classes/com/sun/jmx/mbeanserver/GetPropertyAction.java delete mode 100644 src/java.management/share/classes/com/sun/jmx/remote/security/JMXSubjectDomainCombiner.java diff --git a/src/java.management/share/classes/com/sun/jmx/interceptor/DefaultMBeanServerInterceptor.java b/src/java.management/share/classes/com/sun/jmx/interceptor/DefaultMBeanServerInterceptor.java index e5aa863f9a6..555dfdc918b 100644 --- a/src/java.management/share/classes/com/sun/jmx/interceptor/DefaultMBeanServerInterceptor.java +++ b/src/java.management/share/classes/com/sun/jmx/interceptor/DefaultMBeanServerInterceptor.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 @@ -39,10 +39,6 @@ import com.sun.jmx.remote.util.EnvHelp; import java.lang.ref.WeakReference; -import java.security.AccessControlContext; -import java.security.AccessController; -import java.security.Permission; -import java.security.PrivilegedAction; import java.security.ProtectionDomain; import java.util.ArrayList; import java.util.HashSet; @@ -64,13 +60,11 @@ import javax.management.ListenerNotFoundException; import javax.management.MBeanException; import javax.management.MBeanInfo; -import javax.management.MBeanPermission; import javax.management.MBeanRegistration; import javax.management.MBeanRegistrationException; import javax.management.MBeanServer; import javax.management.MBeanServerDelegate; import javax.management.MBeanServerNotification; -import javax.management.MBeanTrustPermission; import javax.management.NotCompliantMBeanException; import javax.management.Notification; import javax.management.NotificationBroadcaster; @@ -248,9 +242,6 @@ private ObjectInstance createMBean(String className, ObjectName name, name = nonDefaultDomain(name); } - checkMBeanPermission(className, null, null, "instantiate"); - checkMBeanPermission(className, null, name, "registerMBean"); - /* Load the appropriate class. */ if (withDefaultLoaderRepository) { if (MBEANSERVER_LOGGER.isLoggable(Level.TRACE)) { @@ -281,8 +272,6 @@ private ObjectInstance createMBean(String className, ObjectName name, theClass = instantiator.findClass(className, loaderName); } - checkMBeanTrustPermission(theClass); - // Check that the MBean can be instantiated by the MBeanServer. Introspector.testCreation(theClass); @@ -309,9 +298,6 @@ public ObjectInstance registerMBean(Object object, ObjectName name) final String infoClassName = getNewMBeanClassName(object); - checkMBeanPermission(infoClassName, null, name, "registerMBean"); - checkMBeanTrustPermission(theClass); - return registerObject(infoClassName, object, name); } @@ -417,8 +403,6 @@ private void exclusiveUnregisterMBean(ObjectName name) DynamicMBean instance = getMBean(name); // may throw InstanceNotFoundException - checkMBeanPermission(instance, null, name, "unregisterMBean"); - if (instance instanceof MBeanRegistration) preDeregisterInvoke((MBeanRegistration) instance); @@ -451,47 +435,13 @@ public ObjectInstance getObjectInstance(ObjectName name) name = nonDefaultDomain(name); DynamicMBean instance = getMBean(name); - checkMBeanPermission(instance, null, name, "getObjectInstance"); - final String className = getClassName(instance); return new ObjectInstance(name, className); } public Set queryMBeans(ObjectName name, QueryExp query) { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - // Check if the caller has the right to invoke 'queryMBeans' - // - checkMBeanPermission((String) null, null, null, "queryMBeans"); - - // Perform query without "query". - // - Set list = queryMBeansImpl(name, null); - - // Check if the caller has the right to invoke 'queryMBeans' - // on each specific classname/objectname in the list. - // - Set allowedList = new HashSet<>(list.size()); - for (ObjectInstance oi : list) { - try { - checkMBeanPermission(oi.getClassName(), null, - oi.getObjectName(), "queryMBeans"); - allowedList.add(oi); - } catch (SecurityException e) { - // OK: Do not add this ObjectInstance to the list - } - } - - // Apply query to allowed MBeans only. - // - return filterListOfObjectInstances(allowedList, query); - } else { - // Perform query. - // - return queryMBeansImpl(name, query); - } + return queryMBeansImpl(name, query); } private Set queryMBeansImpl(ObjectName name, @@ -504,46 +454,7 @@ private Set queryMBeansImpl(ObjectName name, } public Set queryNames(ObjectName name, QueryExp query) { - Set queryList; - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - // Check if the caller has the right to invoke 'queryNames' - // - checkMBeanPermission((String) null, null, null, "queryNames"); - - // Perform query without "query". - // - Set list = queryMBeansImpl(name, null); - - // Check if the caller has the right to invoke 'queryNames' - // on each specific classname/objectname in the list. - // - Set allowedList = new HashSet<>(list.size()); - for (ObjectInstance oi : list) { - try { - checkMBeanPermission(oi.getClassName(), null, - oi.getObjectName(), "queryNames"); - allowedList.add(oi); - } catch (SecurityException e) { - // OK: Do not add this ObjectInstance to the list - } - } - - // Apply query to allowed MBeans only. - // - Set queryObjectInstanceList = - filterListOfObjectInstances(allowedList, query); - queryList = new HashSet<>(queryObjectInstanceList.size()); - for (ObjectInstance oi : queryObjectInstanceList) { - queryList.add(oi.getObjectName()); - } - } else { - // Perform query. - // - queryList = queryNamesImpl(name, query); - } - return queryList; + return queryNamesImpl(name, query); } private Set queryNamesImpl(ObjectName name, QueryExp query) { @@ -562,45 +473,11 @@ public boolean isRegistered(ObjectName name) { } name = nonDefaultDomain(name); - - /* No Permission check */ - // isRegistered is always unchecked as per JMX spec. - return (repository.contains(name)); } public String[] getDomains() { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - // Check if the caller has the right to invoke 'getDomains' - // - checkMBeanPermission((String) null, null, null, "getDomains"); - - // Return domains - // - String[] domains = repository.getDomains(); - - // Check if the caller has the right to invoke 'getDomains' - // on each specific domain in the list. - // - List result = new ArrayList<>(domains.length); - for (int i = 0; i < domains.length; i++) { - try { - ObjectName dom = Util.newObjectName(domains[i] + ":x=x"); - checkMBeanPermission((String) null, null, dom, "getDomains"); - result.add(domains[i]); - } catch (SecurityException e) { - // OK: Do not add this domain to the list - } - } - - // Make an array from result. - // - return result.toArray(new String[result.size()]); - } else { - return repository.getDomains(); - } + return repository.getDomains(); } public Integer getMBeanCount() { @@ -630,7 +507,6 @@ public Object getAttribute(ObjectName name, String attribute) } final DynamicMBean instance = getMBean(name); - checkMBeanPermission(instance, attribute, name, "getAttribute"); try { return instance.getAttribute(attribute); @@ -664,33 +540,7 @@ public AttributeList getAttributes(ObjectName name, String[] attributes) } final DynamicMBean instance = getMBean(name); - final String[] allowedAttributes; - @SuppressWarnings("removal") - final SecurityManager sm = System.getSecurityManager(); - if (sm == null) - allowedAttributes = attributes; - else { - final String classname = getClassName(instance); - - // Check if the caller has the right to invoke 'getAttribute' - // - checkMBeanPermission(classname, null, name, "getAttribute"); - - // Check if the caller has the right to invoke 'getAttribute' - // on each specific attribute - // - List allowedList = new ArrayList<>(attributes.length); - for (String attr : attributes) { - try { - checkMBeanPermission(classname, attr, name, "getAttribute"); - allowedList.add(attr); - } catch (SecurityException e) { - // OK: Do not add this attribute to the list - } - } - allowedAttributes = - allowedList.toArray(new String[allowedList.size()]); - } + final String[] allowedAttributes = attributes; try { return instance.getAttributes(allowedAttributes); @@ -725,7 +575,6 @@ public void setAttribute(ObjectName name, Attribute attribute) } DynamicMBean instance = getMBean(name); - checkMBeanPermission(instance, attribute.getName(), name, "setAttribute"); try { instance.setAttribute(attribute); @@ -756,32 +605,8 @@ public AttributeList setAttributes(ObjectName name, name = nonDefaultDomain(name); final DynamicMBean instance = getMBean(name); - final AttributeList allowedAttributes; - @SuppressWarnings("removal") - final SecurityManager sm = System.getSecurityManager(); - if (sm == null) - allowedAttributes = attributes; - else { - String classname = getClassName(instance); - - // Check if the caller has the right to invoke 'setAttribute' - // - checkMBeanPermission(classname, null, name, "setAttribute"); + final AttributeList allowedAttributes = attributes; - // Check if the caller has the right to invoke 'setAttribute' - // on each specific attribute - // - allowedAttributes = new AttributeList(attributes.size()); - for (Attribute attribute : attributes.asList()) { - try { - checkMBeanPermission(classname, attribute.getName(), - name, "setAttribute"); - allowedAttributes.add(attribute); - } catch (SecurityException e) { - // OK: Do not add this attribute to the list - } - } - } try { return instance.setAttributes(allowedAttributes); } catch (Throwable t) { @@ -798,7 +623,6 @@ public Object invoke(ObjectName name, String operationName, name = nonDefaultDomain(name); DynamicMBean instance = getMBean(name); - checkMBeanPermission(instance, operationName, name, "invoke"); try { return instance.invoke(operationName, params, signature); } catch (Throwable t) { @@ -922,8 +746,6 @@ private ObjectInstance registerDynamicMBean(String classname, ObjectName.getInstance(nonDefaultDomain(logicalName)); } - checkMBeanPermission(classname, null, logicalName, "registerMBean"); - if (logicalName == null) { final RuntimeException wrapped = new IllegalArgumentException("No object name specified"); @@ -1159,7 +981,6 @@ public void addNotificationListener(ObjectName name, } DynamicMBean instance = getMBean(name); - checkMBeanPermission(instance, null, name, "addNotificationListener"); NotificationBroadcaster broadcaster = getNotificationBroadcaster(name, instance, @@ -1288,7 +1109,6 @@ private void removeNotificationListener(ObjectName name, } DynamicMBean instance = getMBean(name); - checkMBeanPermission(instance, null, name, "removeNotificationListener"); /* We could simplify the code by assigning broadcaster after assigning listenerWrapper, but that would change the error @@ -1356,8 +1176,6 @@ public MBeanInfo getMBeanInfo(ObjectName name) throw new JMRuntimeException("MBean " + name + "has no MBeanInfo"); - checkMBeanPermission(mbi.getClassName(), null, name, "getMBeanInfo"); - return mbi; } @@ -1365,7 +1183,6 @@ public boolean isInstanceOf(ObjectName name, String className) throws InstanceNotFoundException { final DynamicMBean instance = getMBean(name); - checkMBeanPermission(instance, null, name, "isInstanceOf"); try { Object resource = getResource(instance); @@ -1407,7 +1224,6 @@ public ClassLoader getClassLoaderFor(ObjectName mbeanName) throws InstanceNotFoundException { DynamicMBean instance = getMBean(mbeanName); - checkMBeanPermission(instance, null, mbeanName, "getClassLoaderFor"); return getResource(instance).getClass().getClassLoader(); } @@ -1422,12 +1238,10 @@ public ClassLoader getClassLoader(ObjectName loaderName) throws InstanceNotFoundException { if (loaderName == null) { - checkMBeanPermission((String) null, null, null, "getClassLoader"); return server.getClass().getClassLoader(); } DynamicMBean instance = getMBean(loaderName); - checkMBeanPermission(instance, null, loaderName, "getClassLoader"); Object resource = getResource(instance); @@ -1565,48 +1379,6 @@ private static String safeGetClassName(DynamicMBean mbean) { } } - /** - * Applies the specified queries to the set of ObjectInstances. - */ - private Set - filterListOfObjectInstances(Set list, - QueryExp query) { - // Null query. - // - if (query == null) { - return list; - } else { - Set result = new HashSet<>(); - // Access the filter. - // - for (ObjectInstance oi : list) { - boolean res = false; - MBeanServer oldServer = QueryEval.getMBeanServer(); - query.setMBeanServer(server); - try { - res = query.apply(oi.getObjectName()); - } catch (Exception e) { - res = false; - } finally { - /* - * query.setMBeanServer is probably - * QueryEval.setMBeanServer so put back the old - * value. Since that method uses a ThreadLocal - * variable, this code is only needed for the - * unusual case where the user creates a custom - * QueryExp that calls a nested query on another - * MBeanServer. - */ - query.setMBeanServer(oldServer); - } - if (res) { - result.add(oi); - } - } - return result; - } - } - /* * Get the existing wrapper for this listener, name, and mbean, if * there is one. Otherwise, if "create" is true, create and @@ -1749,56 +1521,6 @@ private static String getClassName(DynamicMBean mbean) { return mbean.getMBeanInfo().getClassName(); } - private static void checkMBeanPermission(DynamicMBean mbean, - String member, - ObjectName objectName, - String actions) { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - checkMBeanPermission(safeGetClassName(mbean), - member, - objectName, - actions); - } - } - - private static void checkMBeanPermission(String classname, - String member, - ObjectName objectName, - String actions) { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - Permission perm = new MBeanPermission(classname, - member, - objectName, - actions); - sm.checkPermission(perm); - } - } - - private static void checkMBeanTrustPermission(final Class theClass) - throws SecurityException { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - Permission perm = new MBeanTrustPermission("register"); - PrivilegedAction act = - new PrivilegedAction<>() { - public ProtectionDomain run() { - return theClass.getProtectionDomain(); - } - }; - @SuppressWarnings("removal") - ProtectionDomain pd = AccessController.doPrivileged(act); - @SuppressWarnings("removal") - AccessControlContext acc = - new AccessControlContext(new ProtectionDomain[] { pd }); - sm.checkPermission(perm, acc); - } - } - // ------------------------------------------------------------------ // // Dealing with registration of special MBeans in the repository. @@ -2006,13 +1728,7 @@ private ResourceContext makeResourceContextFor(Object resource, return ResourceContext.NONE; } - @SuppressWarnings("removal") private ModifiableClassLoaderRepository getInstantiatorCLR() { - return AccessController.doPrivileged(new PrivilegedAction<>() { - @Override - public ModifiableClassLoaderRepository run() { - return instantiator != null ? instantiator.getClassLoaderRepository() : null; - } - }); + return instantiator != null ? instantiator.getClassLoaderRepository() : null; } } diff --git a/src/java.management/share/classes/com/sun/jmx/mbeanserver/ClassLoaderRepositorySupport.java b/src/java.management/share/classes/com/sun/jmx/mbeanserver/ClassLoaderRepositorySupport.java index a73e46e6020..78dc5ce2ea1 100644 --- a/src/java.management/share/classes/com/sun/jmx/mbeanserver/ClassLoaderRepositorySupport.java +++ b/src/java.management/share/classes/com/sun/jmx/mbeanserver/ClassLoaderRepositorySupport.java @@ -27,18 +27,15 @@ import static com.sun.jmx.defaults.JmxProperties.MBEANSERVER_LOGGER; -import java.security.Permission; import java.util.ArrayList; import java.util.Arrays; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.lang.System.Logger.Level; -import javax.management.MBeanPermission; import javax.management.ObjectName; import javax.management.loading.PrivateClassLoader; -import sun.reflect.misc.ReflectUtil; /** * This class keeps the list of Class Loaders registered in the MBean Server. @@ -192,7 +189,6 @@ private Class loadClass(final LoaderEntry list[], final ClassLoader without, final ClassLoader stop) throws ClassNotFoundException { - ReflectUtil.checkPackageAccess(className); final int size = list.length; for(int i=0; iA converter between Java types and the limited set of classes @@ -301,7 +300,6 @@ recognizes the Type (Chain of Responsibility pattern). */ private static > MXBeanMapping makeEnumMapping(Class enumClass, Class fake) { - ReflectUtil.checkPackageAccess(enumClass); return new EnumMapping<>(Util.>cast(enumClass)); } @@ -426,7 +424,6 @@ private MXBeanMapping makeCompositeMapping(Class c, (c.getName().equals("com.sun.management.GcInfo") && c.getClassLoader() == null); - ReflectUtil.checkPackageAccess(c); final List methods = MBeanAnalyzer.eliminateCovariantMethods(Arrays.asList(c.getMethods())); final SortedMap getterMap = newSortedMap(); @@ -1119,7 +1116,6 @@ Object fromCompositeData(CompositeData cd, Object o; try { final Class targetClass = getTargetClass(); - ReflectUtil.checkPackageAccess(targetClass); @SuppressWarnings("deprecation") Object tmp = targetClass.newInstance(); o = tmp; @@ -1375,7 +1371,6 @@ Object fromCompositeData(CompositeData cd, } try { - ReflectUtil.checkPackageAccess(max.constructor.getDeclaringClass()); return max.constructor.newInstance(params); } catch (Exception e) { final String msg = diff --git a/src/java.management/share/classes/com/sun/jmx/mbeanserver/GetPropertyAction.java b/src/java.management/share/classes/com/sun/jmx/mbeanserver/GetPropertyAction.java deleted file mode 100644 index 2628c4ac2a3..00000000000 --- a/src/java.management/share/classes/com/sun/jmx/mbeanserver/GetPropertyAction.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) 2002, 2004, 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 com.sun.jmx.mbeanserver; - -import java.security.PrivilegedAction; - -/** - * Utility class to be used by the method {@code AccessControler.doPrivileged} - * to get a system property. - * - * @since 1.5 - */ -public class GetPropertyAction implements PrivilegedAction { - private final String key; - - public GetPropertyAction(String key) { - this.key = key; - } - - public String run() { - return System.getProperty(key); - } -} diff --git a/src/java.management/share/classes/com/sun/jmx/mbeanserver/Introspector.java b/src/java.management/share/classes/com/sun/jmx/mbeanserver/Introspector.java index ea1d685b5fc..374dd57a4ee 100644 --- a/src/java.management/share/classes/com/sun/jmx/mbeanserver/Introspector.java +++ b/src/java.management/share/classes/com/sun/jmx/mbeanserver/Introspector.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2023, 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 @@ -52,12 +52,10 @@ import com.sun.jmx.remote.util.EnvHelp; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; -import java.security.AccessController; import javax.management.AttributeNotFoundException; import javax.management.openmbean.CompositeData; import sun.reflect.misc.MethodUtil; -import sun.reflect.misc.ReflectUtil; /** * This class contains the methods for performing all the tests needed to verify @@ -66,12 +64,7 @@ * @since 1.5 */ public class Introspector { - public static final boolean ALLOW_NONPUBLIC_MBEAN; - static { - @SuppressWarnings("removal") - String val = AccessController.doPrivileged(new GetPropertyAction("jdk.jmx.mbeans.allowNonPublic")); - ALLOW_NONPUBLIC_MBEAN = Boolean.parseBoolean(val); - } + public static final boolean ALLOW_NONPUBLIC_MBEAN = Boolean.parseBoolean(System.getProperty("jdk.jmx.mbeans.allowNonPublic")); /* * ------------------------------------------ @@ -276,7 +269,6 @@ public static void testComplianceMBeanInterface(Class interfaceClass) throws NotCompliantMBeanException { if (mbeanInterface == null) mbeanInterface = getStandardMBeanInterface(baseClass); - ReflectUtil.checkPackageAccess(mbeanInterface); MBeanIntrospector introspector = StandardMBeanIntrospector.getInstance(); return getClassMBeanInfo(introspector, baseClass, mbeanInterface); } @@ -401,18 +393,12 @@ public static Descriptor descriptorForAnnotations(Annotation[] annots) { for (Annotation a : annots) { Class c = a.annotationType(); Method[] elements = c.getMethods(); - boolean packageAccess = false; for (Method element : elements) { DescriptorKey key = element.getAnnotation(DescriptorKey.class); if (key != null) { String name = key.value(); Object value; try { - // Avoid checking access more than once per annotation - if (!packageAccess) { - ReflectUtil.checkPackageAccess(c); - packageAccess = true; - } value = MethodUtil.invoke(element, a, null); } catch (RuntimeException e) { // we don't expect this - except for possibly @@ -560,7 +546,6 @@ public static Object elementFromComplex(Object complex, String element) readMethod = SimpleIntrospector.getReadMethod(clazz, element); } if (readMethod != null) { - ReflectUtil.checkPackageAccess(readMethod.getDeclaringClass()); return MethodUtil.invoke(readMethod, complex, new Class[0]); } diff --git a/src/java.management/share/classes/com/sun/jmx/mbeanserver/JmxMBeanServer.java b/src/java.management/share/classes/com/sun/jmx/mbeanserver/JmxMBeanServer.java index 85f433ab11f..fd7bf8fbcae 100644 --- a/src/java.management/share/classes/com/sun/jmx/mbeanserver/JmxMBeanServer.java +++ b/src/java.management/share/classes/com/sun/jmx/mbeanserver/JmxMBeanServer.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 @@ -30,10 +30,6 @@ import static com.sun.jmx.defaults.JmxProperties.MBEANSERVER_LOGGER; import java.io.ObjectInputStream; -import java.security.AccessController; -import java.security.Permission; -import java.security.PrivilegedAction; -import java.security.PrivilegedExceptionAction; import java.util.List; import java.util.Set; import java.lang.System.Logger.Level; @@ -48,11 +44,9 @@ import javax.management.ListenerNotFoundException; import javax.management.MBeanException; import javax.management.MBeanInfo; -import javax.management.MBeanPermission; import javax.management.MBeanRegistrationException; import javax.management.MBeanServer; import javax.management.MBeanServerDelegate; -import javax.management.MBeanServerPermission; import javax.management.NotCompliantMBeanException; import javax.management.NotificationFilter; import javax.management.NotificationListener; @@ -232,13 +226,7 @@ public final class JmxMBeanServer final MBeanInstantiator fInstantiator = instantiator; this.secureClr = new - SecureClassLoaderRepository(AccessController.doPrivileged(new PrivilegedAction<>() { - @Override - public ClassLoaderRepository run() { - return fInstantiator.getClassLoaderRepository(); - } - }) - ); + SecureClassLoaderRepository(fInstantiator.getClassLoaderRepository()); if (delegate == null) delegate = new MBeanServerDelegateImpl(); if (outer == null) @@ -947,9 +935,6 @@ public MBeanInfo getMBeanInfo(ObjectName name) throws public Object instantiate(String className) throws ReflectionException, MBeanException { - /* Permission check */ - checkMBeanPermission(className, null, null, "instantiate"); - return instantiator.instantiate(className); } @@ -984,9 +969,6 @@ public Object instantiate(String className, ObjectName loaderName) throws ReflectionException, MBeanException, InstanceNotFoundException { - /* Permission check */ - checkMBeanPermission(className, null, null, "instantiate"); - ClassLoader myLoader = outerShell.getClass().getClassLoader(); return instantiator.instantiate(className, loaderName, myLoader); } @@ -1022,9 +1004,6 @@ public Object instantiate(String className, Object params[], String signature[]) throws ReflectionException, MBeanException { - /* Permission check */ - checkMBeanPermission(className, null, null, "instantiate"); - ClassLoader myLoader = outerShell.getClass().getClassLoader(); return instantiator.instantiate(className, params, signature, myLoader); @@ -1065,9 +1044,6 @@ public Object instantiate(String className, ObjectName loaderName, throws ReflectionException, MBeanException, InstanceNotFoundException { - /* Permission check */ - checkMBeanPermission(className, null, null, "instantiate"); - ClassLoader myLoader = outerShell.getClass().getClassLoader(); return instantiator.instantiate(className,loaderName,params,signature, myLoader); @@ -1112,8 +1088,6 @@ public boolean isInstanceOf(ObjectName name, String className) public ObjectInputStream deserialize(ObjectName name, byte[] data) throws InstanceNotFoundException, OperationsException { - /* Permission check */ - // This call requires MBeanPermission 'getClassLoaderFor' final ClassLoader loader = getClassLoaderFor(name); return instantiator.deserialize(loader, data); @@ -1145,8 +1119,6 @@ public ObjectInputStream deserialize(String className, byte[] data) "Null className passed in parameter"); } - /* Permission check */ - // This call requires MBeanPermission 'getClassLoaderRepository' final ClassLoaderRepository clr = getClassLoaderRepository(); Class theClass; @@ -1197,16 +1169,6 @@ public ObjectInputStream deserialize(String className, // loaderName = cloneObjectName(loaderName); - /* Permission check */ - // Make this call just to force the 'getClassLoader' - // permission check - try { - getClassLoader(loaderName); - } catch (SecurityException e) { - throw e; - } catch (Exception e) { - } - ClassLoader myLoader = outerShell.getClass().getClassLoader(); return instantiator.deserialize(className, loaderName, data, myLoader); } @@ -1222,14 +1184,7 @@ private void initialize() { // Registers the MBeanServer identification MBean try { - AccessController.doPrivileged(new PrivilegedExceptionAction<>() { - public Object run() throws Exception { - mbsInterceptor.registerMBean( - mBeanServerDelegateObject, - MBeanServerDelegate.DELEGATE_NAME); - return null; - } - }); + mbsInterceptor.registerMBean(mBeanServerDelegateObject, MBeanServerDelegate.DELEGATE_NAME); } catch (SecurityException e) { if (MBEANSERVER_LOGGER.isLoggable(Level.DEBUG)) { MBEANSERVER_LOGGER.log(Level.DEBUG, @@ -1251,13 +1206,7 @@ public Object run() throws Exception { class loader. The ClassLoaderRepository knows how to handle that case. */ ClassLoader myLoader = outerShell.getClass().getClassLoader(); - final ModifiableClassLoaderRepository loaders = AccessController.doPrivileged(new PrivilegedAction<>() { - - @Override - public ModifiableClassLoaderRepository run() { - return instantiator.getClassLoaderRepository(); - } - }); + final ModifiableClassLoaderRepository loaders = instantiator.getClassLoaderRepository(); if (loaders != null) { loaders.addClassLoader(myLoader); @@ -1266,17 +1215,8 @@ public ModifiableClassLoaderRepository run() { loaded by the bootstrap class loader we can still load MBeans from the classpath using createMBean(className, objectName). + */ - If this class (JmxMBeanServer) was not loaded by the - system class loader or a parent of it, then the caller - must have RuntimePermission("getClassLoader") for the - getSystemClassLoader() call to succeed. If the caller - does not have that permission, any call to - Class.getClassLoader() will fail. Since there are lots - of those in JMX, we better throw the exception now. - - This permission question is irrelevant when JMX is part - of J2SE (as of 1.5). */ ClassLoader systemLoader = ClassLoader.getSystemClassLoader(); if (systemLoader != myLoader) loaders.addClassLoader(systemLoader); @@ -1341,8 +1281,6 @@ public ClassLoader getClassLoader(ObjectName loaderName) * @return The ClassLoaderRepository for that MBeanServer. **/ public ClassLoaderRepository getClassLoaderRepository() { - /* Permission check */ - checkMBeanPermission(null, null, null, "getClassLoaderRepository"); return secureClr; } @@ -1425,8 +1363,6 @@ public static MBeanServer newMBeanServer(String defaultDomain, // Default is true. final boolean fairLock = DEFAULT_FAIR_LOCK_POLICY; - checkNewMBeanServerPermission(); - // This constructor happens to disregard the value of the interceptors // flag - that is, it always uses the default value - false. // This is admittedly a bug, but we chose not to fix it for now @@ -1493,32 +1429,4 @@ private AttributeList cloneAttributeList(AttributeList list) { } return list; } - - // SECURITY CHECKS - //---------------- - - private static void checkMBeanPermission(String classname, - String member, - ObjectName objectName, - String actions) - throws SecurityException { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - Permission perm = new MBeanPermission(classname, - member, - objectName, - actions); - sm.checkPermission(perm); - } - } - - private static void checkNewMBeanServerPermission() { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - Permission perm = new MBeanServerPermission("newMBeanServer"); - sm.checkPermission(perm); - } - } } diff --git a/src/java.management/share/classes/com/sun/jmx/mbeanserver/MBeanInstantiator.java b/src/java.management/share/classes/com/sun/jmx/mbeanserver/MBeanInstantiator.java index 6de9ca2873c..53eeb721a13 100644 --- a/src/java.management/share/classes/com/sun/jmx/mbeanserver/MBeanInstantiator.java +++ b/src/java.management/share/classes/com/sun/jmx/mbeanserver/MBeanInstantiator.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 @@ -33,18 +33,12 @@ import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Modifier; -import java.security.AccessControlContext; -import java.security.AccessController; -import java.security.Permission; -import java.security.Permissions; -import java.security.PrivilegedAction; import java.security.ProtectionDomain; import java.util.Map; import java.lang.System.Logger.Level; import javax.management.InstanceNotFoundException; import javax.management.MBeanException; -import javax.management.MBeanPermission; import javax.management.NotCompliantMBeanException; import javax.management.ObjectName; import javax.management.OperationsException; @@ -53,7 +47,6 @@ import javax.management.RuntimeMBeanException; import javax.management.RuntimeOperationsException; import sun.reflect.misc.ConstructorUtil; -import sun.reflect.misc.ReflectUtil; /** * Implements the MBeanInstantiator interface. Provides methods for @@ -95,7 +88,6 @@ public Class findClassWithDefaultLoaderRepository(String className) "Exception occurred during object instantiation"); } - ReflectUtil.checkPackageAccess(className); try { if (clr == null) throw new ClassNotFoundException(className); theClass = clr.loadClass(className); @@ -169,7 +161,6 @@ public Class[] findSignatureClasses(String signature[], continue; } - ReflectUtil.checkPackageAccess(signature[i]); // Ok we do not have a primitive type ! We need to build // the signature of the method // @@ -210,8 +201,6 @@ public Class[] findSignatureClasses(String signature[], public Object instantiate(Class theClass) throws ReflectionException, MBeanException { - checkMBeanPermission(theClass, null, null, "instantiate"); - Object moi; // ------------------------------ @@ -223,7 +212,6 @@ public Object instantiate(Class theClass) } // Instantiate the new object try { - ReflectUtil.checkPackageAccess(theClass); ensureClassAccess(theClass); moi= cons.newInstance(); } catch (InvocationTargetException e) { @@ -262,8 +250,6 @@ public Object instantiate(Class theClass, Object params[], String signature[], ClassLoader loader) throws ReflectionException, MBeanException { - checkMBeanPermission(theClass, null, null, "instantiate"); - // Instantiate the new object // ------------------------------ // ------------------------------ @@ -293,7 +279,6 @@ public Object instantiate(Class theClass, Object params[], NoSuchMethodException("No such constructor")); } try { - ReflectUtil.checkPackageAccess(theClass); ensureClassAccess(theClass); moi = cons.newInstance(params); } @@ -408,7 +393,6 @@ public ObjectInputStream deserialize(String className, IllegalArgumentException(), "Null className passed in parameter"); } - ReflectUtil.checkPackageAccess(className); Class theClass; if (loaderName == null) { // Load the class using the agent class loader @@ -611,7 +595,6 @@ public Object instantiate(String className, * Return the Default Loader Repository used by this instantiator object. **/ public ModifiableClassLoaderRepository getClassLoaderRepository() { - checkMBeanPermission((String)null, null, null, "getClassLoaderRepository"); return clr; } @@ -627,7 +610,6 @@ static Class loadClass(String className, ClassLoader loader) IllegalArgumentException("The class name cannot be null"), "Exception occurred during object instantiation"); } - ReflectUtil.checkPackageAccess(className); try { if (loader == null) loader = MBeanInstantiator.class.getClassLoader(); @@ -678,7 +660,6 @@ static Class[] loadSignatureClasses(String signature[], // We need to load the class through the class // loader of the target object. // - ReflectUtil.checkPackageAccess(signature[i]); tab[i] = Class.forName(signature[i], false, aLoader); } } catch (ClassNotFoundException e) { @@ -715,31 +696,6 @@ private Constructor findConstructor(Class c, Class[] params) { primitiveClasses.put(c.getName(), c); } - private static void checkMBeanPermission(Class clazz, - String member, - ObjectName objectName, - String actions) { - if (clazz != null) { - checkMBeanPermission(clazz.getName(), member, objectName, actions); - } - } - - private static void checkMBeanPermission(String classname, - String member, - ObjectName objectName, - String actions) - throws SecurityException { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - Permission perm = new MBeanPermission(classname, - member, - objectName, - actions); - sm.checkPermission(perm); - } - } - private static void ensureClassAccess(Class clazz) throws IllegalAccessException { @@ -752,20 +708,8 @@ private static void ensureClassAccess(Class clazz) private ClassLoader getClassLoader(final ObjectName name) { if(clr == null){ return null; + } else { + return clr.getClassLoader(name); } - // Restrict to getClassLoader permission only - Permissions permissions = new Permissions(); - permissions.add(new MBeanPermission("*", null, name, "getClassLoader")); - ProtectionDomain protectionDomain = new ProtectionDomain(null, permissions); - ProtectionDomain[] domains = {protectionDomain}; - @SuppressWarnings("removal") - AccessControlContext ctx = new AccessControlContext(domains); - @SuppressWarnings("removal") - ClassLoader loader = AccessController.doPrivileged(new PrivilegedAction<>() { - public ClassLoader run() { - return clr.getClassLoader(name); - } - }, ctx); - return loader; } } diff --git a/src/java.management/share/classes/com/sun/jmx/mbeanserver/MBeanIntrospector.java b/src/java.management/share/classes/com/sun/jmx/mbeanserver/MBeanIntrospector.java index b80bb165a7b..fdbb961630c 100644 --- a/src/java.management/share/classes/com/sun/jmx/mbeanserver/MBeanIntrospector.java +++ b/src/java.management/share/classes/com/sun/jmx/mbeanserver/MBeanIntrospector.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2022, 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 @@ -50,7 +50,6 @@ import javax.management.NotCompliantMBeanException; import javax.management.NotificationBroadcaster; import javax.management.ReflectionException; -import sun.reflect.misc.ReflectUtil; /** * An introspector for MBeans of a certain type. There is one instance @@ -176,7 +175,6 @@ abstract MBeanOperationInfo getMBeanOperationInfo(String operationName, * Get the methods to be analyzed to build the MBean interface. */ final List getMethods(final Class mbeanType) { - ReflectUtil.checkPackageAccess(mbeanType); return Arrays.asList(mbeanType.getMethods()); } diff --git a/src/java.management/share/classes/com/sun/jmx/mbeanserver/MBeanSupport.java b/src/java.management/share/classes/com/sun/jmx/mbeanserver/MBeanSupport.java index ec40a30406b..f63222f251f 100644 --- a/src/java.management/share/classes/com/sun/jmx/mbeanserver/MBeanSupport.java +++ b/src/java.management/share/classes/com/sun/jmx/mbeanserver/MBeanSupport.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2022, 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 @@ -38,7 +38,6 @@ import javax.management.ObjectName; import javax.management.ReflectionException; import com.sun.jmx.mbeanserver.MXBeanMappingFactory; -import sun.reflect.misc.ReflectUtil; /** * Base class for MBeans. There is one instance of this class for @@ -132,7 +131,6 @@ MBeanSupport(T resource, Class mbeanInterfaceType) " is not an instance of " + mbeanInterfaceType.getName(); throw new NotCompliantMBeanException(msg); } - ReflectUtil.checkPackageAccess(mbeanInterfaceType); this.resource = resource; MBeanIntrospector introspector = getMBeanIntrospector(); this.perInterface = introspector.getPerInterface(mbeanInterfaceType); diff --git a/src/java.management/share/classes/com/sun/jmx/mbeanserver/MXBeanLookup.java b/src/java.management/share/classes/com/sun/jmx/mbeanserver/MXBeanLookup.java index fd291133d08..0027710d06a 100644 --- a/src/java.management/share/classes/com/sun/jmx/mbeanserver/MXBeanLookup.java +++ b/src/java.management/share/classes/com/sun/jmx/mbeanserver/MXBeanLookup.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2022, 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 @@ -30,7 +30,6 @@ import java.lang.ref.WeakReference; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; -import java.security.AccessController; import javax.management.InstanceAlreadyExistsException; import javax.management.JMX; import javax.management.MBeanServerConnection; @@ -145,9 +144,7 @@ synchronized void addReference(ObjectName name, Object mxbean) throws InstanceAlreadyExistsException { ObjectName existing = mxbeanToObjectName.get(mxbean); if (existing != null) { - @SuppressWarnings("removal") - String multiname = AccessController.doPrivileged( - new GetPropertyAction("jmx.mxbean.multiname")); + String multiname = System.getProperty("jmx.mxbean.multiname"); if (!"true".equalsIgnoreCase(multiname)) { throw new InstanceAlreadyExistsException( "MXBean already registered with name " + existing); diff --git a/src/java.management/share/classes/com/sun/jmx/mbeanserver/ObjectInputStreamWithLoader.java b/src/java.management/share/classes/com/sun/jmx/mbeanserver/ObjectInputStreamWithLoader.java index 4f3e4a43893..339b708ef18 100644 --- a/src/java.management/share/classes/com/sun/jmx/mbeanserver/ObjectInputStreamWithLoader.java +++ b/src/java.management/share/classes/com/sun/jmx/mbeanserver/ObjectInputStreamWithLoader.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2013, 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 @@ -30,7 +30,6 @@ import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectStreamClass; -import sun.reflect.misc.ReflectUtil; /** * This class deserializes an object in the context of a specific class loader. @@ -61,7 +60,6 @@ protected Class resolveClass(ObjectStreamClass aClass) return super.resolveClass(aClass); } else { String name = aClass.getName(); - ReflectUtil.checkPackageAccess(name); // Query the class loader ... return Class.forName(name, false, loader); } diff --git a/src/java.management/share/classes/com/sun/jmx/mbeanserver/PerInterface.java b/src/java.management/share/classes/com/sun/jmx/mbeanserver/PerInterface.java index 9522208aafe..6684e0390cf 100644 --- a/src/java.management/share/classes/com/sun/jmx/mbeanserver/PerInterface.java +++ b/src/java.management/share/classes/com/sun/jmx/mbeanserver/PerInterface.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,7 +25,6 @@ package com.sun.jmx.mbeanserver; -import java.security.AccessController; import java.util.Arrays; import java.util.Collections; import java.util.List; @@ -175,15 +174,7 @@ private Object noSuchMethod(String msg, Object resource, String operation, throw exception; // No compatibility requirement here // Is the compatibility property set? - GetPropertyAction act = new GetPropertyAction("jmx.invoke.getters"); - String invokeGettersS; - try { - invokeGettersS = AccessController.doPrivileged(act); - } catch (Exception e) { - // We don't expect an exception here but if we get one then - // we'll simply assume that the property is not set. - invokeGettersS = null; - } + String invokeGettersS = System.getProperty("jmx.invoke.getters"); if (invokeGettersS == null) throw exception; diff --git a/src/java.management/share/classes/com/sun/jmx/remote/internal/ArrayNotificationBuffer.java b/src/java.management/share/classes/com/sun/jmx/remote/internal/ArrayNotificationBuffer.java index b2f8e4c028e..d06456a73dd 100644 --- a/src/java.management/share/classes/com/sun/jmx/remote/internal/ArrayNotificationBuffer.java +++ b/src/java.management/share/classes/com/sun/jmx/remote/internal/ArrayNotificationBuffer.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 @@ -25,10 +25,6 @@ package com.sun.jmx.remote.internal; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -396,20 +392,6 @@ public void dispose() { if (nextSeq < nextSequenceNumber()) { candidate = notificationAt(nextSeq); - // Skip security check if NotificationBufferFilter is not overloaded - if (!(filter instanceof ServerNotifForwarder.NotifForwarderBufferFilter)) { - try { - ServerNotifForwarder.checkMBeanPermission(this.mBeanServer, - candidate.getObjectName(),"addNotificationListener"); - } catch (InstanceNotFoundException | SecurityException e) { - if (logger.debugOn()) { - logger.debug("fetchNotifications", "candidate: " + candidate + " skipped. exception " + e); - } - ++nextSeq; - continue; - } - } - if (logger.debugOn()) { logger.debug("fetchNotifications", "candidate: " + candidate); @@ -653,54 +635,27 @@ private void removeBufferListener(ObjectName name) { } } - @SuppressWarnings("removal") private void addNotificationListener(final ObjectName name, final NotificationListener listener, final NotificationFilter filter, final Object handback) throws Exception { - try { - AccessController.doPrivileged(new PrivilegedExceptionAction() { - public Void run() throws InstanceNotFoundException { - mBeanServer.addNotificationListener(name, - listener, - filter, - handback); - return null; - } - }); - } catch (Exception e) { - throw extractException(e); - } + mBeanServer.addNotificationListener(name, + listener, + filter, + handback); } - @SuppressWarnings("removal") private void removeNotificationListener(final ObjectName name, final NotificationListener listener) throws Exception { - try { - AccessController.doPrivileged(new PrivilegedExceptionAction() { - public Void run() throws Exception { - mBeanServer.removeNotificationListener(name, listener); - return null; - } - }); - } catch (Exception e) { - throw extractException(e); - } + mBeanServer.removeNotificationListener(name, listener); } - @SuppressWarnings("removal") private Set queryNames(final ObjectName name, final QueryExp query) { - PrivilegedAction> act = - new PrivilegedAction<>() { - public Set run() { - return mBeanServer.queryNames(name, query); - } - }; try { - return AccessController.doPrivileged(act); + return mBeanServer.queryNames(name, query); } catch (RuntimeException e) { logger.fine("queryNames", "Failed to query names: " + e); logger.debug("queryNames", e); @@ -708,18 +663,11 @@ public Set run() { } } - @SuppressWarnings("removal") private static boolean isInstanceOf(final MBeanServer mbs, final ObjectName name, final String className) { - PrivilegedExceptionAction act = - new PrivilegedExceptionAction<>() { - public Boolean run() throws InstanceNotFoundException { - return mbs.isInstanceOf(name, className); - } - }; try { - return AccessController.doPrivileged(act); + return mbs.isInstanceOf(name, className); } catch (Exception e) { logger.fine("isInstanceOf", "failed: " + e); logger.debug("isInstanceOf", e); @@ -825,17 +773,6 @@ private void checkNoLocks() { logger.warning("checkNoLocks", "lock protocol violation"); } - /** - * Iterate until we extract the real exception - * from a stack of PrivilegedActionExceptions. - */ - private static Exception extractException(Exception e) { - while (e instanceof PrivilegedActionException) { - e = ((PrivilegedActionException)e).getException(); - } - return e; - } - private static final ClassLogger logger = new ClassLogger("javax.management.remote.misc", "ArrayNotificationBuffer"); diff --git a/src/java.management/share/classes/com/sun/jmx/remote/internal/ClientNotifForwarder.java b/src/java.management/share/classes/com/sun/jmx/remote/internal/ClientNotifForwarder.java index 471cccecc8a..87947e06ac8 100644 --- a/src/java.management/share/classes/com/sun/jmx/remote/internal/ClientNotifForwarder.java +++ b/src/java.management/share/classes/com/sun/jmx/remote/internal/ClientNotifForwarder.java @@ -33,9 +33,6 @@ import java.util.Map; import java.util.concurrent.Executor; -import java.security.AccessControlContext; -import java.security.AccessController; -import java.security.PrivilegedAction; import javax.security.auth.Subject; import javax.management.Notification; @@ -56,9 +53,6 @@ public abstract class ClientNotifForwarder { - @SuppressWarnings("removal") - private final AccessControlContext acc; - public ClientNotifForwarder(Map env) { this(null, env); } @@ -139,7 +133,6 @@ else if (logger.traceOn()) this.defaultClassLoader = defaultClassLoader; this.executor = ex; - this.acc = AccessController.getContext(); } /** @@ -419,40 +412,14 @@ private void logOnce(String msg, SecurityException x) { } // Set new context class loader, returns previous one. - @SuppressWarnings("removal") private final ClassLoader setContextClassLoader(final ClassLoader loader) { - final AccessControlContext ctxt = ClientNotifForwarder.this.acc; - // if ctxt is null, log a config message and throw a - // SecurityException. - if (ctxt == null) { - logOnce("AccessControlContext must not be null.",null); - throw new SecurityException("AccessControlContext must not be null"); - } - return AccessController.doPrivileged( - new PrivilegedAction<>() { - public ClassLoader run() { - try { - // get context class loader - may throw - // SecurityException - though unlikely. - final ClassLoader previous = - Thread.currentThread().getContextClassLoader(); - - // if nothing needs to be done, break here... - if (loader == previous) return previous; - - // reset context class loader - may throw - // SecurityException - Thread.currentThread().setContextClassLoader(loader); - return previous; - } catch (SecurityException x) { - logOnce("Permission to set ContextClassLoader missing. " + - "Notifications will not be dispatched. " + - "Please check your Java policy configuration: " + - x, x); - throw x; - } - } - }, ctxt); + final ClassLoader previous = Thread.currentThread().getContextClassLoader(); + + // if nothing needs to be done, break here... + if (loader == previous) return previous; + + Thread.currentThread().setContextClassLoader(loader); + return previous; } public void run() { diff --git a/src/java.management/share/classes/com/sun/jmx/remote/internal/ServerNotifForwarder.java b/src/java.management/share/classes/com/sun/jmx/remote/internal/ServerNotifForwarder.java index dd557523e65..a1f5ece89a2 100644 --- a/src/java.management/share/classes/com/sun/jmx/remote/internal/ServerNotifForwarder.java +++ b/src/java.management/share/classes/com/sun/jmx/remote/internal/ServerNotifForwarder.java @@ -29,10 +29,6 @@ import com.sun.jmx.remote.util.ClassLogger; import com.sun.jmx.remote.util.EnvHelp; import java.io.IOException; -import java.security.AccessControlContext; -import java.security.AccessController; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -85,30 +81,16 @@ public Integer addNotificationListener(final ObjectName name, checkState(); - // Explicitly check MBeanPermission for addNotificationListener - // - checkMBeanPermission(name, "addNotificationListener"); if (notificationAccessController != null) { notificationAccessController.addNotificationListener( connectionId, name, getSubject()); } - try { - @SuppressWarnings("removal") - boolean instanceOf = - AccessController.doPrivileged( - new PrivilegedExceptionAction<>() { - public Boolean run() throws InstanceNotFoundException { - return mbeanServer.isInstanceOf(name, broadcasterClass); - } - }); - if (!instanceOf) { - throw new IllegalArgumentException("The specified MBean [" + - name + "] is not a " + - "NotificationBroadcaster " + - "object."); - } - } catch (PrivilegedActionException e) { - throw (InstanceNotFoundException) extractException(e); + boolean instanceOf = mbeanServer.isInstanceOf(name, broadcasterClass); + if (!instanceOf) { + throw new IllegalArgumentException("The specified MBean [" + + name + "] is not a " + + "NotificationBroadcaster " + + "object."); } final Integer id = getListenerID(); @@ -154,9 +136,6 @@ public void removeNotificationListener(ObjectName name, checkState(); - // Explicitly check MBeanPermission for removeNotificationListener - // - checkMBeanPermission(name, "removeNotificationListener"); if (notificationAccessController != null) { notificationAccessController.removeNotificationListener( connectionId, name, getSubject()); @@ -373,55 +352,12 @@ private Integer getListenerID() { } } - /** - * Explicitly check the MBeanPermission for - * the current access control context. - */ - public final void checkMBeanPermission( - final ObjectName name, final String actions) - throws InstanceNotFoundException, SecurityException { - checkMBeanPermission(mbeanServer,name,actions); - } - - @SuppressWarnings("removal") - static void checkMBeanPermission( - final MBeanServer mbs, final ObjectName name, final String actions) - throws InstanceNotFoundException, SecurityException { - - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - AccessControlContext acc = AccessController.getContext(); - ObjectInstance oi; - try { - oi = AccessController.doPrivileged( - new PrivilegedExceptionAction<>() { - public ObjectInstance run() - throws InstanceNotFoundException { - return mbs.getObjectInstance(name); - } - }); - } catch (PrivilegedActionException e) { - throw (InstanceNotFoundException) extractException(e); - } - String classname = oi.getClassName(); - MBeanPermission perm = new MBeanPermission( - classname, - null, - name, - actions); - sm.checkPermission(perm, acc); - } - } - /** * Check if the caller has the right to get the following notifications. */ private boolean allowNotificationEmission(ObjectName name, TargetedNotification tn) { try { - if (checkNotificationEmission) { - checkMBeanPermission(name, "addNotificationListener"); - } if (notificationAccessController != null) { notificationAccessController.fetchNotification( connectionId, name, tn.getNotification(), getSubject()); @@ -444,17 +380,6 @@ private boolean allowNotificationEmission(ObjectName name, } } - /** - * Iterate until we extract the real exception - * from a stack of PrivilegedActionExceptions. - */ - private static Exception extractException(Exception e) { - while (e instanceof PrivilegedActionException) { - e = ((PrivilegedActionException)e).getException(); - } - return e; - } - private static class IdAndFilter { private Integer id; private NotificationFilter filter; diff --git a/src/java.management/share/classes/com/sun/jmx/remote/security/FileLoginModule.java b/src/java.management/share/classes/com/sun/jmx/remote/security/FileLoginModule.java index bb5d5e88ff3..65a1b424477 100644 --- a/src/java.management/share/classes/com/sun/jmx/remote/security/FileLoginModule.java +++ b/src/java.management/share/classes/com/sun/jmx/remote/security/FileLoginModule.java @@ -24,13 +24,9 @@ */ package com.sun.jmx.remote.security; -import com.sun.jmx.mbeanserver.GetPropertyAction; import com.sun.jmx.mbeanserver.Util; import java.io.File; -import java.io.FilePermission; import java.io.IOException; -import java.security.AccessControlException; -import java.security.AccessController; import java.util.Arrays; import java.util.Map; @@ -109,12 +105,9 @@ public class FileLoginModule implements LoginModule { private static final String PASSWORD_FILE_NAME = "jmxremote.password"; // Location of the default password file - @SuppressWarnings("removal") private static final String DEFAULT_PASSWORD_FILE_NAME = - AccessController.doPrivileged(new GetPropertyAction("java.home")) + - File.separatorChar + "conf" + - File.separatorChar + "management" + File.separatorChar + - PASSWORD_FILE_NAME; + System.getProperty("java.home") + File.separatorChar + "conf" + File.separatorChar + + "management" + File.separatorChar + PASSWORD_FILE_NAME; // Key to retrieve the stored username private static final String USERNAME_KEY = @@ -152,7 +145,6 @@ public class FileLoginModule implements LoginModule { private String passwordFile; private String passwordFileDisplayName; private boolean userSuppliedPasswordFile; - private boolean hasJavaHomePermission; private HashedPasswordManager hashPwdMgr; /** @@ -196,14 +188,7 @@ public void initialize(Subject subject, CallbackHandler callbackHandler, if (passwordFile == null) { passwordFile = DEFAULT_PASSWORD_FILE_NAME; userSuppliedPasswordFile = false; - try { - System.getProperty("java.home"); - hasJavaHomePermission = true; - passwordFileDisplayName = passwordFile; - } catch (SecurityException e) { - hasJavaHomePermission = false; - passwordFileDisplayName = PASSWORD_FILE_NAME; - } + passwordFileDisplayName = passwordFile; } } @@ -233,18 +218,6 @@ public boolean login() throws LoginException { "Error: unable to load the password file: " + passwordFileDisplayName); throw EnvHelp.initCause(le, ioe); - } catch (SecurityException e) { - if (userSuppliedPasswordFile || hasJavaHomePermission) { - throw e; - } else { - final FilePermission fp - = new FilePermission(passwordFileDisplayName, "read"); - @SuppressWarnings("removal") - AccessControlException ace = new AccessControlException( - "access denied " + fp.toString()); - ace.initCause(e); - throw ace; - } } if (logger.debugOn()) { diff --git a/src/java.management/share/classes/com/sun/jmx/remote/security/HashedPasswordManager.java b/src/java.management/share/classes/com/sun/jmx/remote/security/HashedPasswordManager.java index 8de1a71fd6a..c50b22fade6 100644 --- a/src/java.management/share/classes/com/sun/jmx/remote/security/HashedPasswordManager.java +++ b/src/java.management/share/classes/com/sun/jmx/remote/security/HashedPasswordManager.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2022, 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 @@ -232,16 +232,9 @@ public synchronized boolean authenticate(String userName, char[] inputPassword) * SHA3-512 hash * * @throws IOException If unable to access the file - * @throws SecurityException If read/write file permissions are not granted */ public synchronized void loadPasswords() - throws IOException, SecurityException { - - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); - if (security != null) { - security.checkRead(passwordFile); - } + throws IOException { AtomicBoolean hasClearPasswords = new AtomicBoolean(false); StringBuilder sbuf = new StringBuilder(); diff --git a/src/java.management/share/classes/com/sun/jmx/remote/security/JMXPluggableAuthenticator.java b/src/java.management/share/classes/com/sun/jmx/remote/security/JMXPluggableAuthenticator.java index f67bde263ea..89a77b3ddaf 100644 --- a/src/java.management/share/classes/com/sun/jmx/remote/security/JMXPluggableAuthenticator.java +++ b/src/java.management/share/classes/com/sun/jmx/remote/security/JMXPluggableAuthenticator.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2022, 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,11 +26,8 @@ package com.sun.jmx.remote.security; import java.io.IOException; -import java.security.AccessController; import java.security.Principal; import java.security.PrivilegedAction; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -105,32 +102,10 @@ public JMXPluggableAuthenticator(Map env) { } else { // use the default JAAS login configuration (file-based) - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPermission( - new AuthPermission("createLoginContext." + - LOGIN_CONFIG_NAME)); - } - - final String pf = passwordFile; - final String hashPass = hashPasswords; - try { - @SuppressWarnings("removal") - var tmp = AccessController.doPrivileged( - new PrivilegedExceptionAction() { - public LoginContext run() throws LoginException { - return new LoginContext( - LOGIN_CONFIG_NAME, + loginContext = new LoginContext(LOGIN_CONFIG_NAME, null, new JMXCallbackHandler(), - new FileLoginConfig(pf, hashPass)); - } - }); - loginContext = tmp; - } catch (PrivilegedActionException pae) { - throw (LoginException) pae.getException(); - } + new FileLoginConfig(passwordFile, hashPasswords)); } } catch (LoginException | SecurityException e) { @@ -190,14 +165,7 @@ public Subject authenticate(Object credentials) { try { loginContext.login(); final Subject subject = loginContext.getSubject(); - @SuppressWarnings("removal") - var dummy = AccessController.doPrivileged(new PrivilegedAction() { - public Void run() { - subject.setReadOnly(); - return null; - } - }); - + subject.setReadOnly(); return subject; } catch (LoginException le) { diff --git a/src/java.management/share/classes/com/sun/jmx/remote/security/JMXSubjectDomainCombiner.java b/src/java.management/share/classes/com/sun/jmx/remote/security/JMXSubjectDomainCombiner.java deleted file mode 100644 index a8f97fad1e4..00000000000 --- a/src/java.management/share/classes/com/sun/jmx/remote/security/JMXSubjectDomainCombiner.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (c) 2003, 2021, 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 com.sun.jmx.remote.security; - -import java.security.AccessControlContext; -import java.security.AccessController; -import java.security.CodeSource; -import java.security.Permissions; -import java.security.ProtectionDomain; -import javax.security.auth.Subject; -import javax.security.auth.SubjectDomainCombiner; - -/** - *

This class represents an extension to the {@link SubjectDomainCombiner} - * and is used to add a new {@link ProtectionDomain}, comprised of a null - * codesource/signers and an empty permission set, to the access control - * context with which this combiner is combined.

- * - *

When the {@link #combine} method is called the {@link ProtectionDomain} - * is augmented with the permissions granted to the set of principals present - * in the supplied {@link Subject}.

- */ -@SuppressWarnings("removal") -public class JMXSubjectDomainCombiner extends SubjectDomainCombiner { - - public JMXSubjectDomainCombiner(Subject s) { - super(s); - } - - public ProtectionDomain[] combine(ProtectionDomain[] current, - ProtectionDomain[] assigned) { - // Add a new ProtectionDomain with the null codesource/signers, and - // the empty permission set, to the end of the array containing the - // 'current' protections domains, i.e. the ones that will be augmented - // with the permissions granted to the set of principals present in - // the supplied subject. - // - ProtectionDomain[] newCurrent; - if (current == null || current.length == 0) { - newCurrent = new ProtectionDomain[1]; - newCurrent[0] = pdNoPerms; - } else { - newCurrent = new ProtectionDomain[current.length + 1]; - for (int i = 0; i < current.length; i++) { - newCurrent[i] = current[i]; - } - newCurrent[current.length] = pdNoPerms; - } - return super.combine(newCurrent, assigned); - } - - /** - * A null CodeSource. - */ - private static final CodeSource nullCodeSource = - new CodeSource(null, (java.security.cert.Certificate[]) null); - - /** - * A ProtectionDomain with a null CodeSource and an empty permission set. - */ - private static final ProtectionDomain pdNoPerms = - new ProtectionDomain(nullCodeSource, new Permissions(), null, null); - - /** - * Get the current AccessControlContext combined with the supplied subject. - */ - public static AccessControlContext getContext(Subject subject) { - return new AccessControlContext(AccessController.getContext(), - new JMXSubjectDomainCombiner(subject)); - } - - /** - * Get the AccessControlContext of the domain combiner created with - * the supplied subject, i.e. an AccessControlContext with the domain - * combiner created with the supplied subject and where the caller's - * context has been removed. - */ - public static AccessControlContext - getDomainCombinerContext(Subject subject) { - return new AccessControlContext( - new AccessControlContext(new ProtectionDomain[0]), - new JMXSubjectDomainCombiner(subject)); - } -} diff --git a/src/java.management/share/classes/com/sun/jmx/remote/security/MBeanServerAccessController.java b/src/java.management/share/classes/com/sun/jmx/remote/security/MBeanServerAccessController.java index c94750e99ff..7fd7fcb2dd2 100644 --- a/src/java.management/share/classes/com/sun/jmx/remote/security/MBeanServerAccessController.java +++ b/src/java.management/share/classes/com/sun/jmx/remote/security/MBeanServerAccessController.java @@ -25,9 +25,7 @@ package com.sun.jmx.remote.security; -import com.sun.jmx.mbeanserver.GetPropertyAction; import java.io.ObjectInputStream; -import java.security.AccessController; import java.util.Set; import javax.management.Attribute; import javax.management.AttributeList; @@ -74,13 +72,8 @@ * be overridden, for instance if the default checking behavior is * inappropriate.

* - *

If there is no SecurityManager, then the access controller will refuse - * to create an MBean that is a ClassLoader. This prevents - * people from opening security holes unintentionally. Otherwise, it - * would not be obvious that granting write access grants the ability to - * download and execute arbitrary code in the target MBean server. Advanced - * users who do want an MBean which is a ClassLoader are presumably advanced enough - * to handle policy files and security managers.

+ *

The access controller will refuse to create an MBean that is a ClassLoader. + *

*/ public abstract class MBeanServerAccessController implements MBeanServerForwarder { @@ -174,15 +167,9 @@ public ObjectInstance createMBean(String className, ObjectName name) MBeanException, NotCompliantMBeanException { checkCreate(className); - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm == null) { - Object object = getMBeanServer().instantiate(className); - checkClassLoader(object); - return getMBeanServer().registerMBean(object, name); - } else { - return getMBeanServer().createMBean(className, name); - } + Object object = getMBeanServer().instantiate(className); + checkClassLoader(object); + return getMBeanServer().registerMBean(object, name); } /** @@ -198,18 +185,11 @@ public ObjectInstance createMBean(String className, ObjectName name, MBeanException, NotCompliantMBeanException { checkCreate(className); - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm == null) { - Object object = getMBeanServer().instantiate(className, - params, - signature); - checkClassLoader(object); - return getMBeanServer().registerMBean(object, name); - } else { - return getMBeanServer().createMBean(className, name, - params, signature); - } + Object object = getMBeanServer().instantiate(className, + params, + signature); + checkClassLoader(object); + return getMBeanServer().registerMBean(object, name); } /** @@ -227,16 +207,10 @@ public ObjectInstance createMBean(String className, NotCompliantMBeanException, InstanceNotFoundException { checkCreate(className); - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm == null) { - Object object = getMBeanServer().instantiate(className, - loaderName); - checkClassLoader(object); - return getMBeanServer().registerMBean(object, name); - } else { - return getMBeanServer().createMBean(className, name, loaderName); - } + Object object = getMBeanServer().instantiate(className, + loaderName); + checkClassLoader(object); + return getMBeanServer().registerMBean(object, name); } /** @@ -256,19 +230,12 @@ public ObjectInstance createMBean(String className, NotCompliantMBeanException, InstanceNotFoundException { checkCreate(className); - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm == null) { - Object object = getMBeanServer().instantiate(className, - loaderName, - params, - signature); - checkClassLoader(object); - return getMBeanServer().registerMBean(object, name); - } else { - return getMBeanServer().createMBean(className, name, loaderName, - params, signature); - } + Object object = getMBeanServer().instantiate(className, + loaderName, + params, + signature); + checkClassLoader(object); + return getMBeanServer().registerMBean(object, name); } /** @@ -614,8 +581,7 @@ private void checkClassLoader(Object object) { if (object instanceof ClassLoader) throw new SecurityException("Access denied! Creating an " + "MBean that is a ClassLoader " + - "is forbidden unless a security " + - "manager is installed."); + "is forbidden."); } //------------------ diff --git a/src/java.management/share/classes/com/sun/jmx/remote/util/EnvHelp.java b/src/java.management/share/classes/com/sun/jmx/remote/util/EnvHelp.java index 3dcadb56325..a64db45c22f 100644 --- a/src/java.management/share/classes/com/sun/jmx/remote/util/EnvHelp.java +++ b/src/java.management/share/classes/com/sun/jmx/remote/util/EnvHelp.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 @@ -39,14 +39,11 @@ import java.util.TreeMap; import java.util.TreeSet; -import java.security.AccessController; - import javax.management.ObjectName; import javax.management.MBeanServer; import javax.management.InstanceNotFoundException; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXConnectorServerFactory; -import com.sun.jmx.mbeanserver.GetPropertyAction; import com.sun.jmx.remote.security.NotificationAccessController; public class EnvHelp { @@ -272,13 +269,11 @@ public static int getNotifBufferSize(Map env) { // the default value re-specified in the system try { - GetPropertyAction act = new GetPropertyAction(BUFFER_SIZE_PROPERTY); - String s = AccessController.doPrivileged(act); + String s = System.getProperty(BUFFER_SIZE_PROPERTY); if (s != null) { defaultQueueSize = Integer.parseInt(s); } else { // try the old one - act = new GetPropertyAction(oldP); - s = AccessController.doPrivileged(act); + s = System.getProperty(oldP); if (s != null) { defaultQueueSize = Integer.parseInt(s); } diff --git a/src/java.management/share/classes/com/sun/jmx/remote/util/OrderClassLoaders.java b/src/java.management/share/classes/com/sun/jmx/remote/util/OrderClassLoaders.java index cc22f207c29..b2449648292 100644 --- a/src/java.management/share/classes/com/sun/jmx/remote/util/OrderClassLoaders.java +++ b/src/java.management/share/classes/com/sun/jmx/remote/util/OrderClassLoaders.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2013, 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 @@ -25,8 +25,6 @@ package com.sun.jmx.remote.util; -import sun.reflect.misc.ReflectUtil; - public class OrderClassLoaders extends ClassLoader { public OrderClassLoaders(ClassLoader cl1, ClassLoader cl2) { super(cl1); @@ -35,7 +33,6 @@ public OrderClassLoaders(ClassLoader cl1, ClassLoader cl2) { } protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { - ReflectUtil.checkPackageAccess(name); try { return super.loadClass(name, resolve); } catch (ClassNotFoundException cne) { diff --git a/src/java.management/share/classes/java/lang/management/ManagementFactory.java b/src/java.management/share/classes/java/lang/management/ManagementFactory.java index 03bbcead194..547d7da9692 100644 --- a/src/java.management/share/classes/java/lang/management/ManagementFactory.java +++ b/src/java.management/share/classes/java/lang/management/ManagementFactory.java @@ -25,24 +25,20 @@ package java.lang.management; -import java.io.FilePermission; import java.io.IOException; import javax.management.DynamicMBean; +import javax.management.MBeanRegistrationException; import javax.management.MBeanServer; import javax.management.MBeanServerConnection; import javax.management.MBeanServerFactory; -import javax.management.MBeanServerPermission; +import javax.management.NotCompliantMBeanException; import javax.management.NotificationEmitter; import javax.management.ObjectName; +import javax.management.InstanceAlreadyExistsException; import javax.management.InstanceNotFoundException; import javax.management.MalformedObjectNameException; import javax.management.StandardEmitterMBean; import javax.management.StandardMBean; -import java.security.AccessController; -import java.security.Permission; -import java.security.PrivilegedAction; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -469,13 +465,6 @@ public static List getGarbageCollectorMXBeans() { * @see javax.management.MBeanServerFactory#createMBeanServer */ public static synchronized MBeanServer getPlatformMBeanServer() { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - Permission perm = new MBeanServerPermission("createMBeanServer"); - sm.checkPermission(perm); - } - if (platformMBeanServer == null) { platformMBeanServer = MBeanServerFactory.createMBeanServer(); platformComponents() @@ -594,10 +583,7 @@ public static synchronized MBeanServer getPlatformMBeanServer() { // Only allow MXBean interfaces from the platform modules loaded by the // bootstrap or platform class loader final Class cls = mxbeanInterface; - @SuppressWarnings("removal") - ClassLoader loader = - AccessController.doPrivileged( - (PrivilegedAction) () -> cls.getClassLoader()); + ClassLoader loader = cls.getClassLoader(); if (!jdk.internal.misc.VM.isSystemDomainLoader(loader)) { throw new IllegalArgumentException(mxbeanName + " is not a platform MXBean"); @@ -882,29 +868,22 @@ private static Stream getProxyNames(PlatformComponent pc, private static final String NOTIF_EMITTER = "javax.management.NotificationEmitter"; - @SuppressWarnings("removal") private static void addMXBean(final MBeanServer mbs, String name, final Object pmo) { try { ObjectName oname = ObjectName.getInstance(name); // Make DynamicMBean out of MXBean by wrapping it with a StandardMBean - AccessController.doPrivileged((PrivilegedExceptionAction) () -> { - final DynamicMBean dmbean; - if (pmo instanceof DynamicMBean) { - dmbean = DynamicMBean.class.cast(pmo); - } else if (pmo instanceof NotificationEmitter) { - dmbean = new StandardEmitterMBean(pmo, null, true, (NotificationEmitter) pmo); - } else { - dmbean = new StandardMBean(pmo, null, true); - } - - mbs.registerMBean(dmbean, oname); - return null; - }); - } catch (MalformedObjectNameException mone) { - throw new IllegalArgumentException(mone); - } catch (PrivilegedActionException e) { - throw new RuntimeException(e.getException()); + final DynamicMBean dmbean; + if (pmo instanceof DynamicMBean) { + dmbean = DynamicMBean.class.cast(pmo); + } else if (pmo instanceof NotificationEmitter) { + dmbean = new StandardEmitterMBean(pmo, null, true, (NotificationEmitter) pmo); + } else { + dmbean = new StandardMBean(pmo, null, true); + } + mbs.registerMBean(dmbean, oname); + } catch (MalformedObjectNameException | InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e) { + throw new IllegalArgumentException(e); } } @@ -918,19 +897,11 @@ private static class PlatformMBeanFinder { static { // get all providers - @SuppressWarnings("removal") - List providers = AccessController.doPrivileged( - new PrivilegedAction<>() { - @Override - public List run() { - List all = new ArrayList<>(); - for (PlatformMBeanProvider provider : ServiceLoader.loadInstalled(PlatformMBeanProvider.class)) { - all.add(provider); - } - all.add(new DefaultPlatformMBeanProvider()); - return all; - } - }, null, new FilePermission("<>", "read")); + List providers = new ArrayList<>(); + for (PlatformMBeanProvider provider : ServiceLoader.loadInstalled(PlatformMBeanProvider.class)) { + providers.add(provider); + } + providers.add(new DefaultPlatformMBeanProvider()); // load all platform components into a map var map = new HashMap>(); @@ -1013,11 +984,8 @@ static PlatformComponent findSingleton(Class mbeanIntf) loadNativeLib(); } - @SuppressWarnings({"removal", "restricted"}) + @SuppressWarnings("restricted") private static void loadNativeLib() { - AccessController.doPrivileged((PrivilegedAction) () -> { - System.loadLibrary("management"); - return null; - }); + System.loadLibrary("management"); } } diff --git a/src/java.management/share/classes/java/lang/management/RuntimeMXBean.java b/src/java.management/share/classes/java/lang/management/RuntimeMXBean.java index 30a399ad6a1..d2aae5cda08 100644 --- a/src/java.management/share/classes/java/lang/management/RuntimeMXBean.java +++ b/src/java.management/share/classes/java/lang/management/RuntimeMXBean.java @@ -25,9 +25,6 @@ package java.lang.management; -import java.security.AccessController; -import java.security.PrivilegedAction; - /** * The management interface for the runtime system of * the Java virtual machine. @@ -76,8 +73,7 @@ public interface RuntimeMXBean extends PlatformManagedObject { */ @SuppressWarnings("removal") public default long getPid() { - return AccessController.doPrivileged((PrivilegedAction) - () -> ProcessHandle.current().pid()); + return ProcessHandle.current().pid(); } /** diff --git a/src/java.management/share/classes/javax/management/ClassAttributeValueExp.java b/src/java.management/share/classes/javax/management/ClassAttributeValueExp.java index f7c40691e39..43f3f428fab 100644 --- a/src/java.management/share/classes/javax/management/ClassAttributeValueExp.java +++ b/src/java.management/share/classes/javax/management/ClassAttributeValueExp.java @@ -25,10 +25,6 @@ package javax.management; -import java.security.AccessController; - -import com.sun.jmx.mbeanserver.GetPropertyAction; - /** * This class represents the name of the Java implementation class of * the MBean. It is used for performing queries based on the class of diff --git a/src/java.management/share/classes/javax/management/JMX.java b/src/java.management/share/classes/javax/management/JMX.java index f1dba270579..82b14c691b4 100644 --- a/src/java.management/share/classes/javax/management/JMX.java +++ b/src/java.management/share/classes/javax/management/JMX.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2013, 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 @@ -29,7 +29,6 @@ import java.lang.reflect.InvocationHandler; import java.lang.reflect.Modifier; import java.lang.reflect.Proxy; -import sun.reflect.misc.ReflectUtil; /** * Static methods from the JMX API. There are no instances of this class. diff --git a/src/java.management/share/classes/javax/management/MBeanAttributeInfo.java b/src/java.management/share/classes/javax/management/MBeanAttributeInfo.java index 6551e9ba81b..e236e511976 100644 --- a/src/java.management/share/classes/javax/management/MBeanAttributeInfo.java +++ b/src/java.management/share/classes/javax/management/MBeanAttributeInfo.java @@ -26,9 +26,7 @@ package javax.management; import java.lang.reflect.Method; -import java.security.AccessController; -import com.sun.jmx.mbeanserver.GetPropertyAction; import com.sun.jmx.mbeanserver.Introspector; import java.util.Objects; diff --git a/src/java.management/share/classes/javax/management/MBeanInfo.java b/src/java.management/share/classes/javax/management/MBeanInfo.java index cfb2e6c0ded..df54b4228e2 100644 --- a/src/java.management/share/classes/javax/management/MBeanInfo.java +++ b/src/java.management/share/classes/javax/management/MBeanInfo.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 @@ -34,8 +34,6 @@ import java.util.Arrays; import java.util.Map; import java.util.WeakHashMap; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.Objects; import static javax.management.ImmutableDescriptor.nonNullDescriptor; @@ -551,10 +549,8 @@ static boolean arrayGettersSafe(Class subclass, Class immutableClass) { Boolean safe = arrayGettersSafeMap.get(subclass); if (safe == null) { try { - ArrayGettersSafeAction action = - new ArrayGettersSafeAction(subclass, immutableClass); - safe = AccessController.doPrivileged(action); - } catch (Exception e) { // e.g. SecurityException + safe = arrayGettersSafeHelper(subclass, immutableClass); + } catch (Exception e) { /* We don't know, so we assume it isn't. */ safe = false; } @@ -564,25 +560,7 @@ static boolean arrayGettersSafe(Class subclass, Class immutableClass) { } } - /* - * The PrivilegedAction stuff is probably overkill. We can be - * pretty sure the caller does have the required privileges -- a - * JMX user that can't do reflection can't even use Standard - * MBeans! But there's probably a performance gain by not having - * to check the whole call stack. - */ - private static class ArrayGettersSafeAction - implements PrivilegedAction { - - private final Class subclass; - private final Class immutableClass; - - ArrayGettersSafeAction(Class subclass, Class immutableClass) { - this.subclass = subclass; - this.immutableClass = immutableClass; - } - - public Boolean run() { + private static boolean arrayGettersSafeHelper(Class subclass, Class immutableClass) { Method[] methods = immutableClass.getMethods(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; @@ -601,7 +579,6 @@ public Boolean run() { } } return true; - } } private static boolean isEqual(String s1, String s2) { diff --git a/src/java.management/share/classes/javax/management/MBeanServer.java b/src/java.management/share/classes/javax/management/MBeanServer.java index efecf0def02..036fea93eb7 100644 --- a/src/java.management/share/classes/javax/management/MBeanServer.java +++ b/src/java.management/share/classes/javax/management/MBeanServer.java @@ -68,13 +68,6 @@ * @since 1.5 */ -/* DELETED: - * - *
  • For the {@link #isRegistered isRegistered} method, the - * caller's permissions must imply {@link - * MBeanPermission#MBeanPermission(String,String,ObjectName,String) - * MBeanPermission(null, null, name, "isRegistered")}.

    - */ public interface MBeanServer extends MBeanServerConnection { /** diff --git a/src/java.management/share/classes/javax/management/MBeanServerFactory.java b/src/java.management/share/classes/javax/management/MBeanServerFactory.java index 21f20e23991..3030d9e2f9a 100644 --- a/src/java.management/share/classes/javax/management/MBeanServerFactory.java +++ b/src/java.management/share/classes/javax/management/MBeanServerFactory.java @@ -28,14 +28,9 @@ import com.sun.jmx.defaults.JmxProperties; import static com.sun.jmx.defaults.JmxProperties.JMX_INITIAL_BUILDER; import static com.sun.jmx.defaults.JmxProperties.MBEANSERVER_LOGGER; -import com.sun.jmx.mbeanserver.GetPropertyAction; -import java.security.AccessController; -import java.security.Permission; import java.util.ArrayList; import java.lang.System.Logger.Level; import javax.management.loading.ClassLoaderRepository; -import sun.reflect.misc.ReflectUtil; - /** *

    Provides MBean server references. There are no instances of @@ -100,38 +95,6 @@ private MBeanServerFactory() { **/ private static MBeanServerBuilder builder = null; - /** - * Provide a new {@link javax.management.MBeanServerBuilder}. - * @param builder The new MBeanServerBuilder that will be used to - * create {@link javax.management.MBeanServer}s. - * @exception IllegalArgumentException if the given builder is null. - * - * @exception SecurityException if there is a SecurityManager and - * the caller's permissions do not include or imply {@link - * MBeanServerPermission}("setMBeanServerBuilder"). - * - **/ - // public static synchronized void - // setMBeanServerBuilder(MBeanServerBuilder builder) { - // checkPermission("setMBeanServerBuilder"); - // MBeanServerFactory.builder = builder; - // } - - /** - * Get the current {@link javax.management.MBeanServerBuilder}. - * - * @return the current {@link javax.management.MBeanServerBuilder}. - * - * @exception SecurityException if there is a SecurityManager and - * the caller's permissions do not include or imply {@link - * MBeanServerPermission}("getMBeanServerBuilder"). - * - **/ - // public static synchronized MBeanServerBuilder getMBeanServerBuilder() { - // checkPermission("getMBeanServerBuilder"); - // return builder; - // } - /** * Remove internal MBeanServerFactory references to a created * MBeanServer. This allows the garbage collector to remove the @@ -146,8 +109,6 @@ private MBeanServerFactory() { * */ public static void releaseMBeanServer(MBeanServer mbeanServer) { - checkPermission("releaseMBeanServer"); - removeMBeanServer(mbeanServer); } @@ -215,8 +176,6 @@ public static MBeanServer createMBeanServer() { * MBeanServerBuilder}. */ public static MBeanServer createMBeanServer(String domain) { - checkPermission("createMBeanServer"); - final MBeanServer mBeanServer = newMBeanServer(domain); addMBeanServer(mBeanServer); return mBeanServer; @@ -290,8 +249,6 @@ public static MBeanServer newMBeanServer() { * MBeanServerBuilder}. */ public static MBeanServer newMBeanServer(String domain) { - checkPermission("newMBeanServer"); - // Get the builder. Creates a new one if necessary. // final MBeanServerBuilder mbsBuilder = getNewMBeanServerBuilder(); @@ -335,8 +292,6 @@ public static MBeanServer newMBeanServer(String domain) { public static synchronized ArrayList findMBeanServer(String agentId) { - checkPermission("findMBeanServer"); - if (agentId == null) return new ArrayList<>(mBeanServerList); @@ -379,16 +334,6 @@ private static String mBeanServerId(MBeanServer mbs) { } } - private static void checkPermission(String action) - throws SecurityException { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - Permission perm = new MBeanServerPermission(action); - sm.checkPermission(perm); - } - } - private static synchronized void addMBeanServer(MBeanServer mbs) { mBeanServerList.add(mbs); } @@ -420,7 +365,7 @@ private static Class loadBuilderClass(String builderClassName) } // No context class loader? Try with Class.forName() - return ReflectUtil.forName(builderClassName); + return Class.forName(builderClassName); } /** @@ -450,10 +395,7 @@ private static MBeanServerBuilder newBuilder(Class builderClass) { **/ private static synchronized void checkMBeanServerBuilder() { try { - GetPropertyAction act = - new GetPropertyAction(JMX_INITIAL_BUILDER); - @SuppressWarnings("removal") - String builderClassName = AccessController.doPrivileged(act); + String builderClassName = System.getProperty(JMX_INITIAL_BUILDER); try { final Class newBuilderClass; @@ -499,9 +441,6 @@ private static synchronized void checkMBeanServerBuilder() { * * @return the new current {@link javax.management.MBeanServerBuilder}. * - * @exception SecurityException if there is a SecurityManager and - * the caller's permissions do not make it possible to instantiate - * a new builder. * @exception JMRuntimeException if the builder instantiation * fails with a checked exception - * {@link java.lang.ClassNotFoundException} etc... diff --git a/src/java.management/share/classes/javax/management/Notification.java b/src/java.management/share/classes/javax/management/Notification.java index 337628aeec8..a1db858bda6 100644 --- a/src/java.management/share/classes/javax/management/Notification.java +++ b/src/java.management/share/classes/javax/management/Notification.java @@ -31,10 +31,6 @@ import java.io.ObjectStreamField; import java.util.EventObject; -import java.security.AccessController; - -import com.sun.jmx.mbeanserver.GetPropertyAction; - /** *

    The Notification class represents a notification emitted by an * MBean. It contains a reference to the source MBean: if the diff --git a/src/java.management/share/classes/javax/management/NumericValueExp.java b/src/java.management/share/classes/javax/management/NumericValueExp.java index bae84019d2e..b748bb6e629 100644 --- a/src/java.management/share/classes/javax/management/NumericValueExp.java +++ b/src/java.management/share/classes/javax/management/NumericValueExp.java @@ -25,16 +25,11 @@ package javax.management; - -import com.sun.jmx.mbeanserver.GetPropertyAction; - import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamField; -import java.security.AccessController; - /** * This class represents numbers that are arguments to relational constraints. * A NumericValueExp may be used anywhere a ValueExp is required. diff --git a/src/java.management/share/classes/javax/management/ObjectName.java b/src/java.management/share/classes/javax/management/ObjectName.java index f20750c9d8a..4bcda7f0252 100644 --- a/src/java.management/share/classes/javax/management/ObjectName.java +++ b/src/java.management/share/classes/javax/management/ObjectName.java @@ -25,14 +25,12 @@ package javax.management; -import com.sun.jmx.mbeanserver.GetPropertyAction; import com.sun.jmx.mbeanserver.Util; import java.io.IOException; import java.io.InvalidObjectException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamField; -import java.security.AccessController; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; diff --git a/src/java.management/share/classes/javax/management/StandardMBean.java b/src/java.management/share/classes/javax/management/StandardMBean.java index a410ffb3492..cf61ff5a6c6 100644 --- a/src/java.management/share/classes/javax/management/StandardMBean.java +++ b/src/java.management/share/classes/javax/management/StandardMBean.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 @@ -33,7 +33,6 @@ import com.sun.jmx.mbeanserver.StandardMBeanSupport; import com.sun.jmx.mbeanserver.Util; -import java.security.AccessController; import java.security.PrivilegedAction; import java.util.HashMap; import java.util.Map; @@ -1163,9 +1162,7 @@ static boolean immutableInfo(Class subclass) { Boolean safe = mbeanInfoSafeMap.get(subclass); if (safe == null) { try { - MBeanInfoSafeAction action = - new MBeanInfoSafeAction(subclass); - safe = AccessController.doPrivileged(action); + safe = mBeanInfoSafe(subclass); } catch (Exception e) { // e.g. SecurityException /* We don't know, so we assume it isn't. */ safe = false; @@ -1189,16 +1186,8 @@ static boolean overrides(Class subclass, Class superclass, return false; } - private static class MBeanInfoSafeAction - implements PrivilegedAction { - private final Class subclass; - - MBeanInfoSafeAction(Class subclass) { - this.subclass = subclass; - } - - public Boolean run() { + private static boolean mBeanInfoSafe(Class subclass) { // Check for "void cacheMBeanInfo(MBeanInfo)" method. // if (overrides(subclass, StandardMBean.class, @@ -1230,6 +1219,5 @@ public Boolean run() { "getNotificationInfo", (Class[]) null)) return false; return true; - } } } diff --git a/src/java.management/share/classes/javax/management/modelmbean/DescriptorSupport.java b/src/java.management/share/classes/javax/management/modelmbean/DescriptorSupport.java index bea7ad92d0c..ebf08d6f1d9 100644 --- a/src/java.management/share/classes/javax/management/modelmbean/DescriptorSupport.java +++ b/src/java.management/share/classes/javax/management/modelmbean/DescriptorSupport.java @@ -32,7 +32,6 @@ import static com.sun.jmx.defaults.JmxProperties.MODELMBEAN_LOGGER; import static com.sun.jmx.mbeanserver.Util.cast; -import com.sun.jmx.mbeanserver.GetPropertyAction; import com.sun.jmx.mbeanserver.Util; import java.io.IOException; @@ -42,7 +41,6 @@ import java.lang.reflect.Constructor; -import java.security.AccessController; import java.util.HashMap; import java.util.Iterator; import java.util.Locale; @@ -58,8 +56,6 @@ import javax.management.MBeanException; import javax.management.RuntimeOperationsException; -import sun.reflect.misc.ReflectUtil; - /** * This class represents the metadata set for a ModelMBean element. A * descriptor is part of the ModelMBeanInfo, @@ -1140,7 +1136,6 @@ private static Object parseQuotedFieldValue(String s) final Constructor constr; try { - ReflectUtil.checkPackageAccess(className); final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); final Class c = diff --git a/src/java.management/share/classes/javax/management/modelmbean/InvalidTargetObjectTypeException.java b/src/java.management/share/classes/javax/management/modelmbean/InvalidTargetObjectTypeException.java index d7d3bed055c..ca94d88c794 100644 --- a/src/java.management/share/classes/javax/management/modelmbean/InvalidTargetObjectTypeException.java +++ b/src/java.management/share/classes/javax/management/modelmbean/InvalidTargetObjectTypeException.java @@ -30,13 +30,10 @@ package javax.management.modelmbean; -import com.sun.jmx.mbeanserver.GetPropertyAction; - import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamField; -import java.security.AccessController; /** * Exception thrown when an invalid target object type is specified. diff --git a/src/java.management/share/classes/javax/management/modelmbean/ModelMBeanAttributeInfo.java b/src/java.management/share/classes/javax/management/modelmbean/ModelMBeanAttributeInfo.java index d30bd368a63..674b5ccffbd 100644 --- a/src/java.management/share/classes/javax/management/modelmbean/ModelMBeanAttributeInfo.java +++ b/src/java.management/share/classes/javax/management/modelmbean/ModelMBeanAttributeInfo.java @@ -31,14 +31,12 @@ package javax.management.modelmbean; import static com.sun.jmx.defaults.JmxProperties.MODELMBEAN_LOGGER; -import com.sun.jmx.mbeanserver.GetPropertyAction; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamField; import java.lang.reflect.Method; -import java.security.AccessController; import java.lang.System.Logger.Level; import javax.management.Descriptor; diff --git a/src/java.management/share/classes/javax/management/modelmbean/ModelMBeanConstructorInfo.java b/src/java.management/share/classes/javax/management/modelmbean/ModelMBeanConstructorInfo.java index 0b8413083ac..2374b862bf3 100644 --- a/src/java.management/share/classes/javax/management/modelmbean/ModelMBeanConstructorInfo.java +++ b/src/java.management/share/classes/javax/management/modelmbean/ModelMBeanConstructorInfo.java @@ -31,14 +31,12 @@ package javax.management.modelmbean; import static com.sun.jmx.defaults.JmxProperties.MODELMBEAN_LOGGER; -import com.sun.jmx.mbeanserver.GetPropertyAction; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamField; import java.lang.reflect.Constructor; -import java.security.AccessController; import java.lang.System.Logger.Level; import javax.management.Descriptor; diff --git a/src/java.management/share/classes/javax/management/modelmbean/ModelMBeanInfoSupport.java b/src/java.management/share/classes/javax/management/modelmbean/ModelMBeanInfoSupport.java index a209c2c7f42..a7d169041a8 100644 --- a/src/java.management/share/classes/javax/management/modelmbean/ModelMBeanInfoSupport.java +++ b/src/java.management/share/classes/javax/management/modelmbean/ModelMBeanInfoSupport.java @@ -31,13 +31,11 @@ package javax.management.modelmbean; import static com.sun.jmx.defaults.JmxProperties.MODELMBEAN_LOGGER; -import com.sun.jmx.mbeanserver.GetPropertyAction; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamField; -import java.security.AccessController; import java.lang.System.Logger.Level; import javax.management.Descriptor; diff --git a/src/java.management/share/classes/javax/management/modelmbean/ModelMBeanNotificationInfo.java b/src/java.management/share/classes/javax/management/modelmbean/ModelMBeanNotificationInfo.java index c0bce84a5d9..8870217cf60 100644 --- a/src/java.management/share/classes/javax/management/modelmbean/ModelMBeanNotificationInfo.java +++ b/src/java.management/share/classes/javax/management/modelmbean/ModelMBeanNotificationInfo.java @@ -31,13 +31,11 @@ package javax.management.modelmbean; import static com.sun.jmx.defaults.JmxProperties.MODELMBEAN_LOGGER; -import com.sun.jmx.mbeanserver.GetPropertyAction; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamField; -import java.security.AccessController; import java.lang.System.Logger.Level; import javax.management.Descriptor; diff --git a/src/java.management/share/classes/javax/management/modelmbean/ModelMBeanOperationInfo.java b/src/java.management/share/classes/javax/management/modelmbean/ModelMBeanOperationInfo.java index 4120bc2cd2d..0249d00eeb6 100644 --- a/src/java.management/share/classes/javax/management/modelmbean/ModelMBeanOperationInfo.java +++ b/src/java.management/share/classes/javax/management/modelmbean/ModelMBeanOperationInfo.java @@ -31,14 +31,12 @@ package javax.management.modelmbean; import static com.sun.jmx.defaults.JmxProperties.MODELMBEAN_LOGGER; -import com.sun.jmx.mbeanserver.GetPropertyAction; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamField; import java.lang.reflect.Method; -import java.security.AccessController; import java.lang.System.Logger.Level; import javax.management.Descriptor; diff --git a/src/java.management/share/classes/javax/management/modelmbean/RequiredModelMBean.java b/src/java.management/share/classes/javax/management/modelmbean/RequiredModelMBean.java index d213324f35c..f15a8bee2b3 100644 --- a/src/java.management/share/classes/javax/management/modelmbean/RequiredModelMBean.java +++ b/src/java.management/share/classes/javax/management/modelmbean/RequiredModelMBean.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 @@ -37,9 +37,6 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -import java.security.AccessControlContext; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.Date; import java.util.HashMap; @@ -78,11 +75,8 @@ import javax.management.RuntimeOperationsException; import javax.management.ServiceNotFoundException; import javax.management.loading.ClassLoaderRepository; -import jdk.internal.access.JavaSecurityAccess; -import jdk.internal.access.SharedSecrets; import sun.reflect.misc.MethodUtil; -import sun.reflect.misc.ReflectUtil; /** * This class is the implementation of a ModelMBean. An appropriate @@ -140,10 +134,6 @@ public class RequiredModelMBean private boolean registered = false; private transient MBeanServer server = null; - private static final JavaSecurityAccess javaSecurityAccess = SharedSecrets.getJavaSecurityAccess(); - @SuppressWarnings("removal") - private final AccessControlContext acc = AccessController.getContext(); - /*************************************/ /* constructors */ /*************************************/ @@ -964,32 +954,18 @@ public Object invoke(String opName, Object[] opArgs, String[] sig) } } - final Class targetClass; + Class targetClass = null; if (opClassName != null) { try { - @SuppressWarnings("removal") - AccessControlContext stack = AccessController.getContext(); - final Object obj = targetObject; - final String className = opClassName; final ClassNotFoundException[] caughtException = new ClassNotFoundException[1]; - targetClass = javaSecurityAccess.doIntersectionPrivilege(new PrivilegedAction<>() { - - @Override - public Class run() { - try { - ReflectUtil.checkPackageAccess(className); - final ClassLoader targetClassLoader = - obj.getClass().getClassLoader(); - return Class.forName(className, false, - targetClassLoader); - } catch (ClassNotFoundException e) { - caughtException[0] = e; - } - return null; - } - }, stack, acc); + final ClassLoader targetClassLoader = targetObject.getClass().getClassLoader(); + try { + targetClass = Class.forName(opClassName, false, targetClassLoader); + } catch (ClassNotFoundException e) { + caughtException[0] = e; + } if (caughtException[0] != null) { throw caughtException[0]; @@ -1039,16 +1015,10 @@ private Method resolveMethod(Class targetClass, if (sig == null) argClasses = null; else { - @SuppressWarnings("removal") - final AccessControlContext stack = AccessController.getContext(); final ReflectionException[] caughtException = new ReflectionException[1]; final ClassLoader targetClassLoader = targetClass.getClassLoader(); argClasses = new Class[sig.length]; - javaSecurityAccess.doIntersectionPrivilege(new PrivilegedAction() { - - @Override - public Void run() { for (int i = 0; i < sig.length; i++) { if (tracing) { MODELMBEAN_LOGGER.log(Level.TRACE, @@ -1057,7 +1027,6 @@ public Void run() { argClasses[i] = (Class) primitiveClassMap.get(sig[i]); if (argClasses[i] == null) { try { - ReflectUtil.checkPackageAccess(sig[i]); argClasses[i] = Class.forName(sig[i], false, targetClassLoader); } catch (ClassNotFoundException e) { @@ -1070,9 +1039,6 @@ public Void run() { } } } - return null; - } - }, stack, acc); if (caughtException[0] != null) { throw caughtException[0]; @@ -1123,31 +1089,20 @@ private Method findRMMBMethod(String opMethodName, if (targetObjectField != null) return null; final Class rmmbClass = RequiredModelMBean.class; - final Class targetClass; + Class targetClass = null; if (opClassName == null) targetClass = rmmbClass; else { - @SuppressWarnings("removal") - AccessControlContext stack = AccessController.getContext(); - final String className = opClassName; - targetClass = javaSecurityAccess.doIntersectionPrivilege(new PrivilegedAction<>() { - - @Override - public Class run() { - try { - ReflectUtil.checkPackageAccess(className); - final ClassLoader targetClassLoader = - rmmbClass.getClassLoader(); - Class clz = Class.forName(className, false, - targetClassLoader); - if (!rmmbClass.isAssignableFrom(clz)) - return null; - return clz; - } catch (ClassNotFoundException e) { - return null; - } + final ClassLoader targetClassLoader = rmmbClass.getClassLoader(); + try { + Class clz = Class.forName(opClassName, false, targetClassLoader); + if (!rmmbClass.isAssignableFrom(clz)) { + targetClass = null; + } else { + targetClass = clz; } - }, stack, acc); + } catch (ClassNotFoundException e) { + } } try { return targetClass != null ? resolveMethod(targetClass, opMethodName, sig) : null; @@ -1165,21 +1120,12 @@ private Object invokeMethod(String opName, final Method method, throws MBeanException, ReflectionException { try { final Throwable[] caughtException = new Throwable[1]; - @SuppressWarnings("removal") - AccessControlContext stack = AccessController.getContext(); - Object rslt = javaSecurityAccess.doIntersectionPrivilege(new PrivilegedAction<>() { - - @Override - public Object run() { - try { - ReflectUtil.checkPackageAccess(method.getDeclaringClass()); - return MethodUtil.invoke(method, targetObject, opArgs); - } catch (InvocationTargetException | IllegalAccessException e) { - caughtException[0] = e; - } - return null; - } - }, stack, acc); + Object rslt = null; + try { + rslt = MethodUtil.invoke(method, targetObject, opArgs); + } catch (InvocationTargetException | IllegalAccessException e) { + caughtException[0] = e; + } if (caughtException[0] != null) { if (caughtException[0] instanceof Exception) { throw (Exception)caughtException[0]; @@ -1577,24 +1523,13 @@ public Object getAttribute(String attrName) final Class respClass = response.getClass(); final Exception[] caughException = new Exception[1]; - @SuppressWarnings("removal") - AccessControlContext stack = AccessController.getContext(); - - Class c = javaSecurityAccess.doIntersectionPrivilege(new PrivilegedAction<>() { - - @Override - public Class run() { - try { - ReflectUtil.checkPackageAccess(respType); - ClassLoader cl = - respClass.getClassLoader(); - return Class.forName(respType, true, cl); - } catch (Exception e) { - caughException[0] = e; - } - return null; - } - }, stack, acc); + ClassLoader cl = respClass.getClassLoader(); + Class c = null; + try { + c = Class.forName(respType, true, cl); + } catch (Exception e) { + caughException[0] = e; + } if (caughException[0] != null) { throw caughException[0]; @@ -2660,31 +2595,20 @@ protected ClassLoaderRepository getClassLoaderRepository() { private Class loadClass(final String className) throws ClassNotFoundException { - @SuppressWarnings("removal") - AccessControlContext stack = AccessController.getContext(); final ClassNotFoundException[] caughtException = new ClassNotFoundException[1]; - Class c = javaSecurityAccess.doIntersectionPrivilege(new PrivilegedAction<>() { - - @Override - public Class run() { - try { - ReflectUtil.checkPackageAccess(className); - return Class.forName(className); - } catch (ClassNotFoundException e) { - final ClassLoaderRepository clr = - getClassLoaderRepository(); - try { - if (clr == null) throw new ClassNotFoundException(className); - return clr.loadClass(className); - } catch (ClassNotFoundException ex) { - caughtException[0] = ex; - } - } - return null; + Class c = null; + try { + c = Class.forName(className); + } catch (ClassNotFoundException e) { + final ClassLoaderRepository clr = getClassLoaderRepository(); + try { + if (clr == null) throw new ClassNotFoundException(className); + return clr.loadClass(className); + } catch (ClassNotFoundException ex) { + caughtException[0] = ex; } - }, stack, acc); - + } if (caughtException[0] != null) { throw caughtException[0]; } diff --git a/src/java.management/share/classes/javax/management/modelmbean/XMLParseException.java b/src/java.management/share/classes/javax/management/modelmbean/XMLParseException.java index daa1abf039e..7d4773a49ea 100644 --- a/src/java.management/share/classes/javax/management/modelmbean/XMLParseException.java +++ b/src/java.management/share/classes/javax/management/modelmbean/XMLParseException.java @@ -31,13 +31,10 @@ package javax.management.modelmbean; -import com.sun.jmx.mbeanserver.GetPropertyAction; - import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamField; -import java.security.AccessController; /** * This exception is thrown when an XML formatted string is being parsed into ModelMBean objects diff --git a/src/java.management/share/classes/javax/management/monitor/Monitor.java b/src/java.management/share/classes/javax/management/monitor/Monitor.java index 151855c3495..6c0b73a41fe 100644 --- a/src/java.management/share/classes/javax/management/monitor/Monitor.java +++ b/src/java.management/share/classes/javax/management/monitor/Monitor.java @@ -26,13 +26,9 @@ package javax.management.monitor; import static com.sun.jmx.defaults.JmxProperties.MONITOR_LOGGER; -import com.sun.jmx.mbeanserver.GetPropertyAction; import com.sun.jmx.mbeanserver.Introspector; import java.io.IOException; -import java.security.AccessControlContext; -import java.security.AccessController; import java.security.PrivilegedAction; -import java.security.ProtectionDomain; import java.util.List; import java.util.Map; import java.util.WeakHashMap; @@ -170,15 +166,9 @@ public final synchronized void setDerivedGaugeTimeStamp( new CopyOnWriteArrayList<>(); /** - * Subject and possibly AccessControlContext of the Monitor.start() caller. + * Subject of the Monitor.start() caller. */ private volatile Subject subject; - @SuppressWarnings("removal") - private static final AccessControlContext noPermissionsACC = - new AccessControlContext( - new ProtectionDomain[] {new ProtectionDomain(null, null)}); - @SuppressWarnings("removal") - private volatile AccessControlContext acc = noPermissionsACC; /** * Scheduler Service. @@ -204,9 +194,7 @@ public final synchronized void setDerivedGaugeTimeStamp( private static final int maximumPoolSize; static { final String maximumPoolSizeSysProp = "jmx.x.monitor.maximum.pool.size"; - @SuppressWarnings("removal") - final String maximumPoolSizeStr = AccessController.doPrivileged( - new GetPropertyAction(maximumPoolSizeSysProp)); + final String maximumPoolSizeStr = System.getProperty(maximumPoolSizeSysProp); if (maximumPoolSizeStr == null || maximumPoolSizeStr.trim().length() == 0) { maximumPoolSize = 10; @@ -749,10 +737,9 @@ void doStop() { // cleanupFutures(); - // Reset the Subject and AccessControlContext. + // Reset the Subject. // subject = null; - acc = noPermissionsACC; // Reset the complex type attribute information // such that it is recalculated again. @@ -1469,14 +1456,10 @@ private class MonitorTask implements Runnable { public MonitorTask() { // Find out if there's already an existing executor for the calling // thread and reuse it. Otherwise, create a new one and store it in - // the executors map. If there is a SecurityManager, the group of - // System.getSecurityManager() is used, else the group of the thread + // the executors map. Use the Thread group of the thread // instantiating this MonitorTask, i.e. the group of the thread that // calls "Monitor.start()". - @SuppressWarnings("removal") - SecurityManager s = System.getSecurityManager(); - ThreadGroup group = (s != null) ? s.getThreadGroup() : - Thread.currentThread().getThreadGroup(); + ThreadGroup group = Thread.currentThread().getThreadGroup(); synchronized (executorsLock) { for (ThreadPoolExecutor e : executors.keySet()) { DaemonThreadFactory tf = @@ -1556,8 +1539,7 @@ public Void run() { * Daemon thread factory used by the monitor executors. *

    * This factory creates all new threads used by an Executor in - * the same ThreadGroup. If there is a SecurityManager, it uses - * the group of System.getSecurityManager(), else the group of + * the same ThreadGroup. Use the Thread group of * the thread instantiating this DaemonThreadFactory. Each new * thread is created as a daemon thread with priority * Thread.NORM_PRIORITY. New threads have names accessible via @@ -1572,10 +1554,7 @@ private static class DaemonThreadFactory implements ThreadFactory { static final String nameSuffix = "]"; public DaemonThreadFactory(String poolName) { - @SuppressWarnings("removal") - SecurityManager s = System.getSecurityManager(); - group = (s != null) ? s.getThreadGroup() : - Thread.currentThread().getThreadGroup(); + group = Thread.currentThread().getThreadGroup(); namePrefix = "JMX Monitor " + poolName + " Pool [Thread-"; } diff --git a/src/java.management/share/classes/javax/management/openmbean/OpenMBeanAttributeInfoSupport.java b/src/java.management/share/classes/javax/management/openmbean/OpenMBeanAttributeInfoSupport.java index c8a6ca2f07a..4f26719d4f3 100644 --- a/src/java.management/share/classes/javax/management/openmbean/OpenMBeanAttributeInfoSupport.java +++ b/src/java.management/share/classes/javax/management/openmbean/OpenMBeanAttributeInfoSupport.java @@ -43,7 +43,6 @@ import javax.management.ImmutableDescriptor; import javax.management.MBeanAttributeInfo; import sun.reflect.misc.MethodUtil; -import sun.reflect.misc.ReflectUtil; /** * Describes an attribute of an open MBean. @@ -693,7 +692,6 @@ private static T convertFromString(String s, OpenType openType) { Class c; try { String className = openType.safeGetClassName(); - ReflectUtil.checkPackageAccess(className); c = cast(Class.forName(className)); } catch (ClassNotFoundException e) { throw new NoClassDefFoundError(e.toString()); // can't happen @@ -702,8 +700,6 @@ private static T convertFromString(String s, OpenType openType) { // Look for: public static T valueOf(String) Method valueOf; try { - // It is safe to call this plain Class.getMethod because the class "c" - // was checked before by ReflectUtil.checkPackageAccess(openType.safeGetClassName()); valueOf = c.getMethod("valueOf", String.class); if (!Modifier.isStatic(valueOf.getModifiers()) || valueOf.getReturnType() != c) @@ -724,8 +720,6 @@ private static T convertFromString(String s, OpenType openType) { // Look for: public T(String) Constructor con; try { - // It is safe to call this plain Class.getConstructor because the class "c" - // was checked before by ReflectUtil.checkPackageAccess(openType.safeGetClassName()); con = c.getConstructor(String.class); } catch (NoSuchMethodException e) { con = null; @@ -764,9 +758,6 @@ private static T convertFromStringArray(Object x, try { String baseClassName = baseType.safeGetClassName(); - // check access to the provided base type class name and bail out early - ReflectUtil.checkPackageAccess(baseClassName); - stringArrayClass = Class.forName(squareBrackets + "Ljava.lang.String;"); targetArrayClass = diff --git a/src/java.management/share/classes/javax/management/openmbean/OpenType.java b/src/java.management/share/classes/javax/management/openmbean/OpenType.java index f2a004dab82..a81359a7fe9 100644 --- a/src/java.management/share/classes/javax/management/openmbean/OpenType.java +++ b/src/java.management/share/classes/javax/management/openmbean/OpenType.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 @@ -25,13 +25,10 @@ package javax.management.openmbean; -import com.sun.jmx.mbeanserver.GetPropertyAction; import java.io.IOException; import java.io.InvalidObjectException; import java.io.ObjectInputStream; import java.io.Serializable; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.Arrays; import java.util.Collections; import java.util.List; @@ -193,14 +190,11 @@ protected OpenType(String className, this.isArray = isArray; } - @SuppressWarnings("removal") private void checkClassNameOverride() throws SecurityException { if (this.getClass().getClassLoader() == null) return; // We trust bootstrap classes. if (overridesGetClassName(this.getClass())) { - final GetPropertyAction getExtendOpenTypes = - new GetPropertyAction("jmx.extend.open.types"); - if (AccessController.doPrivileged(getExtendOpenTypes) == null) { + if (System.getProperty("jmx.extend.open.types") == null) { throw new SecurityException("Cannot override getClassName() " + "unless -Djmx.extend.open.types"); } @@ -209,16 +203,11 @@ private void checkClassNameOverride() throws SecurityException { @SuppressWarnings("removal") private static boolean overridesGetClassName(final Class c) { - return AccessController.doPrivileged(new PrivilegedAction<>() { - public Boolean run() { - try { - return (c.getMethod("getClassName").getDeclaringClass() != - OpenType.class); - } catch (Exception e) { - return true; // fail safe - } - } - }); + try { + return (c.getMethod("getClassName").getDeclaringClass() != OpenType.class); + } catch (Exception e) { + return true; // fail safe + } } private static String validClassName(String className) throws OpenDataException { diff --git a/src/java.management/share/classes/javax/management/openmbean/TabularDataSupport.java b/src/java.management/share/classes/javax/management/openmbean/TabularDataSupport.java index 00f255f394b..94c804d9029 100644 --- a/src/java.management/share/classes/javax/management/openmbean/TabularDataSupport.java +++ b/src/java.management/share/classes/javax/management/openmbean/TabularDataSupport.java @@ -26,12 +26,10 @@ package javax.management.openmbean; -import com.sun.jmx.mbeanserver.GetPropertyAction; import com.sun.jmx.mbeanserver.Util; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; -import java.security.AccessController; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -148,10 +146,7 @@ public TabularDataSupport(TabularType tabularType, int initialCapacity, float lo // Since LinkedHashMap was introduced in SE 1.4, it's conceivable even // if very unlikely that we might be the server of a 1.3 client. In // that case you'll need to set this property. See CR 6334663. - @SuppressWarnings("removal") - String useHashMapProp = AccessController.doPrivileged( - new GetPropertyAction("jmx.tabular.data.hash.map")); - boolean useHashMap = "true".equalsIgnoreCase(useHashMapProp); + boolean useHashMap = Boolean.getBoolean("jmx.tabular.data.hash.map"); // Construct the empty contents HashMap // diff --git a/src/java.management/share/classes/javax/management/relation/MBeanServerNotificationFilter.java b/src/java.management/share/classes/javax/management/relation/MBeanServerNotificationFilter.java index 7579e416e36..077fce5786e 100644 --- a/src/java.management/share/classes/javax/management/relation/MBeanServerNotificationFilter.java +++ b/src/java.management/share/classes/javax/management/relation/MBeanServerNotificationFilter.java @@ -27,13 +27,11 @@ import static com.sun.jmx.mbeanserver.Util.cast; import static com.sun.jmx.defaults.JmxProperties.RELATION_LOGGER; -import com.sun.jmx.mbeanserver.GetPropertyAction; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamField; -import java.security.AccessController; import java.util.List; import java.util.Vector; diff --git a/src/java.management/share/classes/javax/management/relation/RelationNotification.java b/src/java.management/share/classes/javax/management/relation/RelationNotification.java index 16d660bc07f..d1849795eb7 100644 --- a/src/java.management/share/classes/javax/management/relation/RelationNotification.java +++ b/src/java.management/share/classes/javax/management/relation/RelationNotification.java @@ -34,8 +34,6 @@ import java.io.ObjectOutputStream; import java.io.ObjectStreamField; -import java.security.AccessController; - import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -43,7 +41,6 @@ import java.util.List; import java.util.Set; -import com.sun.jmx.mbeanserver.GetPropertyAction; import static com.sun.jmx.mbeanserver.Util.cast; /** diff --git a/src/java.management/share/classes/javax/management/relation/RelationTypeSupport.java b/src/java.management/share/classes/javax/management/relation/RelationTypeSupport.java index 766c42ca780..e4b221b1d68 100644 --- a/src/java.management/share/classes/javax/management/relation/RelationTypeSupport.java +++ b/src/java.management/share/classes/javax/management/relation/RelationTypeSupport.java @@ -27,15 +27,12 @@ import static com.sun.jmx.defaults.JmxProperties.RELATION_LOGGER; import static com.sun.jmx.mbeanserver.Util.cast; -import com.sun.jmx.mbeanserver.GetPropertyAction; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamField; -import java.security.AccessController; - import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; diff --git a/src/java.management/share/classes/javax/management/relation/Role.java b/src/java.management/share/classes/javax/management/relation/Role.java index 431092a3b48..7fd90f69b7d 100644 --- a/src/java.management/share/classes/javax/management/relation/Role.java +++ b/src/java.management/share/classes/javax/management/relation/Role.java @@ -26,7 +26,6 @@ package javax.management.relation; import static com.sun.jmx.mbeanserver.Util.cast; -import com.sun.jmx.mbeanserver.GetPropertyAction; import java.io.IOException; import java.io.ObjectInputStream; @@ -34,8 +33,6 @@ import java.io.ObjectStreamField; import java.io.Serializable; -import java.security.AccessController; - import java.util.ArrayList; import java.util.Iterator; import java.util.List; diff --git a/src/java.management/share/classes/javax/management/relation/RoleInfo.java b/src/java.management/share/classes/javax/management/relation/RoleInfo.java index 6f2926005e9..9c75cda273f 100644 --- a/src/java.management/share/classes/javax/management/relation/RoleInfo.java +++ b/src/java.management/share/classes/javax/management/relation/RoleInfo.java @@ -25,15 +25,11 @@ package javax.management.relation; - -import com.sun.jmx.mbeanserver.GetPropertyAction; - import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamField; import java.io.Serializable; -import java.security.AccessController; import javax.management.MBeanServer; diff --git a/src/java.management/share/classes/javax/management/relation/RoleResult.java b/src/java.management/share/classes/javax/management/relation/RoleResult.java index 7f98a7f7a24..c372f47cd77 100644 --- a/src/java.management/share/classes/javax/management/relation/RoleResult.java +++ b/src/java.management/share/classes/javax/management/relation/RoleResult.java @@ -25,17 +25,12 @@ package javax.management.relation; - -import com.sun.jmx.mbeanserver.GetPropertyAction; - import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamField; import java.io.Serializable; -import java.security.AccessController; - /** * Represents the result of a multiple access to several roles of a relation * (either for reading or writing). diff --git a/src/java.management/share/classes/javax/management/relation/RoleUnresolved.java b/src/java.management/share/classes/javax/management/relation/RoleUnresolved.java index 36b6dff9d71..435f68011c2 100644 --- a/src/java.management/share/classes/javax/management/relation/RoleUnresolved.java +++ b/src/java.management/share/classes/javax/management/relation/RoleUnresolved.java @@ -26,7 +26,6 @@ package javax.management.relation; import static com.sun.jmx.mbeanserver.Util.cast; -import com.sun.jmx.mbeanserver.GetPropertyAction; import java.io.IOException; import java.io.ObjectInputStream; @@ -34,8 +33,6 @@ import java.io.ObjectStreamField; import java.io.Serializable; -import java.security.AccessController; - import java.util.ArrayList; import java.util.Iterator; import java.util.List; diff --git a/src/java.management/share/classes/javax/management/remote/JMXConnectorFactory.java b/src/java.management/share/classes/javax/management/remote/JMXConnectorFactory.java index e5c0907a7b4..459a00f88cf 100644 --- a/src/java.management/share/classes/javax/management/remote/JMXConnectorFactory.java +++ b/src/java.management/share/classes/javax/management/remote/JMXConnectorFactory.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 @@ -37,13 +37,9 @@ import java.util.StringTokenizer; import java.util.function.Predicate; import java.util.stream.Stream; -import java.security.AccessController; -import java.security.PrivilegedAction; import com.sun.jmx.remote.util.ClassLogger; import com.sun.jmx.remote.util.EnvHelp; -import sun.reflect.misc.ReflectUtil; - /** *

    Factory to create JMX API connector clients. There @@ -388,12 +384,7 @@ private static String resolvePkgs(Map env) pkgsObject = env.get(PROTOCOL_PROVIDER_PACKAGES); if (pkgsObject == null) - pkgsObject = - AccessController.doPrivileged(new PrivilegedAction() { - public String run() { - return System.getProperty(PROTOCOL_PROVIDER_PACKAGES); - } - }); + pkgsObject = System.getProperty(PROTOCOL_PROVIDER_PACKAGES); if (pkgsObject == null) return null; @@ -447,20 +438,12 @@ static T getProvider(JMXServiceURL serviceURL, return instance; } - @SuppressWarnings("removal") private static ClassLoader wrap(final ClassLoader parent) { - return parent != null ? AccessController.doPrivileged(new PrivilegedAction<>() { - @Override - public ClassLoader run() { - return new ClassLoader(parent) { - @Override - protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { - ReflectUtil.checkPackageAccess(name); - return super.loadClass(name, resolve); - } - }; - } - }) : null; + return parent != null ? new ClassLoader(parent) { + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException + { return super.loadClass(name, resolve); } + } + : null; } /** diff --git a/src/java.management/share/classes/sun/management/ClassLoadingImpl.java b/src/java.management/share/classes/sun/management/ClassLoadingImpl.java index 9c3c62158b7..855b3e97575 100644 --- a/src/java.management/share/classes/sun/management/ClassLoadingImpl.java +++ b/src/java.management/share/classes/sun/management/ClassLoadingImpl.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 @@ -64,8 +64,6 @@ public boolean isVerbose() { } public void setVerbose(boolean value) { - Util.checkControlAccess(); - setVerboseClass(value); } static native void setVerboseClass(boolean value); diff --git a/src/java.management/share/classes/sun/management/ManagementFactoryHelper.java b/src/java.management/share/classes/sun/management/ManagementFactoryHelper.java index 3746cd311b2..a0291045654 100644 --- a/src/java.management/share/classes/sun/management/ManagementFactoryHelper.java +++ b/src/java.management/share/classes/sun/management/ManagementFactoryHelper.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 @@ -36,9 +36,6 @@ import javax.management.NotCompliantMBeanException; import javax.management.ObjectName; import javax.management.RuntimeOperationsException; -import java.security.AccessController; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; import jdk.internal.misc.VM; import jdk.internal.misc.VM.BufferPool; @@ -47,7 +44,6 @@ import java.util.List; import java.lang.reflect.UndeclaredThrowableException; -import java.security.PrivilegedAction; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; @@ -191,18 +187,13 @@ static boolean isAvailable() { return LOG_MANAGER_CLASS != null; } - @SuppressWarnings("removal") private static Class loadLoggingClass(String className) { - return AccessController.doPrivileged(new PrivilegedAction<>() { - @Override - public Class run() { - Optional logging = ModuleLayer.boot().findModule("java.logging"); - if (logging.isPresent()) { - return Class.forName(logging.get(), className); - } - return null; - } - }); + Optional logging = ModuleLayer.boot().findModule("java.logging"); + if (logging.isPresent()) { + return Class.forName(logging.get(), className); + } else { + return null; + } } private Map initMethodMap(Object impl) { @@ -460,29 +451,15 @@ public static synchronized HotspotCompilationMBean getHotspotCompilationMBean() * Registers a given MBean if not registered in the MBeanServer; * otherwise, just return. */ - @SuppressWarnings("removal") private static void addMBean(MBeanServer mbs, Object mbean, String mbeanName) { + final ObjectName objName = Util.newObjectName(mbeanName); + try { - final ObjectName objName = Util.newObjectName(mbeanName); - - // inner class requires these fields to be final - final MBeanServer mbs0 = mbs; - final Object mbean0 = mbean; - AccessController.doPrivileged(new PrivilegedExceptionAction() { - public Void run() throws MBeanRegistrationException, - NotCompliantMBeanException { - try { - mbs0.registerMBean(mbean0, objName); - return null; - } catch (InstanceAlreadyExistsException e) { - // if an instance with the object name exists in - // the MBeanServer ignore the exception - } - return null; - } - }); - } catch (PrivilegedActionException e) { - throw new RuntimeException(e.getException()); + mbs.registerMBean(mbean, objName); + } catch (InstanceAlreadyExistsException iaee) { + // if an instance with the object name exists in the MBeanServer, ignore the exception + } catch (Exception e) { + throw new RuntimeException(e); } } @@ -521,26 +498,15 @@ static void registerInternalMBeans(MBeanServer mbs) { } } - @SuppressWarnings("removal") private static void unregisterMBean(MBeanServer mbs, String mbeanName) { + final ObjectName objName = Util.newObjectName(mbeanName); + try { - final ObjectName objName = Util.newObjectName(mbeanName); - - // inner class requires these fields to be final - final MBeanServer mbs0 = mbs; - AccessController.doPrivileged(new PrivilegedExceptionAction() { - public Void run() throws MBeanRegistrationException, - RuntimeOperationsException { - try { - mbs0.unregisterMBean(objName); - } catch (InstanceNotFoundException e) { - // ignore exception if not found - } - return null; - } - }); - } catch (PrivilegedActionException e) { - throw new RuntimeException(e.getException()); + mbs.unregisterMBean(objName); + } catch (InstanceNotFoundException infe) { + // ignore exception if not found + } catch (Exception e) { + throw new RuntimeException(e); } } diff --git a/src/java.management/share/classes/sun/management/MappedMXBeanType.java b/src/java.management/share/classes/sun/management/MappedMXBeanType.java index 25ae6321b31..3e83ea35545 100644 --- a/src/java.management/share/classes/sun/management/MappedMXBeanType.java +++ b/src/java.management/share/classes/sun/management/MappedMXBeanType.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2022, 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 @@ -35,10 +35,6 @@ import java.util.Map; import java.util.*; import java.io.InvalidObjectException; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; import javax.management.openmbean.*; import static javax.management.openmbean.SimpleType.*; @@ -610,19 +606,14 @@ static class CompositeDataMXBeanType extends MappedMXBeanType { Method fromMethod = null; Method toMethod = null; - @SuppressWarnings("removal") CompositeDataMXBeanType(Class c) throws OpenDataException { this.javaClass = c; this.mappedTypeClass = COMPOSITE_DATA_CLASS; // check if a static from method exists try { - fromMethod = AccessController.doPrivileged(new PrivilegedExceptionAction<>() { - public Method run() throws NoSuchMethodException { - return javaClass.getMethod("from", COMPOSITE_DATA_CLASS); - } - }); - } catch (PrivilegedActionException e) { + fromMethod = javaClass.getMethod("from", COMPOSITE_DATA_CLASS); + } catch (NoSuchMethodException e) { // ignore NoSuchMethodException since we allow classes // that has no from method to be embedded in another class. } @@ -637,12 +628,7 @@ public Method run() throws NoSuchMethodException { this.isCompositeData = false; // Make a CompositeData containing all the getters - final Method[] methods = - AccessController.doPrivileged(new PrivilegedAction<>() { - public Method[] run() { - return javaClass.getMethods(); - } - }); + final Method[] methods = javaClass.getMethods(); final List names = new ArrayList<>(); final List> types = new ArrayList<>(); diff --git a/src/java.management/share/classes/sun/management/MemoryImpl.java b/src/java.management/share/classes/sun/management/MemoryImpl.java index 5bdbe7b6349..e1f68ce3711 100644 --- a/src/java.management/share/classes/sun/management/MemoryImpl.java +++ b/src/java.management/share/classes/sun/management/MemoryImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2008, 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 @@ -81,8 +81,6 @@ public boolean isVerbose() { } public void setVerbose(boolean value) { - Util.checkControlAccess(); - setVerboseGC(value); } diff --git a/src/java.management/share/classes/sun/management/MemoryPoolImpl.java b/src/java.management/share/classes/sun/management/MemoryPoolImpl.java index 3b8197bb8f1..defcecf7b21 100644 --- a/src/java.management/share/classes/sun/management/MemoryPoolImpl.java +++ b/src/java.management/share/classes/sun/management/MemoryPoolImpl.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 @@ -112,8 +112,6 @@ public void setUsageThreshold(long newThreshold) { "Usage threshold is not supported"); } - Util.checkControlAccess(); - MemoryUsage usage = getUsage0(); if (newThreshold < 0) { throw new IllegalArgumentException( @@ -157,8 +155,6 @@ public String[] getMemoryManagerNames() { } public void resetPeakUsage() { - Util.checkControlAccess(); - synchronized (this) { // synchronized since getPeakUsage may be called concurrently resetPeakUsage0(); @@ -209,8 +205,6 @@ public void setCollectionUsageThreshold(long newThreshold) { "CollectionUsage threshold is not supported"); } - Util.checkControlAccess(); - MemoryUsage usage = getUsage0(); if (newThreshold < 0) { throw new IllegalArgumentException( diff --git a/src/java.management/share/classes/sun/management/RuntimeImpl.java b/src/java.management/share/classes/sun/management/RuntimeImpl.java index c919c0eeddf..a7550650f94 100644 --- a/src/java.management/share/classes/sun/management/RuntimeImpl.java +++ b/src/java.management/share/classes/sun/management/RuntimeImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2013, 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 @@ -101,7 +101,6 @@ public String getBootClassPath() { } public List getInputArguments() { - Util.checkMonitorAccess(); return jvm.getVmArguments(); } diff --git a/src/java.management/share/classes/sun/management/ThreadImpl.java b/src/java.management/share/classes/sun/management/ThreadImpl.java index 1f37b2da567..be54ced066d 100644 --- a/src/java.management/share/classes/sun/management/ThreadImpl.java +++ b/src/java.management/share/classes/sun/management/ThreadImpl.java @@ -129,7 +129,6 @@ protected boolean isThreadAllocatedMemoryEnabled() { @Override public long[] getAllThreadIds() { - Util.checkMonitorAccess(); Thread[] threads = getThreads(); return threadIds(threads); } @@ -178,8 +177,6 @@ public ThreadInfo[] getThreadInfo(long[] ids, int maxDepth) { // an empty array of ids should return an empty array of ThreadInfos if (ids.length == 0) return new ThreadInfo[0]; - Util.checkMonitorAccess(); - ThreadInfo[] infos = new ThreadInfo[ids.length]; // nulls if (maxDepth == Integer.MAX_VALUE) { getThreadInfo1(ids, -1, infos); @@ -196,8 +193,6 @@ public void setThreadContentionMonitoringEnabled(boolean enable) { "Thread contention monitoring is not supported"); } - Util.checkControlAccess(); - synchronized (this) { if (contentionMonitoringEnabled != enable) { if (enable) { @@ -332,7 +327,6 @@ public void setThreadCpuTimeEnabled(boolean enable) { "Thread CPU time measurement is not supported"); } - Util.checkControlAccess(); synchronized (this) { if (cpuTimeEnabled != enable) { // notify VM of the state change @@ -401,7 +395,6 @@ protected long[] getThreadAllocatedBytes(long[] ids) { protected void setThreadAllocatedMemoryEnabled(boolean enable) { ensureThreadAllocatedMemorySupported(); - Util.checkControlAccess(); synchronized (this) { if (allocatedMemoryEnabled != enable) { // notify VM of the state change @@ -426,7 +419,6 @@ private long[] threadsToIds(Thread[] threads) { @Override public long[] findMonitorDeadlockedThreads() { - Util.checkMonitorAccess(); Thread[] threads = findMonitorDeadlockedThreads0(); return threadsToIds(threads); } @@ -438,15 +430,12 @@ public long[] findDeadlockedThreads() { "Monitoring of Synchronizer Usage is not supported."); } - Util.checkMonitorAccess(); - Thread[] threads = findDeadlockedThreads0(); return threadsToIds(threads); } @Override public void resetPeakThreadCount() { - Util.checkControlAccess(); resetPeakThreadCount0(); } @@ -471,8 +460,6 @@ private void verifyDumpThreads(boolean lockedMonitors, throw new UnsupportedOperationException( "Monitoring of Synchronizer Usage is not supported."); } - - Util.checkMonitorAccess(); } @Override diff --git a/src/java.management/share/classes/sun/management/Util.java b/src/java.management/share/classes/sun/management/Util.java index e5a25792263..cad5a2e3892 100644 --- a/src/java.management/share/classes/sun/management/Util.java +++ b/src/java.management/share/classes/sun/management/Util.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 @@ -50,34 +50,15 @@ public static ObjectName newObjectName(String name) { } } - private static ManagementPermission monitorPermission = - new ManagementPermission("monitor"); - private static ManagementPermission controlPermission = - new ManagementPermission("control"); - - /** - * Check that the current context is trusted to perform monitoring - * or management. - *

    - * If the check fails we throw a SecurityException, otherwise - * we return normally. - * - * @exception SecurityException if a security manager exists and if - * the caller does not have ManagementPermission("control"). - */ - static void checkAccess(ManagementPermission p) - throws SecurityException { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPermission(p); - } + // Methods retained temporarily due to usage by jdk.management. + static void checkAccess(ManagementPermission p) { + // no-op } static void checkMonitorAccess() throws SecurityException { - checkAccess(monitorPermission); + // no-op } public static void checkControlAccess() throws SecurityException { - checkAccess(controlPermission); + // no-op } } diff --git a/src/java.management/share/classes/sun/management/VMManagementImpl.java b/src/java.management/share/classes/sun/management/VMManagementImpl.java index 7e1e870acb4..041f09547d2 100644 --- a/src/java.management/share/classes/sun/management/VMManagementImpl.java +++ b/src/java.management/share/classes/sun/management/VMManagementImpl.java @@ -200,7 +200,7 @@ public synchronized List getVmArguments() { public native int getAvailableProcessors(); // Compilation Subsystem - public String getCompilerName() { + public String getCompilerName() { return System.getProperty("sun.management.compiler"); } public native long getTotalCompileTime(); From 6c1ed0bb6912d8085b98f50b7bdbb467369f3992 Mon Sep 17 00:00:00 2001 From: Aggelos Biboudis Date: Wed, 4 Dec 2024 14:32:47 +0000 Subject: [PATCH 12/43] 8345474: Translation for instanceof is not triggered when patterns are not used in the compilation unit Reviewed-by: mcimadamore --- .../sun/tools/javac/main/JavaCompiler.java | 8 +++ .../tools/javac/patterns/T8345474.java | 49 +++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 test/langtools/tools/javac/patterns/T8345474.java diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/main/JavaCompiler.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/main/JavaCompiler.java index 9600e4f6e4f..274ac029b92 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/main/JavaCompiler.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/main/JavaCompiler.java @@ -97,6 +97,7 @@ import static com.sun.tools.javac.code.TypeTag.CLASS; import static com.sun.tools.javac.main.Option.*; import com.sun.tools.javac.tree.JCTree.JCBindingPattern; +import com.sun.tools.javac.tree.JCTree.JCInstanceOf; import static com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag.*; import static javax.tools.StandardLocation.CLASS_OUTPUT; @@ -1550,6 +1551,13 @@ public void visitBindingPattern(JCBindingPattern tree) { super.visitBindingPattern(tree); } @Override + public void visitTypeTest(JCInstanceOf tree) { + if (tree.pattern.type.isPrimitive()) { + hasPatterns = true; + } + super.visitTypeTest(tree); + } + @Override public void visitRecordPattern(JCRecordPattern that) { hasPatterns = true; super.visitRecordPattern(that); diff --git a/test/langtools/tools/javac/patterns/T8345474.java b/test/langtools/tools/javac/patterns/T8345474.java new file mode 100644 index 00000000000..68a0c88a501 --- /dev/null +++ b/test/langtools/tools/javac/patterns/T8345474.java @@ -0,0 +1,49 @@ +/* + * 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 8345474 + * @summary Translation for instanceof is not triggered when patterns are not used in the compilation unit + * @enablePreview + * @compile T8345474.java + * @run main T8345474 + */ +import java.util.List; + +public class T8345474 { + public static void main(String[] args) { + erasureInstanceofTypeComparisonOperator(); + } + + public static void erasureInstanceofTypeComparisonOperator() { + List ls = List.of((short) 42); + + assertTrue(ls.get(0) instanceof int); + } + + static void assertTrue(boolean actual) { + if (!actual) { + throw new AssertionError("Expected: true, but got false"); + } + } +} From 6f307623568efe4d90942cd22ec9a26b2e1ca1b1 Mon Sep 17 00:00:00 2001 From: Prasanta Sadhukhan Date: Wed, 4 Dec 2024 15:34:11 +0000 Subject: [PATCH 13/43] 8345468: test/jdk/javax/swing/JScrollBar/4865918/bug4865918.java fails in ubuntu22.04 Reviewed-by: abhiscxk --- .../swing/JScrollBar/4865918/bug4865918.java | 50 ++++++++----------- 1 file changed, 20 insertions(+), 30 deletions(-) diff --git a/test/jdk/javax/swing/JScrollBar/4865918/bug4865918.java b/test/jdk/javax/swing/JScrollBar/4865918/bug4865918.java index eba58ef0649..ea20840d862 100644 --- a/test/jdk/javax/swing/JScrollBar/4865918/bug4865918.java +++ b/test/jdk/javax/swing/JScrollBar/4865918/bug4865918.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 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 @@ -26,14 +26,17 @@ * @key headful * @bug 4865918 * @summary REGRESSION:JCK1.4a-runtime api/javax_swing/interactive/JScrollBarTests.html#JScrollBar - * @author Andrey Pikalev * @run main bug4865918 */ -import javax.swing.*; -import java.awt.*; -import java.awt.event.*; -import java.util.*; +import java.awt.Dimension; +import java.awt.Robot; +import javax.swing.JFrame; +import javax.swing.JScrollBar; +import javax.swing.SwingUtilities; +import java.awt.event.MouseEvent; + +import java.util.Date; public class bug4865918 { @@ -43,29 +46,18 @@ public class bug4865918 { public static void main(String[] argv) throws Exception { try { Robot robot = new Robot(); - SwingUtilities.invokeAndWait(new Runnable() { - - public void run() { - createAndShowGUI(); - } - }); + SwingUtilities.invokeAndWait(() -> createAndShowGUI()); robot.waitForIdle(); + robot.delay(1000); - SwingUtilities.invokeAndWait(new Runnable() { - - @Override - public void run() { - sbar.pressMouse(); - } - }); + SwingUtilities.invokeAndWait(() -> sbar.pressMouse()); robot.waitForIdle(); + robot.delay(200); - int value = getValue(); - - if (value != 9) { - throw new Error("The scrollbar block increment is incorect"); + if (getValue() != 9) { + throw new RuntimeException("The scrollbar block increment is incorrect"); } } finally { if (frame != null) SwingUtilities.invokeAndWait(() -> frame.dispose()); @@ -75,11 +67,8 @@ public void run() { private static int getValue() throws Exception { final int[] result = new int[1]; - SwingUtilities.invokeAndWait(new Runnable() { - @Override - public void run() { - result[0] = sbar.getValue(); - } + SwingUtilities.invokeAndWait(() -> { + result[0] = sbar.getValue(); }); return result[0]; @@ -95,8 +84,9 @@ private static void createAndShowGUI() { frame.getContentPane().add(sbar); frame.pack(); + frame.setLocationRelativeTo(null); frame.setVisible(true); - + frame.toFront(); } static class TestScrollBar extends JScrollBar { @@ -111,7 +101,7 @@ public void pressMouse() { MouseEvent me = new MouseEvent(sbar, MouseEvent.MOUSE_PRESSED, (new Date()).getTime(), - MouseEvent.BUTTON1_MASK, + MouseEvent.BUTTON1_DOWN_MASK, 3 * getWidth() / 4, getHeight() / 2, 1, true); processMouseEvent(me); From 923321cfb1a9c66ca0e8f843ff029fd161a19b5b Mon Sep 17 00:00:00 2001 From: Prasanta Sadhukhan Date: Wed, 4 Dec 2024 15:35:27 +0000 Subject: [PATCH 14/43] 8345447: test/jdk/javax/swing/JToolBar/4529206/bug4529206.java fails in ubuntu22.04 Reviewed-by: abhiscxk --- .../javax/swing/JToolBar/4529206/bug4529206.java | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/test/jdk/javax/swing/JToolBar/4529206/bug4529206.java b/test/jdk/javax/swing/JToolBar/4529206/bug4529206.java index ed4f062b24c..56f4a224e3b 100644 --- a/test/jdk/javax/swing/JToolBar/4529206/bug4529206.java +++ b/test/jdk/javax/swing/JToolBar/4529206/bug4529206.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 @@ -30,6 +30,7 @@ import javax.swing.JTextField; import javax.swing.JToolBar; import javax.swing.SwingUtilities; +import javax.swing.plaf.basic.BasicToolBarUI; /* * @test @@ -45,7 +46,7 @@ public class bug4529206 { static JButton jButton1; private static void test() { - frame = new JFrame(); + frame = new JFrame("bug4529206"); JPanel jPanFrame = (JPanel) frame.getContentPane(); jPanFrame.setLayout(new BorderLayout()); frame.setSize(new Dimension(200, 100)); @@ -64,7 +65,7 @@ private static void test() { } private static void makeToolbarFloat() { - javax.swing.plaf.basic.BasicToolBarUI ui = (javax.swing.plaf.basic.BasicToolBarUI) jToolBar1.getUI(); + BasicToolBarUI ui = (BasicToolBarUI) jToolBar1.getUI(); if (!ui.isFloating()) { ui.setFloatingLocation(100, 100); ui.setFloating(true, jToolBar1.getLocation()); @@ -79,16 +80,17 @@ public static void main(String[] args) throws Exception { try { SwingUtilities.invokeAndWait(() -> test()); Robot robot = new Robot(); - robot.setAutoWaitForIdle(true); + robot.waitForIdle(); robot.delay(1000); SwingUtilities.invokeAndWait(() -> makeToolbarFloat()); + robot.waitForIdle(); robot.delay(300); SwingUtilities.invokeAndWait(() -> { if (frame.isFocused()) { - throw - new RuntimeException("setFloating does not work correctly"); + throw new RuntimeException( + "setFloating does not work correctly"); } }); } finally { From 16ef6e2a187181f49b7b2d601c660bbd25ab3845 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Volkan=20Yaz=C4=B1c=C4=B1?= Date: Wed, 4 Dec 2024 15:38:17 +0000 Subject: [PATCH 15/43] 8344229: Revisit SecurityManager usage in jdk.httpserver after JEP 486 integration Reviewed-by: dfuchs --- .../httpserver/spi/HttpServerProvider.java | 48 ++--- .../sun/net/httpserver/AuthFilter.java | 8 +- .../sun/net/httpserver/HttpServerImpl.java | 9 +- .../sun/net/httpserver/HttpsServerImpl.java | 9 +- .../sun/net/httpserver/ServerConfig.java | 183 +++++++----------- .../sun/net/httpserver/ServerImpl.java | 12 +- .../simpleserver/FileServerHandler.java | 12 -- .../httpserver/simpleserver/JWebServer.java | 14 +- .../sun/net/httpserver/FileServerHandler.java | 8 +- .../HttpsParametersClientAuthTest.java | 26 +-- .../jdk/com/sun/net/httpserver/LogFilter.java | 10 +- .../com/sun/net/httpserver/SelCacheTest.java | 5 +- .../sun/net/httpserver/SimpleFileServer.java | 6 +- test/jdk/com/sun/net/httpserver/Test14.java | 7 +- test/jdk/com/sun/net/httpserver/Test2.java | 7 +- test/jdk/com/sun/net/httpserver/Test3.java | 6 +- test/jdk/com/sun/net/httpserver/Test4.java | 5 +- test/jdk/com/sun/net/httpserver/Test5.java | 5 +- test/jdk/com/sun/net/httpserver/Test6.java | 7 +- test/jdk/com/sun/net/httpserver/Test7.java | 7 +- test/jdk/com/sun/net/httpserver/Test8.java | 7 +- .../com/sun/net/httpserver/TestLogging.java | 7 +- .../com/sun/net/httpserver/bugs/B6339483.java | 7 +- .../com/sun/net/httpserver/bugs/B6341616.java | 7 +- .../com/sun/net/httpserver/bugs/B6526158.java | 7 +- .../com/sun/net/httpserver/bugs/B6526913.java | 7 +- .../com/sun/net/httpserver/bugs/B6529200.java | 6 +- .../com/sun/net/httpserver/bugs/B6744329.java | 7 +- .../simpleserver/RootDirPermissionsTest.java | 3 +- 29 files changed, 135 insertions(+), 317 deletions(-) diff --git a/src/jdk.httpserver/share/classes/com/sun/net/httpserver/spi/HttpServerProvider.java b/src/jdk.httpserver/share/classes/com/sun/net/httpserver/spi/HttpServerProvider.java index e86f1944cd3..d025e90cf87 100644 --- a/src/jdk.httpserver/share/classes/com/sun/net/httpserver/spi/HttpServerProvider.java +++ b/src/jdk.httpserver/share/classes/com/sun/net/httpserver/spi/HttpServerProvider.java @@ -31,8 +31,6 @@ import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.net.InetSocketAddress; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.Iterator; import java.util.ServiceConfigurationError; import java.util.ServiceLoader; @@ -83,12 +81,7 @@ public abstract HttpsServer createHttpsServer(InetSocketAddress addr, /** * Initializes a new instance of this class. */ - protected HttpServerProvider() { - @SuppressWarnings("removal") - SecurityManager sm = System.getSecurityManager(); - if (sm != null) - sm.checkPermission(new RuntimePermission("httpServerProvider")); - } + protected HttpServerProvider() {} private static boolean loadProviderFromProperty() { String cn = System.getProperty("com.sun.net.httpserver.HttpServerProvider"); @@ -107,8 +100,7 @@ private static boolean loadProviderFromProperty() { NoSuchMethodException | ClassNotFoundException | IllegalAccessException | - InstantiationException | - SecurityException x) { + InstantiationException x) { throw new ServiceConfigurationError(null, x); } } @@ -118,20 +110,10 @@ private static boolean loadProviderAsService() { ServiceLoader.load(HttpServerProvider.class, ClassLoader.getSystemClassLoader()) .iterator(); - for (;;) { - try { - if (!i.hasNext()) - return false; - provider = i.next(); - return true; - } catch (ServiceConfigurationError sce) { - if (sce.getCause() instanceof SecurityException) { - // Ignore the security exception, try the next provider - continue; - } - throw sce; - } - } + if (!i.hasNext()) + return false; + provider = i.next(); + return true; } /** @@ -170,22 +152,16 @@ private static boolean loadProviderAsService() { * * @return The system-wide default HttpServerProvider */ - @SuppressWarnings("removal") public static HttpServerProvider provider () { synchronized (lock) { if (provider != null) return provider; - return (HttpServerProvider)AccessController - .doPrivileged(new PrivilegedAction() { - public Object run() { - if (loadProviderFromProperty()) - return provider; - if (loadProviderAsService()) - return provider; - provider = new sun.net.httpserver.DefaultHttpServerProvider(); - return provider; - } - }); + if (loadProviderFromProperty()) + return provider; + if (loadProviderAsService()) + return provider; + provider = new sun.net.httpserver.DefaultHttpServerProvider(); + return provider; } } diff --git a/src/jdk.httpserver/share/classes/sun/net/httpserver/AuthFilter.java b/src/jdk.httpserver/share/classes/sun/net/httpserver/AuthFilter.java index d56ae8aa94d..a6f03fdc542 100644 --- a/src/jdk.httpserver/share/classes/sun/net/httpserver/AuthFilter.java +++ b/src/jdk.httpserver/share/classes/sun/net/httpserver/AuthFilter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 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,6 @@ import com.sun.net.httpserver.*; import java.io.*; -import java.nio.*; -import java.nio.channels.*; -import java.util.*; -import javax.security.auth.*; -import javax.security.auth.callback.*; -import javax.security.auth.login.*; public class AuthFilter extends Filter { diff --git a/src/jdk.httpserver/share/classes/sun/net/httpserver/HttpServerImpl.java b/src/jdk.httpserver/share/classes/sun/net/httpserver/HttpServerImpl.java index e6e0ad85759..dd09957c0c6 100644 --- a/src/jdk.httpserver/share/classes/sun/net/httpserver/HttpServerImpl.java +++ b/src/jdk.httpserver/share/classes/sun/net/httpserver/HttpServerImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 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 @@ -27,14 +27,9 @@ import java.net.*; import java.io.*; -import java.nio.*; -import java.security.*; -import java.nio.channels.*; -import java.util.*; import java.util.concurrent.*; -import javax.net.ssl.*; + import com.sun.net.httpserver.*; -import com.sun.net.httpserver.spi.*; public class HttpServerImpl extends HttpServer { diff --git a/src/jdk.httpserver/share/classes/sun/net/httpserver/HttpsServerImpl.java b/src/jdk.httpserver/share/classes/sun/net/httpserver/HttpsServerImpl.java index f6b94db7c0e..97312ec29e6 100644 --- a/src/jdk.httpserver/share/classes/sun/net/httpserver/HttpsServerImpl.java +++ b/src/jdk.httpserver/share/classes/sun/net/httpserver/HttpsServerImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 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 @@ -27,14 +27,9 @@ import java.net.*; import java.io.*; -import java.nio.*; -import java.security.*; -import java.nio.channels.*; -import java.util.*; import java.util.concurrent.*; -import javax.net.ssl.*; + import com.sun.net.httpserver.*; -import com.sun.net.httpserver.spi.*; public class HttpsServerImpl extends HttpsServer { diff --git a/src/jdk.httpserver/share/classes/sun/net/httpserver/ServerConfig.java b/src/jdk.httpserver/share/classes/sun/net/httpserver/ServerConfig.java index 9186dd4c168..3eda0eb1a48 100644 --- a/src/jdk.httpserver/share/classes/sun/net/httpserver/ServerConfig.java +++ b/src/jdk.httpserver/share/classes/sun/net/httpserver/ServerConfig.java @@ -27,14 +27,11 @@ import java.lang.System.Logger; import java.lang.System.Logger.Level; -import java.security.PrivilegedAction; /** * Parameters that users will not likely need to set * but are useful for debugging */ - -@SuppressWarnings("removal") class ServerConfig { private static final int DEFAULT_IDLE_TIMER_SCHEDULE_MILLIS = 10000 ; // 10 sec. @@ -52,94 +49,73 @@ class ServerConfig { private static final int DEFAULT_MAX_REQ_HEADER_SIZE = 380 * 1024; private static final long DEFAULT_DRAIN_AMOUNT = 64 * 1024; - private static long idleTimerScheduleMillis; - private static long idleIntervalMillis; + private static final long idleTimerScheduleMillis; + private static final long idleIntervalMillis; // The maximum number of bytes to drain from an inputstream - private static long drainAmount; + private static final long drainAmount; // the maximum number of connections that the server will allow to be open // after which it will no longer "accept()" any new connections, till the // current connection count goes down due to completion of processing the requests - private static int maxConnections; - private static int maxIdleConnections; + private static final int maxConnections; + private static final int maxIdleConnections; // The maximum number of request headers allowable - private static int maxReqHeaders; + private static final int maxReqHeaders; // a maximum value for the header list size. This is the // names size + values size + 32 bytes per field line - private static int maxReqHeadersSize; + private static final int maxReqHeadersSize; // max time a request or response is allowed to take - private static long maxReqTime; - private static long maxRspTime; - private static long reqRspTimerScheduleMillis; - private static boolean debug; + private static final long maxReqTime; + private static final long maxRspTime; + private static final long reqRspTimerScheduleMillis; + private static final boolean debug; // the value of the TCP_NODELAY socket-level option - private static boolean noDelay; + private static final boolean noDelay; static { - java.security.AccessController.doPrivileged( - new PrivilegedAction() { - @Override - public Void run () { - idleIntervalMillis = Long.getLong("sun.net.httpserver.idleInterval", - DEFAULT_IDLE_INTERVAL_IN_SECS) * 1000; - if (idleIntervalMillis <= 0) { - idleIntervalMillis = DEFAULT_IDLE_INTERVAL_IN_SECS * 1000; - } - - idleTimerScheduleMillis = Long.getLong("sun.net.httpserver.clockTick", - DEFAULT_IDLE_TIMER_SCHEDULE_MILLIS); - if (idleTimerScheduleMillis <= 0) { - // ignore zero or negative value and use the default schedule - idleTimerScheduleMillis = DEFAULT_IDLE_TIMER_SCHEDULE_MILLIS; - } - - maxConnections = Integer.getInteger( - "jdk.httpserver.maxConnections", - DEFAULT_MAX_CONNECTIONS); - - maxIdleConnections = Integer.getInteger( - "sun.net.httpserver.maxIdleConnections", - DEFAULT_MAX_IDLE_CONNECTIONS); - - drainAmount = Long.getLong("sun.net.httpserver.drainAmount", - DEFAULT_DRAIN_AMOUNT); - - maxReqHeaders = Integer.getInteger( - "sun.net.httpserver.maxReqHeaders", - DEFAULT_MAX_REQ_HEADERS); - if (maxReqHeaders <= 0) { - maxReqHeaders = DEFAULT_MAX_REQ_HEADERS; - } - - // a value <= 0 means unlimited - maxReqHeadersSize = Integer.getInteger( - "sun.net.httpserver.maxReqHeaderSize", - DEFAULT_MAX_REQ_HEADER_SIZE); - if (maxReqHeadersSize <= 0) { - maxReqHeadersSize = 0; - } - - maxReqTime = Long.getLong("sun.net.httpserver.maxReqTime", - DEFAULT_MAX_REQ_TIME); - - maxRspTime = Long.getLong("sun.net.httpserver.maxRspTime", - DEFAULT_MAX_RSP_TIME); - - reqRspTimerScheduleMillis = Long.getLong("sun.net.httpserver.timerMillis", - DEFAULT_REQ_RSP_TIMER_TASK_SCHEDULE_MILLIS); - if (reqRspTimerScheduleMillis <= 0) { - // ignore any negative or zero value for this configuration and reset - // to default schedule - reqRspTimerScheduleMillis = DEFAULT_REQ_RSP_TIMER_TASK_SCHEDULE_MILLIS; - } - - debug = Boolean.getBoolean("sun.net.httpserver.debug"); - - noDelay = Boolean.getBoolean("sun.net.httpserver.nodelay"); - - return null; - } - }); + + long providedIdleIntervalMillis = + Long.getLong("sun.net.httpserver.idleInterval", DEFAULT_IDLE_INTERVAL_IN_SECS) * 1000; + idleIntervalMillis = providedIdleIntervalMillis > 0 + ? providedIdleIntervalMillis + : Math.multiplyExact(DEFAULT_IDLE_INTERVAL_IN_SECS, 1000); + + long providedIdleTimerScheduleMillis = + Long.getLong("sun.net.httpserver.clockTick", DEFAULT_IDLE_TIMER_SCHEDULE_MILLIS); + // Ignore zero or negative value and use the default schedule + idleTimerScheduleMillis = providedIdleTimerScheduleMillis > 0 + ? providedIdleTimerScheduleMillis + : DEFAULT_IDLE_TIMER_SCHEDULE_MILLIS; + + maxConnections = Integer.getInteger("jdk.httpserver.maxConnections", DEFAULT_MAX_CONNECTIONS); + + maxIdleConnections = Integer.getInteger("sun.net.httpserver.maxIdleConnections", DEFAULT_MAX_IDLE_CONNECTIONS); + + drainAmount = Long.getLong("sun.net.httpserver.drainAmount", DEFAULT_DRAIN_AMOUNT); + + int providedMaxReqHeaders = Integer.getInteger("sun.net.httpserver.maxReqHeaders", DEFAULT_MAX_REQ_HEADERS); + maxReqHeaders = providedMaxReqHeaders > 0 ? providedMaxReqHeaders : DEFAULT_MAX_REQ_HEADERS; + + // A value <= 0 means unlimited + maxReqHeadersSize = Math.max( + Integer.getInteger("sun.net.httpserver.maxReqHeaderSize", DEFAULT_MAX_REQ_HEADER_SIZE), + 0); + + maxReqTime = Long.getLong("sun.net.httpserver.maxReqTime", DEFAULT_MAX_REQ_TIME); + + maxRspTime = Long.getLong("sun.net.httpserver.maxRspTime", DEFAULT_MAX_RSP_TIME); + + long providedReqRspTimerScheduleMillis = Long.getLong( + "sun.net.httpserver.timerMillis", + DEFAULT_REQ_RSP_TIMER_TASK_SCHEDULE_MILLIS); + // Ignore any negative or zero value for this configuration and reset to default schedule + reqRspTimerScheduleMillis = providedReqRspTimerScheduleMillis > 0 + ? providedReqRspTimerScheduleMillis + : DEFAULT_REQ_RSP_TIMER_TASK_SCHEDULE_MILLIS; + + debug = Boolean.getBoolean("sun.net.httpserver.debug"); + + noDelay = Boolean.getBoolean("sun.net.httpserver.nodelay"); } @@ -148,39 +124,22 @@ static void checkLegacyProperties(final Logger logger) { // legacy properties that are no longer used // print a warning to logger if they are set. - java.security.AccessController.doPrivileged( - new PrivilegedAction() { - public Void run () { - if (System.getProperty("sun.net.httpserver.readTimeout") - !=null) - { - logger.log (Level.WARNING, - "sun.net.httpserver.readTimeout "+ - "property is no longer used. "+ - "Use sun.net.httpserver.maxReqTime instead." - ); - } - if (System.getProperty("sun.net.httpserver.writeTimeout") - !=null) - { - logger.log (Level.WARNING, - "sun.net.httpserver.writeTimeout "+ - "property is no longer used. Use "+ - "sun.net.httpserver.maxRspTime instead." - ); - } - if (System.getProperty("sun.net.httpserver.selCacheTimeout") - !=null) - { - logger.log (Level.WARNING, - "sun.net.httpserver.selCacheTimeout "+ - "property is no longer used." - ); - } - return null; - } - } - ); + if (System.getProperty("sun.net.httpserver.readTimeout") != null) { + logger.log( + Level.WARNING, + "sun.net.httpserver.readTimeout property is no longer used. " + + "Use sun.net.httpserver.maxReqTime instead."); + } + if (System.getProperty("sun.net.httpserver.writeTimeout") != null) { + logger.log( + Level.WARNING, + "sun.net.httpserver.writeTimeout property is no longer used. " + + "Use sun.net.httpserver.maxRspTime instead."); + } + if (System.getProperty("sun.net.httpserver.selCacheTimeout") != null) { + logger.log(Level.WARNING, "sun.net.httpserver.selCacheTimeout property is no longer used."); + } + } static boolean debugEnabled() { diff --git a/src/jdk.httpserver/share/classes/sun/net/httpserver/ServerImpl.java b/src/jdk.httpserver/share/classes/sun/net/httpserver/ServerImpl.java index 49377475719..cb27911c647 100644 --- a/src/jdk.httpserver/share/classes/sun/net/httpserver/ServerImpl.java +++ b/src/jdk.httpserver/share/classes/sun/net/httpserver/ServerImpl.java @@ -53,8 +53,6 @@ import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; @@ -304,16 +302,8 @@ public synchronized void removeContext (HttpContext context) throws IllegalArgum logger.log (Level.DEBUG, "context removed: " + context.getPath()); } - @SuppressWarnings("removal") public InetSocketAddress getAddress() { - return AccessController.doPrivileged( - new PrivilegedAction() { - public InetSocketAddress run() { - return - (InetSocketAddress)schan.socket() - .getLocalSocketAddress(); - } - }); + return (InetSocketAddress) schan.socket().getLocalSocketAddress(); } void addEvent (Event r) { diff --git a/src/jdk.httpserver/share/classes/sun/net/httpserver/simpleserver/FileServerHandler.java b/src/jdk.httpserver/share/classes/sun/net/httpserver/simpleserver/FileServerHandler.java index 81ddb58eecf..6e2683737e6 100644 --- a/src/jdk.httpserver/share/classes/sun/net/httpserver/simpleserver/FileServerHandler.java +++ b/src/jdk.httpserver/share/classes/sun/net/httpserver/simpleserver/FileServerHandler.java @@ -25,7 +25,6 @@ package sun.net.httpserver.simpleserver; -import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -67,12 +66,6 @@ public final class FileServerHandler implements HttpHandler { private FileServerHandler(Path root, UnaryOperator mimeTable) { root = root.normalize(); - - @SuppressWarnings("removal") - var securityManager = System.getSecurityManager(); - if (securityManager != null) - securityManager.checkRead(pathForSecurityCheck(root.toString())); - if (!Files.exists(root)) throw new IllegalArgumentException("Path does not exist: " + root); if (!root.isAbsolute()) @@ -86,11 +79,6 @@ private FileServerHandler(Path root, UnaryOperator mimeTable) { this.logger = System.getLogger("com.sun.net.httpserver"); } - private static String pathForSecurityCheck(String path) { - var separator = String.valueOf(File.separatorChar); - return path.endsWith(separator) ? (path + "-") : (path + separator + "-"); - } - private static final HttpHandler NOT_IMPLEMENTED_HANDLER = HttpHandlers.of(501, Headers.of(), ""); diff --git a/src/jdk.httpserver/share/classes/sun/net/httpserver/simpleserver/JWebServer.java b/src/jdk.httpserver/share/classes/sun/net/httpserver/simpleserver/JWebServer.java index baa35a76883..a7daa46bdff 100644 --- a/src/jdk.httpserver/share/classes/sun/net/httpserver/simpleserver/JWebServer.java +++ b/src/jdk.httpserver/share/classes/sun/net/httpserver/simpleserver/JWebServer.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 @@ -26,8 +26,6 @@ package sun.net.httpserver.simpleserver; import java.io.PrintWriter; -import java.security.AccessController; -import java.security.PrivilegedAction; import static java.nio.charset.StandardCharsets.UTF_8; @@ -84,15 +82,9 @@ private static void setMaxReqTime() { } } - @SuppressWarnings("removal") static void setMaxConnectionsIfNotSet() { - AccessController.doPrivileged((PrivilegedAction) () -> { - if (System.getProperty(SYS_PROP_MAX_CONNECTIONS) != null) { - // an explicit value has already been set, so we don't override it - return null; - } + if (System.getProperty(SYS_PROP_MAX_CONNECTIONS) == null) { System.setProperty(SYS_PROP_MAX_CONNECTIONS, DEFAULT_JWEBSERVER_MAX_CONNECTIONS); - return null; - }); + } } } diff --git a/test/jdk/com/sun/net/httpserver/FileServerHandler.java b/test/jdk/com/sun/net/httpserver/FileServerHandler.java index bff78443839..849b5fd06de 100644 --- a/test/jdk/com/sun/net/httpserver/FileServerHandler.java +++ b/test/jdk/com/sun/net/httpserver/FileServerHandler.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 @@ -21,13 +21,9 @@ * questions. */ -import java.util.*; -import java.util.concurrent.*; -import java.util.logging.*; import java.io.*; import java.net.*; -import java.security.*; -import javax.net.ssl.*; + import com.sun.net.httpserver.*; /** diff --git a/test/jdk/com/sun/net/httpserver/HttpsParametersClientAuthTest.java b/test/jdk/com/sun/net/httpserver/HttpsParametersClientAuthTest.java index 291b74f2669..dc1f573c4e4 100644 --- a/test/jdk/com/sun/net/httpserver/HttpsParametersClientAuthTest.java +++ b/test/jdk/com/sun/net/httpserver/HttpsParametersClientAuthTest.java @@ -31,9 +31,7 @@ import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.net.http.HttpResponse.BodyHandlers; -import java.security.AccessController; import java.security.KeyStore; -import java.security.PrivilegedExceptionAction; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -359,21 +357,15 @@ private static SSLContext onlyTrustStoreContext() throws Exception { } private static KeyStore loadTestKeyStore() throws Exception { - return AccessController.doPrivileged( - new PrivilegedExceptionAction() { - @Override - public KeyStore run() throws Exception { - final String testKeys = System.getProperty("test.src") - + "/" - + "../../../../../../test/lib/jdk/test/lib/net/testkeys"; - try (final FileInputStream fis = new FileInputStream(testKeys)) { - final char[] passphrase = "passphrase".toCharArray(); - final KeyStore ks = KeyStore.getInstance("PKCS12"); - ks.load(fis, passphrase); - return ks; - } - } - }); + final String testKeys = System.getProperty("test.src") + + "/" + + "../../../../../../test/lib/jdk/test/lib/net/testkeys"; + try (final FileInputStream fis = new FileInputStream(testKeys)) { + final char[] passphrase = "passphrase".toCharArray(); + final KeyStore ks = KeyStore.getInstance("PKCS12"); + ks.load(fis, passphrase); + return ks; + } } // no-op implementations of the abstract methods of HttpsParameters diff --git a/test/jdk/com/sun/net/httpserver/LogFilter.java b/test/jdk/com/sun/net/httpserver/LogFilter.java index 702db801a3f..43d93ab02c2 100644 --- a/test/jdk/com/sun/net/httpserver/LogFilter.java +++ b/test/jdk/com/sun/net/httpserver/LogFilter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 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 @@ -21,17 +21,11 @@ * questions. */ -import java.net.*; import java.util.*; import java.text.*; import java.io.*; -import java.nio.*; -import java.nio.channels.*; -import java.util.*; + import com.sun.net.httpserver.*; -import javax.security.auth.*; -import javax.security.auth.callback.*; -import javax.security.auth.login.*; class LogFilter extends Filter { diff --git a/test/jdk/com/sun/net/httpserver/SelCacheTest.java b/test/jdk/com/sun/net/httpserver/SelCacheTest.java index 644e64419e0..1ac4d21ee3e 100644 --- a/test/jdk/com/sun/net/httpserver/SelCacheTest.java +++ b/test/jdk/com/sun/net/httpserver/SelCacheTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 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,12 +36,9 @@ import jdk.test.lib.net.SimpleSSLContext; import jdk.test.lib.net.URIBuilder; -import java.util.*; import java.util.concurrent.*; import java.io.*; import java.net.*; -import java.security.*; -import java.security.cert.*; import javax.net.ssl.*; /* basic http/s connectivity test diff --git a/test/jdk/com/sun/net/httpserver/SimpleFileServer.java b/test/jdk/com/sun/net/httpserver/SimpleFileServer.java index 0d32f37bda3..bff415c0b98 100644 --- a/test/jdk/com/sun/net/httpserver/SimpleFileServer.java +++ b/test/jdk/com/sun/net/httpserver/SimpleFileServer.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 @@ -21,13 +21,11 @@ * questions. */ -import java.util.*; import java.util.concurrent.*; import java.util.logging.*; import java.io.*; import java.net.*; -import java.security.*; -import javax.net.ssl.*; + import com.sun.net.httpserver.*; /** diff --git a/test/jdk/com/sun/net/httpserver/Test14.java b/test/jdk/com/sun/net/httpserver/Test14.java index 532078e8215..9b10a87642a 100644 --- a/test/jdk/com/sun/net/httpserver/Test14.java +++ b/test/jdk/com/sun/net/httpserver/Test14.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 @@ -32,13 +32,10 @@ import com.sun.net.httpserver.*; -import java.util.*; import java.util.concurrent.*; import java.io.*; import java.net.*; -import java.security.*; -import javax.security.auth.callback.*; -import javax.net.ssl.*; + import jdk.test.lib.net.URIBuilder; /** diff --git a/test/jdk/com/sun/net/httpserver/Test2.java b/test/jdk/com/sun/net/httpserver/Test2.java index dd675c8933f..1e7710162fd 100644 --- a/test/jdk/com/sun/net/httpserver/Test2.java +++ b/test/jdk/com/sun/net/httpserver/Test2.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 @@ -32,13 +32,10 @@ import com.sun.net.httpserver.*; -import java.util.*; import java.util.concurrent.*; import java.io.*; import java.net.*; -import java.security.*; -import javax.security.auth.callback.*; -import javax.net.ssl.*; + import jdk.test.lib.net.URIBuilder; /** diff --git a/test/jdk/com/sun/net/httpserver/Test3.java b/test/jdk/com/sun/net/httpserver/Test3.java index a9dab54a388..ed5b46781fd 100644 --- a/test/jdk/com/sun/net/httpserver/Test3.java +++ b/test/jdk/com/sun/net/httpserver/Test3.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 @@ -32,14 +32,10 @@ import com.sun.net.httpserver.*; -import java.util.*; import java.util.concurrent.*; import java.util.regex.*; -import java.util.regex.Pattern.*; import java.io.*; import java.net.*; -import java.security.*; -import javax.net.ssl.*; /** * Test pipe-lining over http diff --git a/test/jdk/com/sun/net/httpserver/Test4.java b/test/jdk/com/sun/net/httpserver/Test4.java index 996614c0a4c..a3502dec22e 100644 --- a/test/jdk/com/sun/net/httpserver/Test4.java +++ b/test/jdk/com/sun/net/httpserver/Test4.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 @@ -32,13 +32,10 @@ import com.sun.net.httpserver.*; -import java.util.*; import java.util.concurrent.*; import java.util.regex.*; import java.io.*; import java.net.*; -import java.security.*; -import javax.net.ssl.*; /** * Test pipe-lining (block after read) diff --git a/test/jdk/com/sun/net/httpserver/Test5.java b/test/jdk/com/sun/net/httpserver/Test5.java index b57778a5226..68556bbb888 100644 --- a/test/jdk/com/sun/net/httpserver/Test5.java +++ b/test/jdk/com/sun/net/httpserver/Test5.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 @@ -32,13 +32,10 @@ import com.sun.net.httpserver.*; -import java.util.*; import java.util.concurrent.*; import java.util.regex.*; import java.io.*; import java.net.*; -import java.security.*; -import javax.net.ssl.*; /** * Test pipe-lining (no block) diff --git a/test/jdk/com/sun/net/httpserver/Test6.java b/test/jdk/com/sun/net/httpserver/Test6.java index cf49cead89b..b69bc57b640 100644 --- a/test/jdk/com/sun/net/httpserver/Test6.java +++ b/test/jdk/com/sun/net/httpserver/Test6.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 @@ -32,13 +32,10 @@ import com.sun.net.httpserver.*; -import java.util.*; import java.util.concurrent.*; import java.io.*; import java.net.*; -import java.security.*; -import javax.security.auth.callback.*; -import javax.net.ssl.*; + import jdk.test.lib.net.URIBuilder; /** diff --git a/test/jdk/com/sun/net/httpserver/Test7.java b/test/jdk/com/sun/net/httpserver/Test7.java index 2c204a8a60b..4b997411316 100644 --- a/test/jdk/com/sun/net/httpserver/Test7.java +++ b/test/jdk/com/sun/net/httpserver/Test7.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 @@ -32,13 +32,10 @@ import com.sun.net.httpserver.*; -import java.util.*; import java.util.concurrent.*; import java.io.*; import java.net.*; -import java.security.*; -import javax.security.auth.callback.*; -import javax.net.ssl.*; + import jdk.test.lib.net.URIBuilder; /** diff --git a/test/jdk/com/sun/net/httpserver/Test8.java b/test/jdk/com/sun/net/httpserver/Test8.java index 0dfc35e50f4..58f3dc2b3b4 100644 --- a/test/jdk/com/sun/net/httpserver/Test8.java +++ b/test/jdk/com/sun/net/httpserver/Test8.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 @@ -32,13 +32,10 @@ import com.sun.net.httpserver.*; -import java.util.*; import java.util.concurrent.*; import java.io.*; import java.net.*; -import java.security.*; -import javax.security.auth.callback.*; -import javax.net.ssl.*; + import jdk.test.lib.net.URIBuilder; /** diff --git a/test/jdk/com/sun/net/httpserver/TestLogging.java b/test/jdk/com/sun/net/httpserver/TestLogging.java index 0dd1fe00dc5..d108d2cce5d 100644 --- a/test/jdk/com/sun/net/httpserver/TestLogging.java +++ b/test/jdk/com/sun/net/httpserver/TestLogging.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 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,14 +32,11 @@ import com.sun.net.httpserver.*; -import java.util.*; import java.util.concurrent.*; import java.util.logging.*; import java.io.*; import java.net.*; -import java.security.*; -import java.security.cert.*; -import javax.net.ssl.*; + import jdk.test.lib.net.URIBuilder; public class TestLogging extends Test { diff --git a/test/jdk/com/sun/net/httpserver/bugs/B6339483.java b/test/jdk/com/sun/net/httpserver/bugs/B6339483.java index 2bfa8ad3efc..1bcf51509e0 100644 --- a/test/jdk/com/sun/net/httpserver/bugs/B6339483.java +++ b/test/jdk/com/sun/net/httpserver/bugs/B6339483.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 @@ -32,13 +32,10 @@ import com.sun.net.httpserver.*; -import java.util.*; import java.util.concurrent.*; import java.io.*; import java.net.*; -import java.security.*; -import java.security.cert.*; -import javax.net.ssl.*; + import jdk.test.lib.net.URIBuilder; public class B6339483 { diff --git a/test/jdk/com/sun/net/httpserver/bugs/B6341616.java b/test/jdk/com/sun/net/httpserver/bugs/B6341616.java index 82222faf08b..8a5cb98f298 100644 --- a/test/jdk/com/sun/net/httpserver/bugs/B6341616.java +++ b/test/jdk/com/sun/net/httpserver/bugs/B6341616.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 @@ -32,13 +32,10 @@ import com.sun.net.httpserver.*; -import java.util.*; import java.util.concurrent.*; import java.io.*; import java.net.*; -import java.security.*; -import java.security.cert.*; -import javax.net.ssl.*; + import jdk.test.lib.net.URIBuilder; public class B6341616 { diff --git a/test/jdk/com/sun/net/httpserver/bugs/B6526158.java b/test/jdk/com/sun/net/httpserver/bugs/B6526158.java index c38f12b49c3..5c25911d87a 100644 --- a/test/jdk/com/sun/net/httpserver/bugs/B6526158.java +++ b/test/jdk/com/sun/net/httpserver/bugs/B6526158.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2023, 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 @@ -32,13 +32,10 @@ import com.sun.net.httpserver.*; -import java.util.*; import java.util.concurrent.*; import java.io.*; import java.net.*; -import java.security.*; -import java.security.cert.*; -import javax.net.ssl.*; + import jdk.test.lib.net.URIBuilder; public class B6526158 { diff --git a/test/jdk/com/sun/net/httpserver/bugs/B6526913.java b/test/jdk/com/sun/net/httpserver/bugs/B6526913.java index 4fb2efd67f8..de2bd398e33 100644 --- a/test/jdk/com/sun/net/httpserver/bugs/B6526913.java +++ b/test/jdk/com/sun/net/httpserver/bugs/B6526913.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2023, 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 @@ -33,13 +33,10 @@ import com.sun.net.httpserver.*; -import java.util.*; import java.util.concurrent.*; import java.io.*; import java.net.*; -import java.security.*; -import java.security.cert.*; -import javax.net.ssl.*; + import jdk.test.lib.net.URIBuilder; public class B6526913 { diff --git a/test/jdk/com/sun/net/httpserver/bugs/B6529200.java b/test/jdk/com/sun/net/httpserver/bugs/B6529200.java index 3ce792ffcd7..774eeb93d0d 100644 --- a/test/jdk/com/sun/net/httpserver/bugs/B6529200.java +++ b/test/jdk/com/sun/net/httpserver/bugs/B6529200.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2023, 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 @@ -31,13 +31,9 @@ import com.sun.net.httpserver.*; -import java.util.*; import java.util.concurrent.*; import java.io.*; import java.net.*; -import java.security.*; -import java.security.cert.*; -import javax.net.ssl.*; public class B6529200 { diff --git a/test/jdk/com/sun/net/httpserver/bugs/B6744329.java b/test/jdk/com/sun/net/httpserver/bugs/B6744329.java index 9a782fd6c94..8a6290441ac 100644 --- a/test/jdk/com/sun/net/httpserver/bugs/B6744329.java +++ b/test/jdk/com/sun/net/httpserver/bugs/B6744329.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 @@ -32,13 +32,10 @@ import com.sun.net.httpserver.*; -import java.util.*; import java.util.concurrent.*; import java.io.*; import java.net.*; -import java.security.*; -import java.security.cert.*; -import javax.net.ssl.*; + import jdk.test.lib.net.URIBuilder; public class B6744329 { diff --git a/test/jdk/com/sun/net/httpserver/simpleserver/RootDirPermissionsTest.java b/test/jdk/com/sun/net/httpserver/simpleserver/RootDirPermissionsTest.java index 79477d23782..16a5f619c4a 100644 --- a/test/jdk/com/sun/net/httpserver/simpleserver/RootDirPermissionsTest.java +++ b/test/jdk/com/sun/net/httpserver/simpleserver/RootDirPermissionsTest.java @@ -23,7 +23,7 @@ /* * @test - * @summary Tests for FileServerHandler with SecurityManager + * @summary Tests file permission checks during the creation of a `FileServerHandler` * @library /test/lib * @build jdk.test.lib.net.URIBuilder * @run main/othervm -ea RootDirPermissionsTest true @@ -245,7 +245,6 @@ private static void testFileGET() throws Exception { } } - @SuppressWarnings("removal") private static void testCreateHandler(){ try { SimpleFileServer.createFileServer(LOOPBACK_ADDR, TEST_DIR, OutputLevel.NONE); From f3b4350e0f14d3b0c551e0d24563788f379111d6 Mon Sep 17 00:00:00 2001 From: Aleksey Shipilev Date: Wed, 4 Dec 2024 16:37:38 +0000 Subject: [PATCH 16/43] 8345219: C2: x86_64 should not go to interpreter stubs for NaNs handling Reviewed-by: epeter, kvn --- src/hotspot/share/compiler/compileBroker.cpp | 4 +- .../compiler/c2/irTests/TestFPConversion.java | 127 ++++++++++++++++++ .../compiler/lib/ir_framework/IRNode.java | 20 +++ .../bench/java/lang/DoubleBitConversion.java | 103 ++++++++++++++ .../bench/java/lang/FloatBitConversion.java | 103 ++++++++++++++ 5 files changed, 355 insertions(+), 2 deletions(-) create mode 100644 test/hotspot/jtreg/compiler/c2/irTests/TestFPConversion.java create mode 100644 test/micro/org/openjdk/bench/java/lang/DoubleBitConversion.java create mode 100644 test/micro/org/openjdk/bench/java/lang/FloatBitConversion.java diff --git a/src/hotspot/share/compiler/compileBroker.cpp b/src/hotspot/share/compiler/compileBroker.cpp index a7b0627c0a4..30956b6c793 100644 --- a/src/hotspot/share/compiler/compileBroker.cpp +++ b/src/hotspot/share/compiler/compileBroker.cpp @@ -1448,7 +1448,7 @@ nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci, // do the compilation if (method->is_native()) { if (!PreferInterpreterNativeStubs || method->is_method_handle_intrinsic()) { -#if defined(X86) && !defined(ZERO) +#if defined(IA32) && !defined(ZERO) // The following native methods: // // java.lang.Float.intBitsToFloat @@ -1470,7 +1470,7 @@ nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci, method->intrinsic_id() == vmIntrinsics::_doubleToRawLongBits))) { return nullptr; } -#endif // X86 && !ZERO +#endif // IA32 && !ZERO // To properly handle the appendix argument for out-of-line calls we are using a small trampoline that // pops off the appendix argument and jumps to the target (see gen_special_dispatch in SharedRuntime). diff --git a/test/hotspot/jtreg/compiler/c2/irTests/TestFPConversion.java b/test/hotspot/jtreg/compiler/c2/irTests/TestFPConversion.java new file mode 100644 index 00000000000..d9eb8c806d8 --- /dev/null +++ b/test/hotspot/jtreg/compiler/c2/irTests/TestFPConversion.java @@ -0,0 +1,127 @@ +/* + * Copyright Amazon.com Inc. 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 compiler.c2.irTests; + +import compiler.lib.ir_framework.*; +import jdk.test.lib.Asserts; + +/* + * @test + * @bug 8345219 + * @summary Test that code generation for FP conversion works as intended + * @library /test/lib / + * @requires os.arch != "x86" & os.arch != "i386" + * @run driver compiler.c2.irTests.TestFPConversion + */ +public class TestFPConversion { + static final double[] DOUBLES = new double[] { + Double.NEGATIVE_INFINITY, + -Double.MAX_VALUE, + -1.0, + -Double.MIN_VALUE, + -0.0, + 0.0, + Double.MIN_VALUE, + 1.0, + Double.MAX_VALUE, + Double.POSITIVE_INFINITY, + Double.NaN, + }; + + static final float[] FLOATS = new float[] { + Float.NEGATIVE_INFINITY, + -Float.MAX_VALUE, + -1.0F, + -Float.MIN_VALUE, + -0.0F, + 0.0F, + Float.MIN_VALUE, + 1.0F, + Float.MAX_VALUE, + Float.POSITIVE_INFINITY, + Float.NaN, + }; + + public static void main(String[] args) { + TestFramework.run(); + } + + @Test + @IR(counts = {IRNode.MOV_D2L, "1"}) + public long doubleToRawLongBits(double x) { + return Double.doubleToRawLongBits(x); + } + + @Test + @IR(counts = {IRNode.MOV_D2L, "1"}) + public long doubleToLongBits(double x) { + return Double.doubleToLongBits(x); + } + + @Test + @IR(counts = {IRNode.MOV_L2D, "1"}) + public double longBitsToDouble(long x) { + return Double.longBitsToDouble(x); + } + + @Test + @IR(counts = {IRNode.MOV_F2I, "1"}) + public int floatToRawIntBits(float x) { + return Float.floatToRawIntBits(x); + } + + @Test + @IR(counts = {IRNode.MOV_F2I, "1"}) + public int floatToIntBits(float x) { + return Float.floatToIntBits(x); + } + + @Test + @IR(counts = {IRNode.MOV_I2F, "1"}) + public float intBitsToFloat(int x) { + return Float.intBitsToFloat(x); + } + + @Run(test = {"doubleToRawLongBits", "doubleToLongBits", "longBitsToDouble", + "floatToRawIntBits", "floatToIntBits", "intBitsToFloat"}) + public void runTests() { + for (int i = 0; i < DOUBLES.length; i++) { + double d = DOUBLES[i]; + long l1 = doubleToRawLongBits(d); + long l2 = doubleToLongBits(d); + double d1 = longBitsToDouble(l1); + double d2 = longBitsToDouble(l2); + Asserts.assertEquals(d, d1); + Asserts.assertEquals(d, d2); + } + for (int i = 0; i < FLOATS.length; i++) { + float f = FLOATS[i]; + int i1 = floatToRawIntBits(f); + int i2 = floatToIntBits(f); + float f1 = intBitsToFloat(i1); + float f2 = intBitsToFloat(i2); + Asserts.assertEquals(f, f1); + Asserts.assertEquals(f, f2); + } + } +} diff --git a/test/hotspot/jtreg/compiler/lib/ir_framework/IRNode.java b/test/hotspot/jtreg/compiler/lib/ir_framework/IRNode.java index 1eb6251b2bb..35e10c7ae9f 100644 --- a/test/hotspot/jtreg/compiler/lib/ir_framework/IRNode.java +++ b/test/hotspot/jtreg/compiler/lib/ir_framework/IRNode.java @@ -1169,6 +1169,26 @@ public class IRNode { beforeMatchingNameRegex(MOD_L, "ModL"); } + public static final String MOV_F2I = PREFIX + "MOV_F2I" + POSTFIX; + static { + beforeMatchingNameRegex(MOV_F2I, "MoveF2I"); + } + + public static final String MOV_I2F = PREFIX + "MOV_I2F" + POSTFIX; + static { + beforeMatchingNameRegex(MOV_I2F, "MoveI2F"); + } + + public static final String MOV_D2L = PREFIX + "MOV_D2L" + POSTFIX; + static { + beforeMatchingNameRegex(MOV_D2L, "MoveD2L"); + } + + public static final String MOV_L2D = PREFIX + "MOD_L2D" + POSTFIX; + static { + beforeMatchingNameRegex(MOV_L2D, "MoveL2D"); + } + public static final String MUL = PREFIX + "MUL" + POSTFIX; static { beforeMatchingNameRegex(MUL, "Mul(I|L|F|D)"); diff --git a/test/micro/org/openjdk/bench/java/lang/DoubleBitConversion.java b/test/micro/org/openjdk/bench/java/lang/DoubleBitConversion.java new file mode 100644 index 00000000000..7ef4bf9cc75 --- /dev/null +++ b/test/micro/org/openjdk/bench/java/lang/DoubleBitConversion.java @@ -0,0 +1,103 @@ +/* + * Copyright Amazon.com Inc. 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.java.lang; + +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.Warmup; +import org.openjdk.jmh.infra.Blackhole; + +import java.util.BitSet; +import java.util.Date; +import java.util.concurrent.TimeUnit; + +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.NANOSECONDS) +@State(Scope.Thread) +@Warmup(iterations = 3, time = 1) +@Measurement(iterations = 3, time = 1) +@Fork(3) +public class DoubleBitConversion { + + double doubleZero = 0; + double doubleOne = 1; + double doubleNan = Double.NaN; + + long longDoubleZero = Double.doubleToLongBits(0); + long longDoubleOne = Double.doubleToLongBits(1); + long longDoubleNaN = Double.doubleToLongBits(Double.NaN); + + @Benchmark + public long doubleToRawLongBits_zero() { + return Double.doubleToRawLongBits(doubleZero); + } + + @Benchmark + public long doubleToRawLongBits_one() { + return Double.doubleToRawLongBits(doubleOne); + } + + @Benchmark + public long doubleToRawLongBits_NaN() { + return Double.doubleToRawLongBits(doubleNan); + } + + @Benchmark + public long doubleToLongBits_zero() { + return Double.doubleToLongBits(doubleZero); + } + + @Benchmark + public long doubleToLongBits_one() { + return Double.doubleToLongBits(doubleOne); + } + + @Benchmark + public long doubleToLongBits_NaN() { + return Double.doubleToLongBits(doubleNan); + } + + @Benchmark + public double longBitsToDouble_zero() { + return Double.longBitsToDouble(longDoubleZero); + } + + @Benchmark + public double longBitsToDouble_one() { + return Double.longBitsToDouble(longDoubleOne); + } + + @Benchmark + public double longBitsToDouble_NaN() { + return Double.longBitsToDouble(longDoubleNaN); + } + +} + diff --git a/test/micro/org/openjdk/bench/java/lang/FloatBitConversion.java b/test/micro/org/openjdk/bench/java/lang/FloatBitConversion.java new file mode 100644 index 00000000000..965e7b88cbb --- /dev/null +++ b/test/micro/org/openjdk/bench/java/lang/FloatBitConversion.java @@ -0,0 +1,103 @@ +/* + * Copyright Amazon.com Inc. 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.java.lang; + +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.Warmup; +import org.openjdk.jmh.infra.Blackhole; + +import java.util.BitSet; +import java.util.Date; +import java.util.concurrent.TimeUnit; + +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.NANOSECONDS) +@State(Scope.Thread) +@Warmup(iterations = 3, time = 1) +@Measurement(iterations = 3, time = 1) +@Fork(3) +public class FloatBitConversion { + + float floatZero = 0; + float floatOne = 1; + float floatNan = Float.NaN; + + int intFloatZero = Float.floatToIntBits(0); + int intFloatOne = Float.floatToIntBits(1); + int intFloatNaN = Float.floatToIntBits(Float.NaN); + + @Benchmark + public int floatToRawIntBits_zero() { + return Float.floatToRawIntBits(floatZero); + } + + @Benchmark + public int floatToRawIntBits_one() { + return Float.floatToRawIntBits(floatOne); + } + + @Benchmark + public int floatToRawIntBits_NaN() { + return Float.floatToRawIntBits(floatNan); + } + + @Benchmark + public int floatToIntBits_zero() { + return Float.floatToIntBits(floatZero); + } + + @Benchmark + public int floatToIntBits_one() { + return Float.floatToIntBits(floatOne); + } + + @Benchmark + public int floatToIntBits_NaN() { + return Float.floatToIntBits(floatNan); + } + + @Benchmark + public float intBitsToFloat_zero() { + return Float.intBitsToFloat(intFloatZero); + } + + @Benchmark + public float intBitsToFloat_one() { + return Float.intBitsToFloat(intFloatOne); + } + + @Benchmark + public float intBitsToFloat_NaN() { + return Float.intBitsToFloat(intFloatNaN); + } + +} + From 79eb77b782bd0c3cecee6c66b86f6f3e17054498 Mon Sep 17 00:00:00 2001 From: Chen Liang Date: Wed, 4 Dec 2024 17:30:01 +0000 Subject: [PATCH 17/43] 8345486: Reevaluate the classes in java.lang.classfile.components package Reviewed-by: mcimadamore, asotona --- make/test/BuildMicrobenchmark.gmk | 1 + .../lang/classfile/ClassFileTransform.java | 7 +- .../snippet-files/PackageSnippets.java | 84 ------------------- .../classfile/components/ClassPrinter.java | 14 +--- .../classfile/components/ClassRemapper.java | 4 +- .../components/CodeLocalsShifter.java | 4 +- .../classfile/components/CodeRelabeler.java | 4 +- .../components/CodeStackTracker.java | 4 +- .../classfile/components/package-info.java | 4 +- .../snippet-files/PackageSnippets.java | 8 +- .../classfile/impl/ClassPrinterImpl.java | 10 +-- .../classfile/impl/ClassRemapperImpl.java | 2 +- .../classfile/impl/CodeLocalsShifterImpl.java | 2 +- .../classfile/impl/CodeRelabelerImpl.java | 2 +- .../classfile/impl/CodeStackTrackerImpl.java | 2 +- .../jdk/internal/classfile/impl/Util.java | 2 +- .../classfile/impl/verifier/VerifierImpl.java | 2 +- src/java.base/share/classes/module-info.java | 3 +- .../jdk/jfr/internal/util/Bytecode.java | 2 +- .../AdvancedTransformationsTest.java | 8 +- test/jdk/jdk/classfile/ClassBuildingTest.java | 2 +- test/jdk/jdk/classfile/ClassPrinterTest.java | 2 +- test/jdk/jdk/classfile/SnippetsTest.java | 16 ++-- test/jdk/jdk/classfile/StackMapsTest.java | 2 +- test/jdk/jdk/classfile/StackTrackerTest.java | 2 +- test/jdk/jdk/classfile/TEST.properties | 1 + test/jdk/jdk/classfile/VerifierSelfTest.java | 2 +- .../examples/AnnotationsExamples.java | 2 +- .../helpers/RebuildingTransformation.java | 2 +- .../jdk/jdk/classfile/helpers/Transforms.java | 3 +- .../classfile/AbstractCorpusBenchmark.java | 1 + .../jdk/classfile/RepeatedModelTraversal.java | 3 +- .../bench/jdk/classfile/Transforms.java | 5 +- 33 files changed, 54 insertions(+), 158 deletions(-) rename src/java.base/share/classes/{java/lang => jdk/internal}/classfile/components/ClassPrinter.java (97%) rename src/java.base/share/classes/{java/lang => jdk/internal}/classfile/components/ClassRemapper.java (98%) rename src/java.base/share/classes/{java/lang => jdk/internal}/classfile/components/CodeLocalsShifter.java (97%) rename src/java.base/share/classes/{java/lang => jdk/internal}/classfile/components/CodeRelabeler.java (98%) rename src/java.base/share/classes/{java/lang => jdk/internal}/classfile/components/CodeStackTracker.java (98%) rename src/java.base/share/classes/{java/lang => jdk/internal}/classfile/components/package-info.java (98%) rename src/java.base/share/classes/{java/lang => jdk/internal}/classfile/components/snippet-files/PackageSnippets.java (97%) diff --git a/make/test/BuildMicrobenchmark.gmk b/make/test/BuildMicrobenchmark.gmk index 0a4c2d9a48d..da9ff2029e8 100644 --- a/make/test/BuildMicrobenchmark.gmk +++ b/make/test/BuildMicrobenchmark.gmk @@ -89,6 +89,7 @@ $(eval $(call SetupJavaCompilation, BUILD_JDK_MICROBENCHMARK, \ SRC := $(MICROBENCHMARK_SRC), \ BIN := $(MICROBENCHMARK_CLASSES), \ JAVAC_FLAGS := \ + --add-exports java.base/jdk.internal.classfile.components=ALL-UNNAMED \ --add-exports java.base/jdk.internal.classfile.impl=ALL-UNNAMED \ --add-exports java.base/jdk.internal.event=ALL-UNNAMED \ --add-exports java.base/jdk.internal.foreign=ALL-UNNAMED \ diff --git a/src/java.base/share/classes/java/lang/classfile/ClassFileTransform.java b/src/java.base/share/classes/java/lang/classfile/ClassFileTransform.java index 9fdafdf4331..7d9385eed68 100644 --- a/src/java.base/share/classes/java/lang/classfile/ClassFileTransform.java +++ b/src/java.base/share/classes/java/lang/classfile/ClassFileTransform.java @@ -60,12 +60,7 @@ * its state must be reset for each traversal; this will happen automatically if * the transform is created with {@link ClassTransform#ofStateful(Supplier)} (or * corresponding methods for other classfile locations.) - *

    - * Class transformation sample where code transformation is stateful: - * {@snippet lang="java" class="PackageSnippets" region="codeRelabeling"} - *

    - * Complex class instrumentation sample chaining multiple transformations: - * {@snippet lang="java" class="PackageSnippets" region="classInstrumentation"} + * * @param the transform type * @param the element type * @param the builder type diff --git a/src/java.base/share/classes/java/lang/classfile/snippet-files/PackageSnippets.java b/src/java.base/share/classes/java/lang/classfile/snippet-files/PackageSnippets.java index c6956d6d23a..7a58da7f6ce 100644 --- a/src/java.base/share/classes/java/lang/classfile/snippet-files/PackageSnippets.java +++ b/src/java.base/share/classes/java/lang/classfile/snippet-files/PackageSnippets.java @@ -25,21 +25,13 @@ package java.lang.classfile.snippets; import java.lang.classfile.*; -import java.lang.classfile.components.ClassRemapper; -import java.lang.classfile.components.CodeLocalsShifter; -import java.lang.classfile.components.CodeRelabeler; import java.lang.classfile.instruction.*; import java.lang.constant.ClassDesc; import java.lang.constant.ConstantDescs; import java.lang.constant.MethodTypeDesc; import java.lang.invoke.MethodHandles; -import java.lang.reflect.AccessFlag; -import java.util.ArrayDeque; import java.util.HashSet; -import java.util.Map; import java.util.Set; -import java.util.function.Predicate; -import java.util.stream.Collectors; import java.util.stream.Stream; import static java.util.stream.Collectors.toSet; @@ -326,82 +318,6 @@ void fooToBarUnrolled(ClassModel classModel) { // @end } - void codeRelabeling(ClassModel classModel) { - // @start region="codeRelabeling" - byte[] newBytes = ClassFile.of().transformClass(classModel, - ClassTransform.transformingMethodBodies( - CodeTransform.ofStateful(CodeRelabeler::of))); - // @end - } - - // @start region="classInstrumentation" - byte[] classInstrumentation(ClassModel target, ClassModel instrumentor, Predicate instrumentedMethodsFilter) { - var instrumentorCodeMap = instrumentor.methods().stream() - .filter(instrumentedMethodsFilter) - .collect(Collectors.toMap(mm -> mm.methodName().stringValue() + mm.methodType().stringValue(), mm -> mm.code().orElseThrow())); - var targetFieldNames = target.fields().stream().map(f -> f.fieldName().stringValue()).collect(Collectors.toSet()); - var targetMethods = target.methods().stream().map(m -> m.methodName().stringValue() + m.methodType().stringValue()).collect(Collectors.toSet()); - var instrumentorClassRemapper = ClassRemapper.of(Map.of(instrumentor.thisClass().asSymbol(), target.thisClass().asSymbol())); - return ClassFile.of().transformClass(target, - ClassTransform.transformingMethods( - instrumentedMethodsFilter, - (mb, me) -> { - if (me instanceof CodeModel targetCodeModel) { - var mm = targetCodeModel.parent().get(); - //instrumented methods code is taken from instrumentor - mb.transformCode(instrumentorCodeMap.get(mm.methodName().stringValue() + mm.methodType().stringValue()), - //all references to the instrumentor class are remapped to target class - instrumentorClassRemapper.asCodeTransform() - .andThen((codeBuilder, instrumentorCodeElement) -> { - //all invocations of target methods from instrumentor are inlined - if (instrumentorCodeElement instanceof InvokeInstruction inv - && target.thisClass().asInternalName().equals(inv.owner().asInternalName()) - && mm.methodName().stringValue().equals(inv.name().stringValue()) - && mm.methodType().stringValue().equals(inv.type().stringValue())) { - - //store stacked method parameters into locals - var storeStack = new ArrayDeque(); - int slot = 0; - if (!mm.flags().has(AccessFlag.STATIC)) - storeStack.push(StoreInstruction.of(TypeKind.REFERENCE, slot++)); - for (var pt : mm.methodTypeSymbol().parameterList()) { - var tk = TypeKind.from(pt); - storeStack.push(StoreInstruction.of(tk, slot)); - slot += tk.slotSize(); - } - storeStack.forEach(codeBuilder::with); - - //inlined target locals must be shifted based on the actual instrumentor locals - codeBuilder.block(inlinedBlockBuilder -> inlinedBlockBuilder - .transform(targetCodeModel, CodeLocalsShifter.of(mm.flags(), mm.methodTypeSymbol()) - .andThen(CodeRelabeler.of()) - .andThen((innerBuilder, shiftedTargetCode) -> { - //returns must be replaced with jump to the end of the inlined method - if (shiftedTargetCode instanceof ReturnInstruction) - innerBuilder.goto_(inlinedBlockBuilder.breakLabel()); - else - innerBuilder.with(shiftedTargetCode); - }))); - } else - codeBuilder.with(instrumentorCodeElement); - })); - } else - mb.with(me); - }) - .andThen(ClassTransform.endHandler(clb -> - //remaining instrumentor fields and methods are injected at the end - clb.transform(instrumentor, - ClassTransform.dropping(cle -> - !(cle instanceof FieldModel fm - && !targetFieldNames.contains(fm.fieldName().stringValue())) - && !(cle instanceof MethodModel mm - && !ConstantDescs.INIT_NAME.equals(mm.methodName().stringValue()) - && !targetMethods.contains(mm.methodName().stringValue() + mm.methodType().stringValue()))) - //and instrumentor class references remapped to target class - .andThen(instrumentorClassRemapper))))); - } - // @end - void resolverExample() { // @start region="lookup-class-hierarchy-resolver" MethodHandles.Lookup lookup = MethodHandles.lookup(); // @replace regex="MethodHandles\.lookup\(\)" replacement="..." diff --git a/src/java.base/share/classes/java/lang/classfile/components/ClassPrinter.java b/src/java.base/share/classes/jdk/internal/classfile/components/ClassPrinter.java similarity index 97% rename from src/java.base/share/classes/java/lang/classfile/components/ClassPrinter.java rename to src/java.base/share/classes/jdk/internal/classfile/components/ClassPrinter.java index 7237dc54580..cc5a3824936 100644 --- a/src/java.base/share/classes/java/lang/classfile/components/ClassPrinter.java +++ b/src/java.base/share/classes/jdk/internal/classfile/components/ClassPrinter.java @@ -22,7 +22,7 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ -package java.lang.classfile.components; +package jdk.internal.classfile.components; import java.lang.classfile.ClassModel; import java.lang.classfile.CodeModel; @@ -58,8 +58,6 @@ *

    * Another use case for {@link ClassPrinter} is to simplify writing of automated tests: * {@snippet lang="java" class="PackageSnippets" region="printNodesInTest"} - * - * @since 24 */ public final class ClassPrinter { @@ -68,8 +66,6 @@ private ClassPrinter() { /** * Level of detail to print or export. - * - * @since 24 */ public enum Verbosity { @@ -102,8 +98,6 @@ public enum Verbosity { /** * Named, traversable, and printable node parent. - * - * @since 24 */ public sealed interface Node { @@ -146,8 +140,6 @@ default void toYaml(Consumer out) { /** * A leaf node holding single printable value. - * - * @since 24 */ public sealed interface LeafNode extends Node permits ClassPrinterImpl.LeafNodeImpl { @@ -161,8 +153,6 @@ public sealed interface LeafNode extends Node /** * A tree node holding {@link List} of nested nodes. - * - * @since 24 */ public sealed interface ListNode extends Node, List permits ClassPrinterImpl.ListNodeImpl { @@ -172,8 +162,6 @@ public sealed interface ListNode extends Node, List * A tree node holding {@link Map} of nested nodes. *

    * Each {@link Map.Entry#getKey()} == {@link Map.Entry#getValue()}.{@link #name()}. - * - * @since 24 */ public sealed interface MapNode extends Node, Map permits ClassPrinterImpl.MapNodeImpl { diff --git a/src/java.base/share/classes/java/lang/classfile/components/ClassRemapper.java b/src/java.base/share/classes/jdk/internal/classfile/components/ClassRemapper.java similarity index 98% rename from src/java.base/share/classes/java/lang/classfile/components/ClassRemapper.java rename to src/java.base/share/classes/jdk/internal/classfile/components/ClassRemapper.java index 4a2808ad4f0..ad116cd9dc4 100644 --- a/src/java.base/share/classes/java/lang/classfile/components/ClassRemapper.java +++ b/src/java.base/share/classes/jdk/internal/classfile/components/ClassRemapper.java @@ -22,7 +22,7 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ -package java.lang.classfile.components; +package jdk.internal.classfile.components; import java.lang.classfile.ClassFile; import java.lang.classfile.ClassModel; @@ -53,8 +53,6 @@ *

    * Arrays of reference types are always decomposed, mapped as the base reference * types and composed back to arrays. - * - * @since 24 */ public sealed interface ClassRemapper extends ClassTransform permits ClassRemapperImpl { diff --git a/src/java.base/share/classes/java/lang/classfile/components/CodeLocalsShifter.java b/src/java.base/share/classes/jdk/internal/classfile/components/CodeLocalsShifter.java similarity index 97% rename from src/java.base/share/classes/java/lang/classfile/components/CodeLocalsShifter.java rename to src/java.base/share/classes/jdk/internal/classfile/components/CodeLocalsShifter.java index 9db85f54a45..f06b4694953 100644 --- a/src/java.base/share/classes/java/lang/classfile/components/CodeLocalsShifter.java +++ b/src/java.base/share/classes/jdk/internal/classfile/components/CodeLocalsShifter.java @@ -22,7 +22,7 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ -package java.lang.classfile.components; +package jdk.internal.classfile.components; import java.lang.classfile.AccessFlags; import java.lang.classfile.CodeTransform; @@ -37,8 +37,6 @@ * newly allocated positions to avoid conflicts during code injection. * Locals pointing to the receiver or to method arguments slots are never shifted. * All locals pointing beyond the method arguments are re-indexed in order of appearance. - * - * @since 24 */ public sealed interface CodeLocalsShifter extends CodeTransform permits CodeLocalsShifterImpl { diff --git a/src/java.base/share/classes/java/lang/classfile/components/CodeRelabeler.java b/src/java.base/share/classes/jdk/internal/classfile/components/CodeRelabeler.java similarity index 98% rename from src/java.base/share/classes/java/lang/classfile/components/CodeRelabeler.java rename to src/java.base/share/classes/jdk/internal/classfile/components/CodeRelabeler.java index 4ef82adfdb9..6a16b6a00dd 100644 --- a/src/java.base/share/classes/java/lang/classfile/components/CodeRelabeler.java +++ b/src/java.base/share/classes/jdk/internal/classfile/components/CodeRelabeler.java @@ -22,7 +22,7 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ -package java.lang.classfile.components; +package jdk.internal.classfile.components; import java.lang.classfile.CodeBuilder; import java.lang.classfile.CodeTransform; @@ -44,8 +44,6 @@ * Primary purpose of CodeRelabeler is for repeated injections of the same code blocks. * Repeated injection of the same code block must be relabeled, so each instance of * {@link java.lang.classfile.Label} is bound in the target bytecode exactly once. - * - * @since 24 */ public sealed interface CodeRelabeler extends CodeTransform permits CodeRelabelerImpl { diff --git a/src/java.base/share/classes/java/lang/classfile/components/CodeStackTracker.java b/src/java.base/share/classes/jdk/internal/classfile/components/CodeStackTracker.java similarity index 98% rename from src/java.base/share/classes/java/lang/classfile/components/CodeStackTracker.java rename to src/java.base/share/classes/jdk/internal/classfile/components/CodeStackTracker.java index 3761e53ff19..eb7f58702eb 100644 --- a/src/java.base/share/classes/java/lang/classfile/components/CodeStackTracker.java +++ b/src/java.base/share/classes/jdk/internal/classfile/components/CodeStackTracker.java @@ -22,7 +22,7 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ -package java.lang.classfile.components; +package jdk.internal.classfile.components; import java.lang.classfile.CodeTransform; import java.lang.classfile.Label; @@ -49,8 +49,6 @@ * int maxStack = stackTracker.maxStackSize().get(); * }); * } - * - * @since 24 */ public sealed interface CodeStackTracker extends CodeTransform permits CodeStackTrackerImpl { diff --git a/src/java.base/share/classes/java/lang/classfile/components/package-info.java b/src/java.base/share/classes/jdk/internal/classfile/components/package-info.java similarity index 98% rename from src/java.base/share/classes/java/lang/classfile/components/package-info.java rename to src/java.base/share/classes/jdk/internal/classfile/components/package-info.java index be650f4c77c..30fb5fc07e5 100644 --- a/src/java.base/share/classes/java/lang/classfile/components/package-info.java +++ b/src/java.base/share/classes/jdk/internal/classfile/components/package-info.java @@ -110,8 +110,6 @@ * CodeLocalsShifter} and {@link CodeRelabeler} into fully functional class * instrumenting transformation: * {@snippet lang="java" class="PackageSnippets" region="classInstrumentation"} - * - * @since 24 */ -package java.lang.classfile.components; +package jdk.internal.classfile.components; diff --git a/src/java.base/share/classes/java/lang/classfile/components/snippet-files/PackageSnippets.java b/src/java.base/share/classes/jdk/internal/classfile/components/snippet-files/PackageSnippets.java similarity index 97% rename from src/java.base/share/classes/java/lang/classfile/components/snippet-files/PackageSnippets.java rename to src/java.base/share/classes/jdk/internal/classfile/components/snippet-files/PackageSnippets.java index 87c2146a7ac..452e0188115 100644 --- a/src/java.base/share/classes/java/lang/classfile/components/snippet-files/PackageSnippets.java +++ b/src/java.base/share/classes/jdk/internal/classfile/components/snippet-files/PackageSnippets.java @@ -25,10 +25,10 @@ package java.lang.classfile.components.snippets; import java.lang.classfile.*; -import java.lang.classfile.components.ClassPrinter; -import java.lang.classfile.components.ClassRemapper; -import java.lang.classfile.components.CodeLocalsShifter; -import java.lang.classfile.components.CodeRelabeler; +import jdk.internal.classfile.components.ClassPrinter; +import jdk.internal.classfile.components.ClassRemapper; +import jdk.internal.classfile.components.CodeLocalsShifter; +import jdk.internal.classfile.components.CodeRelabeler; import java.lang.classfile.instruction.InvokeInstruction; import java.lang.classfile.instruction.ReturnInstruction; import java.lang.classfile.instruction.StoreInstruction; diff --git a/src/java.base/share/classes/jdk/internal/classfile/impl/ClassPrinterImpl.java b/src/java.base/share/classes/jdk/internal/classfile/impl/ClassPrinterImpl.java index 183ee323b52..8a44890fe66 100644 --- a/src/java.base/share/classes/jdk/internal/classfile/impl/ClassPrinterImpl.java +++ b/src/java.base/share/classes/jdk/internal/classfile/impl/ClassPrinterImpl.java @@ -31,11 +31,11 @@ import java.lang.classfile.attribute.StackMapFrameInfo.SimpleVerificationTypeInfo; import java.lang.classfile.attribute.StackMapFrameInfo.UninitializedVerificationTypeInfo; import java.lang.classfile.attribute.StackMapFrameInfo.VerificationTypeInfo; -import java.lang.classfile.components.ClassPrinter.LeafNode; -import java.lang.classfile.components.ClassPrinter.ListNode; -import java.lang.classfile.components.ClassPrinter.MapNode; -import java.lang.classfile.components.ClassPrinter.Node; -import java.lang.classfile.components.ClassPrinter.Verbosity; +import jdk.internal.classfile.components.ClassPrinter.LeafNode; +import jdk.internal.classfile.components.ClassPrinter.ListNode; +import jdk.internal.classfile.components.ClassPrinter.MapNode; +import jdk.internal.classfile.components.ClassPrinter.Node; +import jdk.internal.classfile.components.ClassPrinter.Verbosity; import java.lang.classfile.constantpool.*; import java.lang.classfile.instruction.*; import java.lang.constant.ConstantDesc; diff --git a/src/java.base/share/classes/jdk/internal/classfile/impl/ClassRemapperImpl.java b/src/java.base/share/classes/jdk/internal/classfile/impl/ClassRemapperImpl.java index cd9faaf2f9a..6dbde898ee5 100644 --- a/src/java.base/share/classes/jdk/internal/classfile/impl/ClassRemapperImpl.java +++ b/src/java.base/share/classes/jdk/internal/classfile/impl/ClassRemapperImpl.java @@ -26,7 +26,7 @@ import java.lang.classfile.*; import java.lang.classfile.attribute.*; -import java.lang.classfile.components.ClassRemapper; +import jdk.internal.classfile.components.ClassRemapper; import java.lang.classfile.constantpool.Utf8Entry; import java.lang.classfile.instruction.ConstantInstruction.LoadConstantInstruction; import java.lang.classfile.instruction.*; diff --git a/src/java.base/share/classes/jdk/internal/classfile/impl/CodeLocalsShifterImpl.java b/src/java.base/share/classes/jdk/internal/classfile/impl/CodeLocalsShifterImpl.java index 7b7d04a8f1d..eac66b7cb5e 100644 --- a/src/java.base/share/classes/jdk/internal/classfile/impl/CodeLocalsShifterImpl.java +++ b/src/java.base/share/classes/jdk/internal/classfile/impl/CodeLocalsShifterImpl.java @@ -28,7 +28,7 @@ import java.lang.classfile.CodeElement; import java.lang.classfile.Signature; import java.lang.classfile.TypeKind; -import java.lang.classfile.components.CodeLocalsShifter; +import jdk.internal.classfile.components.CodeLocalsShifter; import java.lang.classfile.instruction.IncrementInstruction; import java.lang.classfile.instruction.LoadInstruction; import java.lang.classfile.instruction.LocalVariable; diff --git a/src/java.base/share/classes/jdk/internal/classfile/impl/CodeRelabelerImpl.java b/src/java.base/share/classes/jdk/internal/classfile/impl/CodeRelabelerImpl.java index af0a59978d7..1e7e5262af4 100644 --- a/src/java.base/share/classes/jdk/internal/classfile/impl/CodeRelabelerImpl.java +++ b/src/java.base/share/classes/jdk/internal/classfile/impl/CodeRelabelerImpl.java @@ -27,7 +27,7 @@ import java.lang.classfile.CodeBuilder; import java.lang.classfile.CodeElement; import java.lang.classfile.Label; -import java.lang.classfile.components.CodeRelabeler; +import jdk.internal.classfile.components.CodeRelabeler; import java.lang.classfile.instruction.*; import java.util.function.BiFunction; diff --git a/src/java.base/share/classes/jdk/internal/classfile/impl/CodeStackTrackerImpl.java b/src/java.base/share/classes/jdk/internal/classfile/impl/CodeStackTrackerImpl.java index 2746caae004..5441f78518e 100644 --- a/src/java.base/share/classes/jdk/internal/classfile/impl/CodeStackTrackerImpl.java +++ b/src/java.base/share/classes/jdk/internal/classfile/impl/CodeStackTrackerImpl.java @@ -29,7 +29,7 @@ import java.lang.classfile.Label; import java.lang.classfile.Opcode; import java.lang.classfile.TypeKind; -import java.lang.classfile.components.CodeStackTracker; +import jdk.internal.classfile.components.CodeStackTracker; import java.lang.classfile.instruction.*; import java.util.*; import java.util.function.Consumer; diff --git a/src/java.base/share/classes/jdk/internal/classfile/impl/Util.java b/src/java.base/share/classes/jdk/internal/classfile/impl/Util.java index fc6099f3e5b..b0234fb88cc 100644 --- a/src/java.base/share/classes/jdk/internal/classfile/impl/Util.java +++ b/src/java.base/share/classes/jdk/internal/classfile/impl/Util.java @@ -26,7 +26,7 @@ import java.lang.classfile.*; import java.lang.classfile.attribute.CodeAttribute; -import java.lang.classfile.components.ClassPrinter; +import jdk.internal.classfile.components.ClassPrinter; import java.lang.classfile.constantpool.ClassEntry; import java.lang.classfile.constantpool.ModuleEntry; import java.lang.classfile.constantpool.PoolEntry; diff --git a/src/java.base/share/classes/jdk/internal/classfile/impl/verifier/VerifierImpl.java b/src/java.base/share/classes/jdk/internal/classfile/impl/verifier/VerifierImpl.java index ed93ff1fc5d..4c2104c5a78 100644 --- a/src/java.base/share/classes/jdk/internal/classfile/impl/verifier/VerifierImpl.java +++ b/src/java.base/share/classes/jdk/internal/classfile/impl/verifier/VerifierImpl.java @@ -26,7 +26,7 @@ import java.lang.classfile.ClassHierarchyResolver; import java.lang.classfile.ClassModel; -import java.lang.classfile.components.ClassPrinter; +import jdk.internal.classfile.components.ClassPrinter; import java.util.ArrayList; import java.util.Collections; import java.util.List; diff --git a/src/java.base/share/classes/module-info.java b/src/java.base/share/classes/module-info.java index c3bcbed4e3b..187c97a6ad3 100644 --- a/src/java.base/share/classes/module-info.java +++ b/src/java.base/share/classes/module-info.java @@ -81,7 +81,6 @@ exports java.lang.annotation; exports java.lang.classfile; exports java.lang.classfile.attribute; - exports java.lang.classfile.components; exports java.lang.classfile.constantpool; exports java.lang.classfile.instruction; exports java.lang.constant; @@ -177,6 +176,8 @@ jdk.net, jdk.sctp, jdk.crypto.cryptoki; + exports jdk.internal.classfile.components to + jdk.jfr; exports jdk.internal.foreign to jdk.incubator.vector; exports jdk.internal.event to diff --git a/src/jdk.jfr/share/classes/jdk/jfr/internal/util/Bytecode.java b/src/jdk.jfr/share/classes/jdk/jfr/internal/util/Bytecode.java index a027d756508..c51c3afe331 100644 --- a/src/jdk.jfr/share/classes/jdk/jfr/internal/util/Bytecode.java +++ b/src/jdk.jfr/share/classes/jdk/jfr/internal/util/Bytecode.java @@ -35,7 +35,7 @@ import java.lang.classfile.CodeBuilder; import java.lang.classfile.ClassModel; import java.lang.classfile.ClassFile; -import java.lang.classfile.components.ClassPrinter; +import jdk.internal.classfile.components.ClassPrinter; /** * Helper class when working with bytecode. diff --git a/test/jdk/jdk/classfile/AdvancedTransformationsTest.java b/test/jdk/jdk/classfile/AdvancedTransformationsTest.java index 450f1279810..557384e602e 100644 --- a/test/jdk/jdk/classfile/AdvancedTransformationsTest.java +++ b/test/jdk/jdk/classfile/AdvancedTransformationsTest.java @@ -37,8 +37,8 @@ import java.lang.classfile.MethodModel; import java.lang.classfile.TypeKind; import jdk.internal.classfile.impl.StackMapGenerator; -import java.lang.classfile.components.ClassRemapper; -import java.lang.classfile.components.CodeLocalsShifter; +import jdk.internal.classfile.components.ClassRemapper; +import jdk.internal.classfile.components.CodeLocalsShifter; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; import static helpers.TestUtil.assertEmpty; @@ -59,9 +59,9 @@ import java.lang.classfile.instruction.ReturnInstruction; import java.lang.classfile.instruction.StoreInstruction; import java.lang.reflect.AccessFlag; -import java.lang.classfile.components.CodeRelabeler; +import jdk.internal.classfile.components.CodeRelabeler; import java.lang.constant.ModuleDesc; -import java.lang.classfile.components.ClassPrinter; +import jdk.internal.classfile.components.ClassPrinter; import static java.lang.annotation.ElementType.*; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; diff --git a/test/jdk/jdk/classfile/ClassBuildingTest.java b/test/jdk/jdk/classfile/ClassBuildingTest.java index bf6380ae8fe..ba58f20f7d7 100644 --- a/test/jdk/jdk/classfile/ClassBuildingTest.java +++ b/test/jdk/jdk/classfile/ClassBuildingTest.java @@ -35,7 +35,7 @@ import java.lang.classfile.MethodTransform; import java.lang.classfile.attribute.MethodParametersAttribute; import java.lang.classfile.attribute.SignatureAttribute; -import java.lang.classfile.components.ClassRemapper; +import jdk.internal.classfile.components.ClassRemapper; import org.junit.jupiter.api.Test; import java.lang.constant.ClassDesc; diff --git a/test/jdk/jdk/classfile/ClassPrinterTest.java b/test/jdk/jdk/classfile/ClassPrinterTest.java index 7ea69f58889..5dc136f59c3 100644 --- a/test/jdk/jdk/classfile/ClassPrinterTest.java +++ b/test/jdk/jdk/classfile/ClassPrinterTest.java @@ -35,7 +35,7 @@ import java.util.Optional; import java.lang.classfile.*; import java.lang.classfile.attribute.*; -import java.lang.classfile.components.ClassPrinter; +import jdk.internal.classfile.components.ClassPrinter; import java.lang.constant.DirectMethodHandleDesc; import java.lang.constant.DynamicCallSiteDesc; import java.lang.constant.MethodHandleDesc; diff --git a/test/jdk/jdk/classfile/SnippetsTest.java b/test/jdk/jdk/classfile/SnippetsTest.java index 6999ef2a0ae..51a73b93d67 100644 --- a/test/jdk/jdk/classfile/SnippetsTest.java +++ b/test/jdk/jdk/classfile/SnippetsTest.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 @@ -28,6 +28,7 @@ */ import java.nio.file.Paths; +import java.util.ArrayList; import java.util.List; import javax.tools.StandardLocation; import javax.tools.ToolProvider; @@ -41,7 +42,7 @@ public class SnippetsTest { @ParameterizedTest @ValueSource(strings = { "src/java.base/share/classes/java/lang/classfile/snippet-files/PackageSnippets.java", - "src/java.base/share/classes/java/lang/classfile/components/snippet-files/PackageSnippets.java"}) + "src/java.base/share/classes/jdk/internal/classfile/components/snippet-files/PackageSnippets.java"}) void testSnippet(String source) throws Exception { var p = Paths.get(System.getProperty("test.src", ".")).toAbsolutePath(); while ((p = p.getParent()) != null) { @@ -52,9 +53,14 @@ void testSnippet(String source) throws Exception { var compilationUnits = fileManager.getJavaFileObjectsFromFiles(List.of(src)); fileManager.setLocation(StandardLocation.CLASS_OUTPUT, List.of(Paths.get(System.getProperty("test.classes", ".")).toFile())); - var task = compiler.getTask(null, fileManager, null, List.of( - "--enable-preview", - "--source", String.valueOf(Runtime.version().feature())), + List flags = List.of( + "--source", String.valueOf(Runtime.version().feature())); + if (source.contains("jdk/internal/classfile/components")) { + flags = new ArrayList<>(flags); + flags.add("--add-exports"); + flags.add("java.base/jdk.internal.classfile.components=ALL-UNNAMED"); + } + var task = compiler.getTask(null, fileManager, null, flags, null, compilationUnits); if (task.call()) return; throw new RuntimeException("Error compiling " + source); diff --git a/test/jdk/jdk/classfile/StackMapsTest.java b/test/jdk/jdk/classfile/StackMapsTest.java index 857299f4ecd..b2f94596622 100644 --- a/test/jdk/jdk/classfile/StackMapsTest.java +++ b/test/jdk/jdk/classfile/StackMapsTest.java @@ -33,7 +33,7 @@ import java.lang.classfile.attribute.CodeAttribute; import java.lang.classfile.attribute.StackMapFrameInfo; import java.lang.classfile.attribute.StackMapTableAttribute; -import java.lang.classfile.components.ClassPrinter; +import jdk.internal.classfile.components.ClassPrinter; import java.lang.constant.ClassDesc; import java.lang.constant.ConstantDescs; import java.lang.constant.MethodTypeDesc; diff --git a/test/jdk/jdk/classfile/StackTrackerTest.java b/test/jdk/jdk/classfile/StackTrackerTest.java index b4e82ab0c4b..7d25c9e2ab9 100644 --- a/test/jdk/jdk/classfile/StackTrackerTest.java +++ b/test/jdk/jdk/classfile/StackTrackerTest.java @@ -31,7 +31,7 @@ import java.lang.constant.MethodTypeDesc; import java.lang.constant.ConstantDescs; import java.lang.classfile.*; -import java.lang.classfile.components.CodeStackTracker; +import jdk.internal.classfile.components.CodeStackTracker; import static java.lang.classfile.TypeKind.*; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; diff --git a/test/jdk/jdk/classfile/TEST.properties b/test/jdk/jdk/classfile/TEST.properties index 756e08b7b93..296312b258f 100644 --- a/test/jdk/jdk/classfile/TEST.properties +++ b/test/jdk/jdk/classfile/TEST.properties @@ -1,6 +1,7 @@ maxOutputSize = 2500000 enablePreview = true modules = \ + java.base/jdk.internal.classfile.components \ java.base/jdk.internal.classfile.impl \ java.base/jdk.internal.classfile.impl.verifier \ java.base/jdk.internal.org.objectweb.asm \ diff --git a/test/jdk/jdk/classfile/VerifierSelfTest.java b/test/jdk/jdk/classfile/VerifierSelfTest.java index 1f9f199a33b..bc4ad5ab4ef 100644 --- a/test/jdk/jdk/classfile/VerifierSelfTest.java +++ b/test/jdk/jdk/classfile/VerifierSelfTest.java @@ -48,7 +48,7 @@ import java.util.stream.Stream; import java.lang.classfile.*; import java.lang.classfile.attribute.*; -import java.lang.classfile.components.ClassPrinter; +import jdk.internal.classfile.components.ClassPrinter; import java.lang.classfile.constantpool.Utf8Entry; import java.lang.constant.ModuleDesc; diff --git a/test/jdk/jdk/classfile/examples/AnnotationsExamples.java b/test/jdk/jdk/classfile/examples/AnnotationsExamples.java index a43ab72556e..dfec144bbab 100644 --- a/test/jdk/jdk/classfile/examples/AnnotationsExamples.java +++ b/test/jdk/jdk/classfile/examples/AnnotationsExamples.java @@ -39,7 +39,7 @@ import java.lang.classfile.ClassFile; import java.lang.classfile.attribute.RuntimeVisibleAnnotationsAttribute; import java.lang.classfile.constantpool.ConstantPoolBuilder; -import java.lang.classfile.components.ClassPrinter; +import jdk.internal.classfile.components.ClassPrinter; public class AnnotationsExamples { diff --git a/test/jdk/jdk/classfile/helpers/RebuildingTransformation.java b/test/jdk/jdk/classfile/helpers/RebuildingTransformation.java index b0e1d6c312d..895c04704cc 100644 --- a/test/jdk/jdk/classfile/helpers/RebuildingTransformation.java +++ b/test/jdk/jdk/classfile/helpers/RebuildingTransformation.java @@ -32,7 +32,7 @@ import java.lang.classfile.instruction.*; import java.lang.constant.ModuleDesc; import java.lang.constant.PackageDesc; -import java.lang.classfile.components.CodeStackTracker; +import jdk.internal.classfile.components.CodeStackTracker; class RebuildingTransformation { diff --git a/test/jdk/jdk/classfile/helpers/Transforms.java b/test/jdk/jdk/classfile/helpers/Transforms.java index c385fe61663..b0e88bd8212 100644 --- a/test/jdk/jdk/classfile/helpers/Transforms.java +++ b/test/jdk/jdk/classfile/helpers/Transforms.java @@ -22,7 +22,6 @@ */ package helpers; -import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.List; import java.util.Map; @@ -43,7 +42,7 @@ import java.lang.classfile.CodeTransform; import java.lang.classfile.MethodModel; import java.lang.classfile.MethodTransform; -import java.lang.classfile.components.ClassRemapper; +import jdk.internal.classfile.components.ClassRemapper; import jdk.internal.org.objectweb.asm.AnnotationVisitor; import jdk.internal.org.objectweb.asm.Attribute; import jdk.internal.org.objectweb.asm.ClassReader; diff --git a/test/micro/org/openjdk/bench/jdk/classfile/AbstractCorpusBenchmark.java b/test/micro/org/openjdk/bench/jdk/classfile/AbstractCorpusBenchmark.java index 5f64e114877..685f73e64ce 100644 --- a/test/micro/org/openjdk/bench/jdk/classfile/AbstractCorpusBenchmark.java +++ b/test/micro/org/openjdk/bench/jdk/classfile/AbstractCorpusBenchmark.java @@ -47,6 +47,7 @@ "--add-exports", "java.base/jdk.internal.org.objectweb.asm=ALL-UNNAMED", "--add-exports", "java.base/jdk.internal.org.objectweb.asm.tree=ALL-UNNAMED", "--enable-preview", + "--add-exports", "java.base/jdk.internal.classfile.components=ALL-UNNAMED", "--add-exports", "java.base/jdk.internal.classfile.impl=ALL-UNNAMED"}) @State(Scope.Benchmark) public class AbstractCorpusBenchmark { diff --git a/test/micro/org/openjdk/bench/jdk/classfile/RepeatedModelTraversal.java b/test/micro/org/openjdk/bench/jdk/classfile/RepeatedModelTraversal.java index b9c9082625c..f8f29036545 100644 --- a/test/micro/org/openjdk/bench/jdk/classfile/RepeatedModelTraversal.java +++ b/test/micro/org/openjdk/bench/jdk/classfile/RepeatedModelTraversal.java @@ -31,12 +31,13 @@ import java.util.List; import java.lang.classfile.ClassModel; import java.lang.classfile.ClassFile; -import java.lang.classfile.components.ClassPrinter; +import jdk.internal.classfile.components.ClassPrinter; import org.openjdk.jmh.annotations.*; @BenchmarkMode(Mode.Throughput) @State(Scope.Benchmark) @Fork(value = 1, jvmArgs = { + "--add-exports", "java.base/jdk.internal.classfile.components=ALL-UNNAMED", "--enable-preview"}) @Warmup(iterations = 3) @Measurement(iterations = 4) diff --git a/test/micro/org/openjdk/bench/jdk/classfile/Transforms.java b/test/micro/org/openjdk/bench/jdk/classfile/Transforms.java index e4d553c268f..8af03a8b874 100644 --- a/test/micro/org/openjdk/bench/jdk/classfile/Transforms.java +++ b/test/micro/org/openjdk/bench/jdk/classfile/Transforms.java @@ -22,11 +22,8 @@ */ package org.openjdk.bench.jdk.classfile; -import java.io.ByteArrayInputStream; -import java.io.IOException; import java.util.List; import java.util.Map; -import java.util.Optional; import java.util.function.Consumer; import java.util.function.UnaryOperator; @@ -43,7 +40,7 @@ import java.lang.classfile.CodeTransform; import java.lang.classfile.MethodModel; import java.lang.classfile.MethodTransform; -import java.lang.classfile.components.ClassRemapper; +import jdk.internal.classfile.components.ClassRemapper; import jdk.internal.org.objectweb.asm.AnnotationVisitor; import jdk.internal.org.objectweb.asm.Attribute; import jdk.internal.org.objectweb.asm.ClassReader; From baa6957b9bf9c050c44ef6e36d21566dd3636fa0 Mon Sep 17 00:00:00 2001 From: Magnus Ihse Bursie Date: Wed, 4 Dec 2024 17:51:04 +0000 Subject: [PATCH 18/43] 8345507: Fix build of static launcher Reviewed-by: erikj --- make/ModuleWrapper.gmk | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/make/ModuleWrapper.gmk b/make/ModuleWrapper.gmk index e99f34cdd71..51208432ea0 100644 --- a/make/ModuleWrapper.gmk +++ b/make/ModuleWrapper.gmk @@ -51,7 +51,7 @@ ifeq ($(MAKEFILE_PREFIX), Lib) # which static library files to include. The variable $(MODULE)_INCLUDED_LIBS is # added to for each call to SetupJdkLibrary. The file module-included-libs.txt is then # read in StaticLibs.gmk. - ifneq ($($(MODULE)_JDK_LIBS), ) + ifneq ($($(MODULE)_INCLUDED_LIBS), ) LIBLIST := $(SUPPORT_OUTPUTDIR)/modules_static-libs/$(MODULE)/module-included-libs.txt $(LIBLIST): $(TARGETS) From e1695f6c40dbf27538c6c450eb1cf64a05e0ee9a Mon Sep 17 00:00:00 2001 From: Jatin Bhateja Date: Wed, 4 Dec 2024 18:27:37 +0000 Subject: [PATCH 19/43] 8345472: Fix incorrect format instruction for floating point max/min patterns Reviewed-by: kvn --- src/hotspot/cpu/x86/x86_64.ad | 40 +++++++++++++++++------------------ 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/src/hotspot/cpu/x86/x86_64.ad b/src/hotspot/cpu/x86/x86_64.ad index 550c8047034..4667922505c 100644 --- a/src/hotspot/cpu/x86/x86_64.ad +++ b/src/hotspot/cpu/x86/x86_64.ad @@ -4424,21 +4424,21 @@ instruct maxF_reg(legRegF dst, legRegF a, legRegF b, legRegF tmp, legRegF atmp, predicate(UseAVX > 0 && !VLoopReductions::is_reduction(n)); match(Set dst (MaxF a b)); effect(USE a, USE b, TEMP tmp, TEMP atmp, TEMP btmp); - format %{ "maxF $dst, $a, $b \t! using tmp, atmp and btmp as TEMP" %} + format %{ "maxF $dst, $a, $b \t! using $tmp, $atmp and $btmp as TEMP" %} ins_encode %{ __ vminmax_fp(Op_MaxV, T_FLOAT, $dst$$XMMRegister, $a$$XMMRegister, $b$$XMMRegister, $tmp$$XMMRegister, $atmp$$XMMRegister, $btmp$$XMMRegister, Assembler::AVX_128bit); %} ins_pipe( pipe_slow ); %} -instruct maxF_reduction_reg(legRegF dst, legRegF a, legRegF b, legRegF xmmt, rRegI tmp, rFlagsReg cr) %{ +instruct maxF_reduction_reg(legRegF dst, legRegF a, legRegF b, legRegF xtmp, rRegI rtmp, rFlagsReg cr) %{ predicate(UseAVX > 0 && VLoopReductions::is_reduction(n)); match(Set dst (MaxF a b)); - effect(USE a, USE b, TEMP xmmt, TEMP tmp, KILL cr); + effect(USE a, USE b, TEMP xtmp, TEMP rtmp, KILL cr); - format %{ "$dst = max($a, $b)\t# intrinsic (float)" %} + format %{ "maxF_reduction $dst, $a, $b \t!using $xtmp and $rtmp as TEMP" %} ins_encode %{ - emit_fp_min_max(masm, $dst$$XMMRegister, $a$$XMMRegister, $b$$XMMRegister, $xmmt$$XMMRegister, $tmp$$Register, + emit_fp_min_max(masm, $dst$$XMMRegister, $a$$XMMRegister, $b$$XMMRegister, $xtmp$$XMMRegister, $rtmp$$Register, false /*min*/, true /*single*/); %} ins_pipe( pipe_slow ); @@ -4449,21 +4449,21 @@ instruct maxD_reg(legRegD dst, legRegD a, legRegD b, legRegD tmp, legRegD atmp, predicate(UseAVX > 0 && !VLoopReductions::is_reduction(n)); match(Set dst (MaxD a b)); effect(USE a, USE b, TEMP atmp, TEMP btmp, TEMP tmp); - format %{ "maxD $dst, $a, $b \t! using tmp, atmp and btmp as TEMP" %} + format %{ "maxD $dst, $a, $b \t! using $tmp, $atmp and $btmp as TEMP" %} ins_encode %{ __ vminmax_fp(Op_MaxV, T_DOUBLE, $dst$$XMMRegister, $a$$XMMRegister, $b$$XMMRegister, $tmp$$XMMRegister, $atmp$$XMMRegister, $btmp$$XMMRegister, Assembler::AVX_128bit); %} ins_pipe( pipe_slow ); %} -instruct maxD_reduction_reg(legRegD dst, legRegD a, legRegD b, legRegD xmmt, rRegL tmp, rFlagsReg cr) %{ +instruct maxD_reduction_reg(legRegD dst, legRegD a, legRegD b, legRegD xtmp, rRegL rtmp, rFlagsReg cr) %{ predicate(UseAVX > 0 && VLoopReductions::is_reduction(n)); match(Set dst (MaxD a b)); - effect(USE a, USE b, TEMP xmmt, TEMP tmp, KILL cr); + effect(USE a, USE b, TEMP xtmp, TEMP rtmp, KILL cr); - format %{ "$dst = max($a, $b)\t# intrinsic (double)" %} + format %{ "maxD_reduction $dst, $a, $b \t! using $xtmp and $rtmp as TEMP" %} ins_encode %{ - emit_fp_min_max(masm, $dst$$XMMRegister, $a$$XMMRegister, $b$$XMMRegister, $xmmt$$XMMRegister, $tmp$$Register, + emit_fp_min_max(masm, $dst$$XMMRegister, $a$$XMMRegister, $b$$XMMRegister, $xtmp$$XMMRegister, $rtmp$$Register, false /*min*/, false /*single*/); %} ins_pipe( pipe_slow ); @@ -4474,21 +4474,21 @@ instruct minF_reg(legRegF dst, legRegF a, legRegF b, legRegF tmp, legRegF atmp, predicate(UseAVX > 0 && !VLoopReductions::is_reduction(n)); match(Set dst (MinF a b)); effect(USE a, USE b, TEMP tmp, TEMP atmp, TEMP btmp); - format %{ "minF $dst, $a, $b \t! using tmp, atmp and btmp as TEMP" %} + format %{ "minF $dst, $a, $b \t! using $tmp, $atmp and $btmp as TEMP" %} ins_encode %{ __ vminmax_fp(Op_MinV, T_FLOAT, $dst$$XMMRegister, $a$$XMMRegister, $b$$XMMRegister, $tmp$$XMMRegister, $atmp$$XMMRegister, $btmp$$XMMRegister, Assembler::AVX_128bit); %} ins_pipe( pipe_slow ); %} -instruct minF_reduction_reg(legRegF dst, legRegF a, legRegF b, legRegF xmmt, rRegI tmp, rFlagsReg cr) %{ +instruct minF_reduction_reg(legRegF dst, legRegF a, legRegF b, legRegF xtmp, rRegI rtmp, rFlagsReg cr) %{ predicate(UseAVX > 0 && VLoopReductions::is_reduction(n)); match(Set dst (MinF a b)); - effect(USE a, USE b, TEMP xmmt, TEMP tmp, KILL cr); + effect(USE a, USE b, TEMP xtmp, TEMP rtmp, KILL cr); - format %{ "$dst = min($a, $b)\t# intrinsic (float)" %} + format %{ "minF_reduction $dst, $a, $b \t! using $xtmp and $rtmp as TEMP" %} ins_encode %{ - emit_fp_min_max(masm, $dst$$XMMRegister, $a$$XMMRegister, $b$$XMMRegister, $xmmt$$XMMRegister, $tmp$$Register, + emit_fp_min_max(masm, $dst$$XMMRegister, $a$$XMMRegister, $b$$XMMRegister, $xtmp$$XMMRegister, $rtmp$$Register, true /*min*/, true /*single*/); %} ins_pipe( pipe_slow ); @@ -4499,21 +4499,21 @@ instruct minD_reg(legRegD dst, legRegD a, legRegD b, legRegD tmp, legRegD atmp, predicate(UseAVX > 0 && !VLoopReductions::is_reduction(n)); match(Set dst (MinD a b)); effect(USE a, USE b, TEMP tmp, TEMP atmp, TEMP btmp); - format %{ "minD $dst, $a, $b \t! using tmp, atmp and btmp as TEMP" %} + format %{ "minD $dst, $a, $b \t! using $tmp, $atmp and $btmp as TEMP" %} ins_encode %{ __ vminmax_fp(Op_MinV, T_DOUBLE, $dst$$XMMRegister, $a$$XMMRegister, $b$$XMMRegister, $tmp$$XMMRegister, $atmp$$XMMRegister, $btmp$$XMMRegister, Assembler::AVX_128bit); %} ins_pipe( pipe_slow ); %} -instruct minD_reduction_reg(legRegD dst, legRegD a, legRegD b, legRegD xmmt, rRegL tmp, rFlagsReg cr) %{ +instruct minD_reduction_reg(legRegD dst, legRegD a, legRegD b, legRegD xtmp, rRegL rtmp, rFlagsReg cr) %{ predicate(UseAVX > 0 && VLoopReductions::is_reduction(n)); match(Set dst (MinD a b)); - effect(USE a, USE b, TEMP xmmt, TEMP tmp, KILL cr); + effect(USE a, USE b, TEMP xtmp, TEMP rtmp, KILL cr); - format %{ "$dst = min($a, $b)\t# intrinsic (double)" %} + format %{ "maxD_reduction $dst, $a, $b \t! using $xtmp and $rtmp as TEMP" %} ins_encode %{ - emit_fp_min_max(masm, $dst$$XMMRegister, $a$$XMMRegister, $b$$XMMRegister, $xmmt$$XMMRegister, $tmp$$Register, + emit_fp_min_max(masm, $dst$$XMMRegister, $a$$XMMRegister, $b$$XMMRegister, $xtmp$$XMMRegister, $rtmp$$Register, true /*min*/, false /*single*/); %} ins_pipe( pipe_slow ); From 6aa7667e9d05c1c3edce5ae2f29864e7a876ebbe Mon Sep 17 00:00:00 2001 From: Ioi Lam Date: Wed, 4 Dec 2024 18:45:35 +0000 Subject: [PATCH 20/43] 8339535: JVM crashes with -Xshare:dump -XX:+SegmentedCodeCache Reviewed-by: ccheung, dholmes, kvn --- src/hotspot/share/runtime/arguments.cpp | 47 ++++++++++--------- src/hotspot/share/runtime/arguments.hpp | 8 ++-- .../cds/appcds/CommandLineFlagCombo.java | 3 +- 3 files changed, 30 insertions(+), 28 deletions(-) diff --git a/src/hotspot/share/runtime/arguments.cpp b/src/hotspot/share/runtime/arguments.cpp index 8df81ca0f94..11481954e10 100644 --- a/src/hotspot/share/runtime/arguments.cpp +++ b/src/hotspot/share/runtime/arguments.cpp @@ -1775,14 +1775,20 @@ bool Arguments::sun_java_launcher_is_altjvm() { //=========================================================================================================== // Parsing of main arguments -unsigned int addreads_count = 0; -unsigned int addexports_count = 0; -unsigned int addopens_count = 0; -unsigned int patch_mod_count = 0; -unsigned int enable_native_access_count = 0; +static unsigned int addreads_count = 0; +static unsigned int addexports_count = 0; +static unsigned int addopens_count = 0; +static unsigned int patch_mod_count = 0; +static unsigned int enable_native_access_count = 0; +static bool patch_mod_javabase = false; // Check the consistency of vm_init_args bool Arguments::check_vm_args_consistency() { + // This may modify compiler flags. Must be called before CompilerConfig::check_args_consistency() + if (!CDSConfig::check_vm_args_consistency(patch_mod_javabase, mode_flag_cmd_line)) { + return false; + } + // Method for adding checks for flag consistency. // The intent is to warn the user of all possible conflicts, // before returning an error. @@ -1953,8 +1959,6 @@ jint Arguments::parse_vm_init_args(const JavaVMInitArgs *vm_options_args, const JavaVMInitArgs *java_tool_options_args, const JavaVMInitArgs *java_options_args, const JavaVMInitArgs *cmd_line_args) { - bool patch_mod_javabase = false; - // Save default settings for some mode flags Arguments::_AlwaysCompileLoopMethods = AlwaysCompileLoopMethods; Arguments::_UseOnStackReplacement = UseOnStackReplacement; @@ -1968,27 +1972,27 @@ jint Arguments::parse_vm_init_args(const JavaVMInitArgs *vm_options_args, set_mode_flags(_mixed); // Parse args structure generated from java.base vm options resource - jint result = parse_each_vm_init_arg(vm_options_args, &patch_mod_javabase, JVMFlagOrigin::JIMAGE_RESOURCE); + jint result = parse_each_vm_init_arg(vm_options_args, JVMFlagOrigin::JIMAGE_RESOURCE); if (result != JNI_OK) { return result; } // Parse args structure generated from JAVA_TOOL_OPTIONS environment // variable (if present). - result = parse_each_vm_init_arg(java_tool_options_args, &patch_mod_javabase, JVMFlagOrigin::ENVIRON_VAR); + result = parse_each_vm_init_arg(java_tool_options_args, JVMFlagOrigin::ENVIRON_VAR); if (result != JNI_OK) { return result; } // Parse args structure generated from the command line flags. - result = parse_each_vm_init_arg(cmd_line_args, &patch_mod_javabase, JVMFlagOrigin::COMMAND_LINE); + result = parse_each_vm_init_arg(cmd_line_args, JVMFlagOrigin::COMMAND_LINE); if (result != JNI_OK) { return result; } // Parse args structure generated from the _JAVA_OPTIONS environment // variable (if present) (mimics classic VM) - result = parse_each_vm_init_arg(java_options_args, &patch_mod_javabase, JVMFlagOrigin::ENVIRON_VAR); + result = parse_each_vm_init_arg(java_options_args, JVMFlagOrigin::ENVIRON_VAR); if (result != JNI_OK) { return result; } @@ -2009,7 +2013,7 @@ jint Arguments::parse_vm_init_args(const JavaVMInitArgs *vm_options_args, SystemMemoryBarrier::initialize(); // Do final processing now that all arguments have been parsed - result = finalize_vm_init_args(patch_mod_javabase); + result = finalize_vm_init_args(); if (result != JNI_OK) { return result; } @@ -2064,7 +2068,7 @@ static bool valid_jdwp_agent(char *name, bool is_path) { } #endif -int Arguments::process_patch_mod_option(const char* patch_mod_tail, bool* patch_mod_javabase) { +int Arguments::process_patch_mod_option(const char* patch_mod_tail) { // --patch-module==()* assert(patch_mod_tail != nullptr, "Unexpected null patch-module value"); // Find the equal sign between the module name and the path specification @@ -2080,7 +2084,7 @@ int Arguments::process_patch_mod_option(const char* patch_mod_tail, bool* patch_ memcpy(module_name, patch_mod_tail, module_len); *(module_name + module_len) = '\0'; // The path piece begins one past the module_equal sign - add_patch_mod_prefix(module_name, module_equal + 1, patch_mod_javabase); + add_patch_mod_prefix(module_name, module_equal + 1); FREE_C_HEAP_ARRAY(char, module_name); if (!create_numbered_module_property("jdk.module.patch", patch_mod_tail, patch_mod_count++)) { return JNI_ENOMEM; @@ -2146,7 +2150,7 @@ jint Arguments::parse_xss(const JavaVMOption* option, const char* tail, intx* ou return JNI_OK; } -jint Arguments::parse_each_vm_init_arg(const JavaVMInitArgs* args, bool* patch_mod_javabase, JVMFlagOrigin origin) { +jint Arguments::parse_each_vm_init_arg(const JavaVMInitArgs* args, JVMFlagOrigin origin) { // For match_option to return remaining or value part of option string const char* tail; @@ -2273,7 +2277,7 @@ jint Arguments::parse_each_vm_init_arg(const JavaVMInitArgs* args, bool* patch_m } } else if (match_option(option, "--patch-module=", &tail)) { // --patch-module==()* - int res = process_patch_mod_option(tail, patch_mod_javabase); + int res = process_patch_mod_option(tail); if (res != JNI_OK) { return res; } @@ -2822,16 +2826,16 @@ jint Arguments::parse_each_vm_init_arg(const JavaVMInitArgs* args, bool* patch_m return JNI_OK; } -void Arguments::add_patch_mod_prefix(const char* module_name, const char* path, bool* patch_mod_javabase) { +void Arguments::add_patch_mod_prefix(const char* module_name, const char* path) { // For java.base check for duplicate --patch-module options being specified on the command line. // This check is only required for java.base, all other duplicate module specifications // will be checked during module system initialization. The module system initialization // will throw an ExceptionInInitializerError if this situation occurs. if (strcmp(module_name, JAVA_BASE_NAME) == 0) { - if (*patch_mod_javabase) { + if (patch_mod_javabase) { vm_exit_during_initialization("Cannot specify " JAVA_BASE_NAME " more than once to --patch-module"); } else { - *patch_mod_javabase = true; + patch_mod_javabase = true; } } @@ -2883,7 +2887,7 @@ void Arguments::fix_appclasspath() { } } -jint Arguments::finalize_vm_init_args(bool patch_mod_javabase) { +jint Arguments::finalize_vm_init_args() { // check if the default lib/endorsed directory exists; if so, error char path[JVM_MAXPATHLEN]; const char* fileSep = os::file_separator(); @@ -2957,9 +2961,6 @@ jint Arguments::finalize_vm_init_args(bool patch_mod_javabase) { return JNI_ERR; } - if (!CDSConfig::check_vm_args_consistency(patch_mod_javabase, mode_flag_cmd_line)) { - return JNI_ERR; - } #ifndef CAN_SHOW_REGISTERS_ON_ASSERT UNSUPPORTED_OPTION(ShowRegistersOnAssert); diff --git a/src/hotspot/share/runtime/arguments.hpp b/src/hotspot/share/runtime/arguments.hpp index cac0296b327..f18e44bbb55 100644 --- a/src/hotspot/share/runtime/arguments.hpp +++ b/src/hotspot/share/runtime/arguments.hpp @@ -290,7 +290,7 @@ class Arguments : AllStatic { static bool create_module_property(const char* prop_name, const char* prop_value, PropertyInternal internal); static bool create_numbered_module_property(const char* prop_base_name, const char* prop_value, unsigned int count); - static int process_patch_mod_option(const char* patch_mod_tail, bool* patch_mod_javabase); + static int process_patch_mod_option(const char* patch_mod_tail); // Aggressive optimization flags. static jint set_aggressive_opts_flags(); @@ -325,8 +325,8 @@ class Arguments : AllStatic { const JavaVMInitArgs *java_tool_options_args, const JavaVMInitArgs *java_options_args, const JavaVMInitArgs *cmd_line_args); - static jint parse_each_vm_init_arg(const JavaVMInitArgs* args, bool* patch_mod_javabase, JVMFlagOrigin origin); - static jint finalize_vm_init_args(bool patch_mod_javabase); + static jint parse_each_vm_init_arg(const JavaVMInitArgs* args, JVMFlagOrigin origin); + static jint finalize_vm_init_args(); static bool is_bad_option(const JavaVMOption* option, jboolean ignore, const char* option_type); static bool is_bad_option(const JavaVMOption* option, jboolean ignore) { @@ -474,7 +474,7 @@ class Arguments : AllStatic { static void set_ext_dirs(char *value) { _ext_dirs = os::strdup_check_oom(value); } // Set up the underlying pieces of the boot class path - static void add_patch_mod_prefix(const char *module_name, const char *path, bool* patch_mod_javabase); + static void add_patch_mod_prefix(const char *module_name, const char *path); static void set_boot_class_path(const char *value, bool has_jimage) { // During start up, set by os::set_boot_path() assert(get_boot_class_path() == nullptr, "Boot class path previously set"); diff --git a/test/hotspot/jtreg/runtime/cds/appcds/CommandLineFlagCombo.java b/test/hotspot/jtreg/runtime/cds/appcds/CommandLineFlagCombo.java index 8e33bf0bb0c..6ab9b18c1e9 100644 --- a/test/hotspot/jtreg/runtime/cds/appcds/CommandLineFlagCombo.java +++ b/test/hotspot/jtreg/runtime/cds/appcds/CommandLineFlagCombo.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 @@ -63,6 +63,7 @@ public class CommandLineFlagCombo { "-Xint", "-Xmixed", "-Xcomp", + "-XX:+SegmentedCodeCache", }; public static void main(String[] args) throws Exception { From faa109e8d40dbe8c6beb26bd8f9e5f6f63e4cab1 Mon Sep 17 00:00:00 2001 From: Alexey Ivanov Date: Wed, 4 Dec 2024 18:52:07 +0000 Subject: [PATCH 21/43] 8340580: Characters in Document diagrams not in the middle Move text in Document-{insert,remove}.svg by 0.5 of pixel Reviewed-by: azvegint, kizune --- .../swing/text/doc-files/Document-insert.svg | 38 +++++++++--------- .../swing/text/doc-files/Document-remove.svg | 40 +++++++++---------- 2 files changed, 39 insertions(+), 39 deletions(-) diff --git a/src/java.desktop/share/classes/javax/swing/text/doc-files/Document-insert.svg b/src/java.desktop/share/classes/javax/swing/text/doc-files/Document-insert.svg index 09a74210d41..8bb51a43055 100644 --- a/src/java.desktop/share/classes/javax/swing/text/doc-files/Document-insert.svg +++ b/src/java.desktop/share/classes/javax/swing/text/doc-files/Document-insert.svg @@ -97,49 +97,49 @@ - T + T - h + h - e + e - + - q + q - u + u - i + i - c + c - k + k - + - b + b - r + r - o + o - w + w - n + n - + - f + f - o + o - x + x diff --git a/src/java.desktop/share/classes/javax/swing/text/doc-files/Document-remove.svg b/src/java.desktop/share/classes/javax/swing/text/doc-files/Document-remove.svg index 2c8e91923f5..e47a5f750d0 100644 --- a/src/java.desktop/share/classes/javax/swing/text/doc-files/Document-remove.svg +++ b/src/java.desktop/share/classes/javax/swing/text/doc-files/Document-remove.svg @@ -1,7 +1,7 @@