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.lang.reflect.Method;
20 import java.util.Stack;
21
22 /**
23 * <em>Consider this class private.</em> Provides various methods to determine the caller class. <h3>Background</h3>
24 * <p>
25 * This method, available only in the Oracle/Sun/OpenJDK implementations of the Java Virtual Machine, is a much more
26 * efficient mechanism for determining the {@link Class} of the caller of a particular method. When it is not available,
27 * a {@link SecurityManager} is the second-best option. When this is also not possible, the {@code StackTraceElement[]}
28 * returned by {@link Throwable#getStackTrace()} must be used, and its {@code String} class name converted to a
29 * {@code Class} using the slow {@link Class#forName} (which can add an extra microsecond or more for each invocation
30 * depending on the runtime ClassLoader hierarchy).
31 * </p>
32 * <p>
33 * During Java 8 development, the {@code sun.reflect.Reflection.getCallerClass(int)} was removed from OpenJDK, and this
34 * change was back-ported to Java 7 in version 1.7.0_25 which changed the behavior of the call and caused it to be off
35 * by one stack frame. This turned out to be beneficial for the survival of this API as the change broke hundreds of
36 * libraries and frameworks relying on the API which brought much more attention to the intended API removal.
37 * </p>
38 * <p>
39 * After much community backlash, the JDK team agreed to restore {@code getCallerClass(int)} and keep its existing
40 * behavior for the rest of Java 7. However, the method is deprecated in Java 8, and current Java 9 development has not
41 * addressed this API. Therefore, the functionality of this class cannot be relied upon for all future versions of Java.
42 * It does, however, work just fine in Sun JDK 1.6, OpenJDK 1.6, Oracle/OpenJDK 1.7, and Oracle/OpenJDK 1.8. Other Java
43 * environments may fall back to using {@link Throwable#getStackTrace()} which is significantly slower due to
44 * examination of every virtual frame of execution.
45 * </p>
46 */
47 public final class StackLocator {
48
49 private static PrivateSecurityManager SECURITY_MANAGER;
50
51 // Checkstyle Suppress: the lower-case 'u' ticks off CheckStyle...
52 // CHECKSTYLE:OFF
53 static final int JDK_7u25_OFFSET;
54 // CHECKSTYLE:OFF
55
56 private static final Method GET_CALLER_CLASS;
57
58 private static final StackLocator INSTANCE;
59
60 static {
61 Method getCallerClass;
62 int java7u25CompensationOffset = 0;
63 try {
64 final Class<?> sunReflectionClass = LoaderUtil.loadClass("sun.reflect.Reflection");
65 getCallerClass = sunReflectionClass.getDeclaredMethod("getCallerClass", int.class);
66 Object o = getCallerClass.invoke(null, 0);
67 getCallerClass.invoke(null, 0);
68 if (o == null || o != sunReflectionClass) {
69 getCallerClass = null;
70 java7u25CompensationOffset = -1;
71 } else {
72 o = getCallerClass.invoke(null, 1);
73 if (o == sunReflectionClass) {
74 System.out.println("WARNING: Java 1.7.0_25 is in use which has a broken implementation of Reflection.getCallerClass(). " +
75 " Please consider upgrading to Java 1.7.0_40 or later.");
76 java7u25CompensationOffset = 1;
77 }
78 }
79 } catch (final Exception | LinkageError e) {
80 System.out.println("WARNING: sun.reflect.Reflection.getCallerClass is not supported. This will impact performance.");
81 getCallerClass = null;
82 java7u25CompensationOffset = -1;
83 }
84
85 GET_CALLER_CLASS = getCallerClass;
86 JDK_7u25_OFFSET = java7u25CompensationOffset;
87
88 INSTANCE = new StackLocator();
89 }
90
91 public static StackLocator getInstance() {
92 return INSTANCE;
93 }
94
95 private StackLocator() {
96 }
97
98 // TODO: return Object.class instead of null (though it will have a null ClassLoader)
99 // (MS) I believe this would work without any modifications elsewhere, but I could be wrong
100
101 // migrated from ReflectiveCallerClassUtility
102 @PerformanceSensitive
103 public Class<?> getCallerClass(final int depth) {
104 if (depth < 0) {
105 throw new IndexOutOfBoundsException(Integer.toString(depth));
106 }
107 // note that we need to add 1 to the depth value to compensate for this method, but not for the Method.invoke
108 // since Reflection.getCallerClass ignores the call to Method.invoke()
109 try {
110 return (Class<?>) GET_CALLER_CLASS.invoke(null, depth + 1 + JDK_7u25_OFFSET);
111 } catch (final Exception e) {
112 // theoretically this could happen if the caller class were native code
113 // TODO: return Object.class
114 return null;
115 }
116 }
117
118 // migrated from Log4jLoggerFactory
119 @PerformanceSensitive
120 public Class<?> getCallerClass(final String fqcn, final String pkg) {
121 boolean next = false;
122 Class<?> clazz;
123 for (int i = 2; null != (clazz = getCallerClass(i)); i++) {
124 if (fqcn.equals(clazz.getName())) {
125 next = true;
126 continue;
127 }
128 if (next && clazz.getName().startsWith(pkg)) {
129 return clazz;
130 }
131 }
132 // TODO: return Object.class
133 return null;
134 }
135
136 // added for use in LoggerAdapter implementations mainly
137 @PerformanceSensitive
138 public Class<?> getCallerClass(final Class<?> anchor) {
139 boolean next = false;
140 Class<?> clazz;
141 for (int i = 2; null != (clazz = getCallerClass(i)); i++) {
142 if (anchor.equals(clazz)) {
143 next = true;
144 continue;
145 }
146 if (next) {
147 return clazz;
148 }
149 }
150 return Object.class;
151 }
152
153 // migrated from ThrowableProxy
154 @PerformanceSensitive
155 public Stack<Class<?>> getCurrentStackTrace() {
156 // benchmarks show that using the SecurityManager is much faster than looping through getCallerClass(int)
157 if (getSecurityManager() != null) {
158 final Class<?>[] array = getSecurityManager().getClassContext();
159 final Stack<Class<?>> classes = new Stack<>();
160 classes.ensureCapacity(array.length);
161 for (final Class<?> clazz : array) {
162 classes.push(clazz);
163 }
164 return classes;
165 }
166 // slower version using getCallerClass where we cannot use a SecurityManager
167 final Stack<Class<?>> classes = new Stack<>();
168 Class<?> clazz;
169 for (int i = 1; null != (clazz = getCallerClass(i)); i++) {
170 classes.push(clazz);
171 }
172 return classes;
173 }
174
175 public StackTraceElement calcLocation(final String fqcnOfLogger) {
176 if (fqcnOfLogger == null) {
177 return null;
178 }
179 // LOG4J2-1029 new Throwable().getStackTrace is faster than Thread.currentThread().getStackTrace().
180 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
181 StackTraceElement last = null;
182 for (int i = stackTrace.length - 1; i > 0; i--) {
183 final String className = stackTrace[i].getClassName();
184 if (fqcnOfLogger.equals(className)) {
185 return last;
186 }
187 last = stackTrace[i];
188 }
189 return null;
190 }
191
192 public StackTraceElement getStackTraceElement(final int depth) {
193 // (MS) I tested the difference between using Throwable.getStackTrace() and Thread.getStackTrace(), and
194 // the version using Throwable was surprisingly faster! at least on Java 1.8. See ReflectionBenchmark.
195 final StackTraceElement[] elements = new Throwable().getStackTrace();
196 int i = 0;
197 for (final StackTraceElement element : elements) {
198 if (isValid(element)) {
199 if (i == depth) {
200 return element;
201 }
202 ++i;
203 }
204 }
205 throw new IndexOutOfBoundsException(Integer.toString(depth));
206 }
207
208 private boolean isValid(final StackTraceElement element) {
209 // ignore native methods (oftentimes are repeated frames)
210 if (element.isNativeMethod()) {
211 return false;
212 }
213 final String cn = element.getClassName();
214 // ignore OpenJDK internal classes involved with reflective invocation
215 if (cn.startsWith("sun.reflect.")) {
216 return false;
217 }
218 final String mn = element.getMethodName();
219 // ignore use of reflection including:
220 // Method.invoke
221 // InvocationHandler.invoke
222 // Constructor.newInstance
223 if (cn.startsWith("java.lang.reflect.") && (mn.equals("invoke") || mn.equals("newInstance"))) {
224 return false;
225 }
226 // ignore use of Java 1.9+ reflection classes
227 if (cn.startsWith("jdk.internal.reflect.")) {
228 return false;
229 }
230 // ignore Class.newInstance
231 if (cn.equals("java.lang.Class") && mn.equals("newInstance")) {
232 return false;
233 }
234 // ignore use of Java 1.7+ MethodHandle.invokeFoo() methods
235 if (cn.equals("java.lang.invoke.MethodHandle") && mn.startsWith("invoke")) {
236 return false;
237 }
238 // any others?
239 return true;
240 }
241
242 protected PrivateSecurityManager getSecurityManager() {
243 return SECURITY_MANAGER;
244 }
245
246 private static final class PrivateSecurityManager extends SecurityManager {
247
248 @Override
249 protected Class<?>[] getClassContext() {
250 return super.getClassContext();
251 }
252
253 }
254 }