|
| 1 | +package edu.umd.cs.findbugs.util; |
| 2 | + |
| 3 | +/** |
| 4 | + * Since Java 17, the security manager is deprecated for removal and invoking related methods |
| 5 | + * causes a warning to be printed to the console. This intermediate disables the use of |
| 6 | + * security manager-related APIs on Java 17 or later, unless using the security manager is |
| 7 | + * explicitly configured by setting the <i>edu.umd.cs.findbugs.securityManagerDisabled</i> |
| 8 | + * property. |
| 9 | + */ |
| 10 | +public class SecurityManagerHandler { |
| 11 | + |
| 12 | + /** |
| 13 | + * Determines if the security manager is used by SpotBugs. |
| 14 | + */ |
| 15 | + public static boolean SECURITY_MANAGER_DISABLED; |
| 16 | + |
| 17 | + static { |
| 18 | + boolean securityManagerDisabled; |
| 19 | + try { |
| 20 | + String property = System.getProperty("edu.umd.cs.findbugs.securityManagerDisabled"); |
| 21 | + if (property != null) { |
| 22 | + securityManagerDisabled = Boolean.parseBoolean(property); |
| 23 | + } else { |
| 24 | + String version = System.getProperty("java.version"); |
| 25 | + if (version.startsWith("1.")) { |
| 26 | + version = version.substring(2, 3); |
| 27 | + } else { |
| 28 | + int index = version.indexOf("."); |
| 29 | + if (index != -1) { |
| 30 | + version = version.substring(0, index); |
| 31 | + } |
| 32 | + } |
| 33 | + securityManagerDisabled = Integer.parseInt(version) > 16; |
| 34 | + } |
| 35 | + } catch (Throwable ignored) { |
| 36 | + securityManagerDisabled = false; |
| 37 | + } |
| 38 | + SECURITY_MANAGER_DISABLED = securityManagerDisabled; |
| 39 | + } |
| 40 | + |
| 41 | + /** |
| 42 | + * Disables the security manager by setting {@link System#setSecurityManager(SecurityManager)} |
| 43 | + * to {@code null}. |
| 44 | + */ |
| 45 | + public static void disableSecurityManager() { |
| 46 | + if (SECURITY_MANAGER_DISABLED) { |
| 47 | + return; |
| 48 | + } |
| 49 | + doDisableSecurityManager(); |
| 50 | + } |
| 51 | + |
| 52 | + /** |
| 53 | + * This method is a safeguard for running this library on a JVM that might no longer include |
| 54 | + * the security manager API after removal. As the JVM verifies methods lazily, and since this |
| 55 | + * method will never be invoked, validation of this method with a missing type can never fail. |
| 56 | + */ |
| 57 | + private static void doDisableSecurityManager() { |
| 58 | + System.setSecurityManager(null); |
| 59 | + } |
| 60 | +} |
0 commit comments