1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache license, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the license for the specific language governing permissions and
15 * limitations under the license.
16 */
17 package org.apache.logging.log4j.util;
18
19 import java.util.Stack;
20
21 /**
22 * Internal utility to share a fast implementation of {@link #getCurrentStackTrace()}
23 * with the java 9 implementation of {@link StackLocator}.
24 */
25 final class PrivateSecurityManagerStackTraceUtil {
26
27 private static final PrivateSecurityManager SECURITY_MANAGER;
28
29 static {
30 PrivateSecurityManager psm;
31 try {
32 final SecurityManager sm = System.getSecurityManager();
33 if (sm != null) {
34 sm.checkPermission(new RuntimePermission("createSecurityManager"));
35 }
36 psm = new PrivateSecurityManager();
37 } catch (final SecurityException ignored) {
38 psm = null;
39 }
40
41 SECURITY_MANAGER = psm;
42 }
43
44 private PrivateSecurityManagerStackTraceUtil() {
45 // Utility Class
46 }
47
48 static boolean isEnabled() {
49 return SECURITY_MANAGER != null;
50 }
51
52 // benchmarks show that using the SecurityManager is much faster than looping through getCallerClass(int)
53 static Stack<Class<?>> getCurrentStackTrace() {
54 final Class<?>[] array = SECURITY_MANAGER.getClassContext();
55 final Stack<Class<?>> classes = new Stack<>();
56 classes.ensureCapacity(array.length);
57 for (final Class<?> clazz : array) {
58 classes.push(clazz);
59 }
60 return classes;
61 }
62
63 private static final class PrivateSecurityManager extends SecurityManager {
64
65 @Override
66 protected Class<?>[] getClassContext() {
67 return super.getClassContext();
68 }
69
70 }
71 }