001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache license, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the license for the specific language governing permissions and
015 * limitations under the license.
016 */
017package org.apache.logging.log4j.util;
018
019import java.lang.reflect.Method;
020import java.util.Stack;
021
022/**
023 * <em>Consider this class private.</em> Provides various methods to determine the caller class. <h3>Background</h3>
024 * <p>
025 * This method, available only in the Oracle/Sun/OpenJDK implementations of the Java Virtual Machine, is a much more
026 * efficient mechanism for determining the {@link Class} of the caller of a particular method. When it is not available,
027 * a {@link SecurityManager} is the second-best option. When this is also not possible, the {@code StackTraceElement[]}
028 * returned by {@link Throwable#getStackTrace()} must be used, and its {@code String} class name converted to a
029 * {@code Class} using the slow {@link Class#forName} (which can add an extra microsecond or more for each invocation
030 * depending on the runtime ClassLoader hierarchy).
031 * </p>
032 * <p>
033 * During Java 8 development, the {@code sun.reflect.Reflection.getCallerClass(int)} was removed from OpenJDK, and this
034 * 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
035 * by one stack frame. This turned out to be beneficial for the survival of this API as the change broke hundreds of
036 * libraries and frameworks relying on the API which brought much more attention to the intended API removal.
037 * </p>
038 * <p>
039 * After much community backlash, the JDK team agreed to restore {@code getCallerClass(int)} and keep its existing
040 * behavior for the rest of Java 7. However, the method is deprecated in Java 8, and current Java 9 development has not
041 * addressed this API. Therefore, the functionality of this class cannot be relied upon for all future versions of Java.
042 * 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
043 * environments may fall back to using {@link Throwable#getStackTrace()} which is significantly slower due to
044 * examination of every virtual frame of execution.
045 * </p>
046 */
047public final class StackLocator {
048
049    private static PrivateSecurityManager SECURITY_MANAGER;
050
051    // Checkstyle Suppress: the lower-case 'u' ticks off CheckStyle...
052    // CHECKSTYLE:OFF
053    static final int JDK_7u25_OFFSET;
054    // CHECKSTYLE:OFF
055
056    private static final Method GET_CALLER_CLASS;
057
058    private static final StackLocator INSTANCE;
059
060    static {
061        Method getCallerClass;
062        int java7u25CompensationOffset = 0;
063        try {
064            final Class<?> sunReflectionClass = LoaderUtil.loadClass("sun.reflect.Reflection");
065            getCallerClass = sunReflectionClass.getDeclaredMethod("getCallerClass", int.class);
066            Object o = getCallerClass.invoke(null, 0);
067            getCallerClass.invoke(null, 0);
068            if (o == null || o != sunReflectionClass) {
069                getCallerClass = null;
070                java7u25CompensationOffset = -1;
071            } else {
072                o = getCallerClass.invoke(null, 1);
073                if (o == sunReflectionClass) {
074                    System.out.println("WARNING: Java 1.7.0_25 is in use which has a broken implementation of Reflection.getCallerClass(). " +
075                        " Please consider upgrading to Java 1.7.0_40 or later.");
076                    java7u25CompensationOffset = 1;
077                }
078            }
079        } catch (final Exception | LinkageError e) {
080            System.out.println("WARNING: sun.reflect.Reflection.getCallerClass is not supported. This will impact performance.");
081            getCallerClass = null;
082            java7u25CompensationOffset = -1;
083        }
084
085        GET_CALLER_CLASS = getCallerClass;
086        JDK_7u25_OFFSET = java7u25CompensationOffset;
087
088        INSTANCE = new StackLocator();
089    }
090
091    public static StackLocator getInstance() {
092        return INSTANCE;
093    }
094
095    private StackLocator() {
096    }
097
098    // TODO: return Object.class instead of null (though it will have a null ClassLoader)
099    // (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}