Skip to content

Commit 40d66ed

Browse files
committed
Verifying the capability of PrivateSecurityManager so platforms not (fully) supporting SecurityManager do not poison the stack trace.
1 parent 7acbc48 commit 40d66ed

File tree

1 file changed

+30
-1
lines changed

1 file changed

+30
-1
lines changed

log4j-api/src/main/java/org/apache/logging/log4j/util/PrivateSecurityManagerStackTraceUtil.java

+30-1
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,35 @@ final class PrivateSecurityManagerStackTraceUtil {
2929
private static final PrivateSecurityManager SECURITY_MANAGER;
3030

3131
static {
32+
PrivateSecurityManager candidate = createPrivateSecurityManager();
33+
if (isCapable(candidate)) {
34+
SECURITY_MANAGER = candidate;
35+
} else {
36+
SECURITY_MANAGER = null;
37+
}
38+
}
39+
40+
private static boolean isCapable(PrivateSecurityManager candidate) {
41+
if (candidate == null) {
42+
return false;
43+
}
44+
45+
try {
46+
final Class<?>[] result = candidate.getClassContext();
47+
if (result == null || result.length == 0) {
48+
// This happens e.g. on Android which has real implementation of SecurityManager replaced with merely
49+
// stubs. So the PrivateSecurityManager, though can be instantiated, will not produce meaningful
50+
// results
51+
return false;
52+
}
53+
// Add more checks here as needed
54+
return true;
55+
} catch (Exception ignored) {
56+
return false;
57+
}
58+
}
59+
60+
private static PrivateSecurityManager createPrivateSecurityManager() {
3261
PrivateSecurityManager psm;
3362
try {
3463
final SecurityManager sm = System.getSecurityManager();
@@ -40,7 +69,7 @@ final class PrivateSecurityManagerStackTraceUtil {
4069
psm = null;
4170
}
4271

43-
SECURITY_MANAGER = psm;
72+
return psm;
4473
}
4574

4675
private PrivateSecurityManagerStackTraceUtil() {

0 commit comments

Comments
 (0)