|
| 1 | +package edu.umd.cs.findbugs.util; |
| 2 | + |
| 3 | +import org.apache.commons.lang3.JavaVersion; |
| 4 | +import org.apache.commons.lang3.SystemUtils; |
| 5 | +import org.slf4j.Logger; |
| 6 | +import org.slf4j.LoggerFactory; |
| 7 | + |
| 8 | +/** |
| 9 | + * Since Java 17, the security manager is deprecated for removal and invoking related methods |
| 10 | + * causes a warning to be printed to the console. This intermediate disables the use of |
| 11 | + * security manager-related APIs on Java 17 or later, unless using the security manager is |
| 12 | + * explicitly configured by setting the <i>edu.umd.cs.findbugs.securityManagerDisabled</i> |
| 13 | + * property. |
| 14 | + */ |
| 15 | +public class SecurityManagerHandler { |
| 16 | + |
| 17 | + private static final Logger LOGGER = LoggerFactory.getLogger(SecurityManagerHandler.class); |
| 18 | + |
| 19 | + /** |
| 20 | + * Determines if the security manager is used by SpotBugs. |
| 21 | + */ |
| 22 | + public static boolean SECURITY_MANAGER_DISABLED; |
| 23 | + |
| 24 | + static { |
| 25 | + boolean securityManagerDisabled; |
| 26 | + try { |
| 27 | + String property = System.getProperty("edu.umd.cs.findbugs.securityManagerDisabled"); |
| 28 | + if (property != null) { |
| 29 | + securityManagerDisabled = Boolean.parseBoolean(property); |
| 30 | + } else { |
| 31 | + securityManagerDisabled = SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_17); |
| 32 | + } |
| 33 | + } catch (Throwable t) { |
| 34 | + securityManagerDisabled = false; |
| 35 | + LOGGER.debug("failed to detect the ability of security manager feature, so treat it as available", t); |
| 36 | + } |
| 37 | + SECURITY_MANAGER_DISABLED = securityManagerDisabled; |
| 38 | + } |
| 39 | + |
| 40 | + /** |
| 41 | + * Disables the security manager by setting {@link System#setSecurityManager(SecurityManager)} |
| 42 | + * to {@code null}. |
| 43 | + */ |
| 44 | + public static void disableSecurityManager() { |
| 45 | + if (SECURITY_MANAGER_DISABLED) { |
| 46 | + return; |
| 47 | + } |
| 48 | + doDisableSecurityManager(); |
| 49 | + } |
| 50 | + |
| 51 | + /** |
| 52 | + * This method is a safeguard for running this library on a JVM that might no longer include |
| 53 | + * the security manager API after removal. As the JVM verifies methods lazily, and since this |
| 54 | + * method will never be invoked, validation of this method with a missing type can never fail. |
| 55 | + * |
| 56 | + * As some environments do not support setting the security manager but always return null |
| 57 | + * when getting it, we check if a security manager is set before disabling it. |
| 58 | + */ |
| 59 | + private static void doDisableSecurityManager() { |
| 60 | + SecurityManager sm = System.getSecurityManager(); |
| 61 | + if (sm != null) { |
| 62 | + System.setSecurityManager(null); |
| 63 | + } |
| 64 | + } |
| 65 | +} |
0 commit comments