8269543: The warning for System::setSecurityManager should only appear once for each caller

Reviewed-by: lancea, alanb, dfuchs
This commit is contained in:
Weijun Wang 2021-07-02 14:31:50 +00:00
parent 2db9005c07
commit c4ea13edd0
2 changed files with 53 additions and 19 deletions

View file

@ -54,6 +54,7 @@ import java.security.AccessController;
import java.security.CodeSource;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@ -61,6 +62,7 @@ import java.util.Properties;
import java.util.PropertyPermission;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.function.Supplier;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Stream;
@ -326,6 +328,13 @@ public final class System {
private static native void setOut0(PrintStream out);
private static native void setErr0(PrintStream err);
private static class CallersHolder {
// Remember callers of setSecurityManager() here so that warning
// is only printed once for each different caller
final static Map<Class<?>, Boolean> callers
= Collections.synchronizedMap(new WeakHashMap<>());
}
// Remember initial System.err. setSecurityManager() warning goes here
private static volatile @Stable PrintStream initialErrStream;
@ -378,19 +387,21 @@ public final class System {
public static void setSecurityManager(@SuppressWarnings("removal") SecurityManager sm) {
if (allowSecurityManager()) {
var callerClass = Reflection.getCallerClass();
URL url = codeSource(callerClass);
final String source;
if (url == null) {
source = callerClass.getName();
} else {
source = callerClass.getName() + " (" + url + ")";
if (CallersHolder.callers.putIfAbsent(callerClass, true) == null) {
URL url = codeSource(callerClass);
final String source;
if (url == null) {
source = callerClass.getName();
} else {
source = callerClass.getName() + " (" + url + ")";
}
initialErrStream.printf("""
WARNING: A terminally deprecated method in java.lang.System has been called
WARNING: System::setSecurityManager has been called by %s
WARNING: Please consider reporting this to the maintainers of %s
WARNING: System::setSecurityManager will be removed in a future release
""", source, callerClass.getName());
}
initialErrStream.printf("""
WARNING: A terminally deprecated method in java.lang.System has been called
WARNING: System::setSecurityManager has been called by %s
WARNING: Please consider reporting this to the maintainers of %s
WARNING: System::setSecurityManager will be removed in a future release
""", source, callerClass.getName());
implSetSecurityManager(sm);
} else {
// security manager not allowed