001/*
002 * Copyright 2002-2019 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.core;
018
019import java.io.IOException;
020import java.io.InputStream;
021import java.lang.reflect.Constructor;
022import java.lang.reflect.Executable;
023import java.lang.reflect.Method;
024import java.util.Collections;
025import java.util.Map;
026import java.util.concurrent.ConcurrentHashMap;
027
028import org.apache.commons.logging.Log;
029import org.apache.commons.logging.LogFactory;
030
031import org.springframework.asm.ClassReader;
032import org.springframework.asm.ClassVisitor;
033import org.springframework.asm.Label;
034import org.springframework.asm.MethodVisitor;
035import org.springframework.asm.Opcodes;
036import org.springframework.asm.SpringAsmInfo;
037import org.springframework.asm.Type;
038import org.springframework.lang.Nullable;
039import org.springframework.util.ClassUtils;
040
041/**
042 * Implementation of {@link ParameterNameDiscoverer} that uses the LocalVariableTable
043 * information in the method attributes to discover parameter names. Returns
044 * {@code null} if the class file was compiled without debug information.
045 *
046 * <p>Uses ObjectWeb's ASM library for analyzing class files. Each discoverer instance
047 * caches the ASM discovered information for each introspected Class, in a thread-safe
048 * manner. It is recommended to reuse ParameterNameDiscoverer instances as far as possible.
049 *
050 * @author Adrian Colyer
051 * @author Costin Leau
052 * @author Juergen Hoeller
053 * @author Chris Beams
054 * @author Sam Brannen
055 * @since 2.0
056 */
057public class LocalVariableTableParameterNameDiscoverer implements ParameterNameDiscoverer {
058
059        private static final Log logger = LogFactory.getLog(LocalVariableTableParameterNameDiscoverer.class);
060
061        // marker object for classes that do not have any debug info
062        private static final Map<Executable, String[]> NO_DEBUG_INFO_MAP = Collections.emptyMap();
063
064        // the cache uses a nested index (value is a map) to keep the top level cache relatively small in size
065        private final Map<Class<?>, Map<Executable, String[]>> parameterNamesCache = new ConcurrentHashMap<>(32);
066
067
068        @Override
069        @Nullable
070        public String[] getParameterNames(Method method) {
071                Method originalMethod = BridgeMethodResolver.findBridgedMethod(method);
072                return doGetParameterNames(originalMethod);
073        }
074
075        @Override
076        @Nullable
077        public String[] getParameterNames(Constructor<?> ctor) {
078                return doGetParameterNames(ctor);
079        }
080
081        @Nullable
082        private String[] doGetParameterNames(Executable executable) {
083                Class<?> declaringClass = executable.getDeclaringClass();
084                Map<Executable, String[]> map = this.parameterNamesCache.computeIfAbsent(declaringClass, this::inspectClass);
085                return (map != NO_DEBUG_INFO_MAP ? map.get(executable) : null);
086        }
087
088        /**
089         * Inspects the target class.
090         * <p>Exceptions will be logged, and a marker map returned to indicate the
091         * lack of debug information.
092         */
093        private Map<Executable, String[]> inspectClass(Class<?> clazz) {
094                InputStream is = clazz.getResourceAsStream(ClassUtils.getClassFileName(clazz));
095                if (is == null) {
096                        // We couldn't load the class file, which is not fatal as it
097                        // simply means this method of discovering parameter names won't work.
098                        if (logger.isDebugEnabled()) {
099                                logger.debug("Cannot find '.class' file for class [" + clazz +
100                                                "] - unable to determine constructor/method parameter names");
101                        }
102                        return NO_DEBUG_INFO_MAP;
103                }
104                try {
105                        ClassReader classReader = new ClassReader(is);
106                        Map<Executable, String[]> map = new ConcurrentHashMap<>(32);
107                        classReader.accept(new ParameterNameDiscoveringVisitor(clazz, map), 0);
108                        return map;
109                }
110                catch (IOException ex) {
111                        if (logger.isDebugEnabled()) {
112                                logger.debug("Exception thrown while reading '.class' file for class [" + clazz +
113                                                "] - unable to determine constructor/method parameter names", ex);
114                        }
115                }
116                catch (IllegalArgumentException ex) {
117                        if (logger.isDebugEnabled()) {
118                                logger.debug("ASM ClassReader failed to parse class file [" + clazz +
119                                                "], probably due to a new Java class file version that isn't supported yet " +
120                                                "- unable to determine constructor/method parameter names", ex);
121                        }
122                }
123                finally {
124                        try {
125                                is.close();
126                        }
127                        catch (IOException ex) {
128                                // ignore
129                        }
130                }
131                return NO_DEBUG_INFO_MAP;
132        }
133
134
135        /**
136         * Helper class that inspects all methods and constructors and then
137         * attempts to find the parameter names for the given {@link Executable}.
138         */
139        private static class ParameterNameDiscoveringVisitor extends ClassVisitor {
140
141                private static final String STATIC_CLASS_INIT = "<clinit>";
142
143                private final Class<?> clazz;
144
145                private final Map<Executable, String[]> executableMap;
146
147                public ParameterNameDiscoveringVisitor(Class<?> clazz, Map<Executable, String[]> executableMap) {
148                        super(SpringAsmInfo.ASM_VERSION);
149                        this.clazz = clazz;
150                        this.executableMap = executableMap;
151                }
152
153                @Override
154                @Nullable
155                public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
156                        // exclude synthetic + bridged && static class initialization
157                        if (!isSyntheticOrBridged(access) && !STATIC_CLASS_INIT.equals(name)) {
158                                return new LocalVariableTableVisitor(this.clazz, this.executableMap, name, desc, isStatic(access));
159                        }
160                        return null;
161                }
162
163                private static boolean isSyntheticOrBridged(int access) {
164                        return (((access & Opcodes.ACC_SYNTHETIC) | (access & Opcodes.ACC_BRIDGE)) > 0);
165                }
166
167                private static boolean isStatic(int access) {
168                        return ((access & Opcodes.ACC_STATIC) > 0);
169                }
170        }
171
172
173        private static class LocalVariableTableVisitor extends MethodVisitor {
174
175                private static final String CONSTRUCTOR = "<init>";
176
177                private final Class<?> clazz;
178
179                private final Map<Executable, String[]> executableMap;
180
181                private final String name;
182
183                private final Type[] args;
184
185                private final String[] parameterNames;
186
187                private final boolean isStatic;
188
189                private boolean hasLvtInfo = false;
190
191                /*
192                 * The nth entry contains the slot index of the LVT table entry holding the
193                 * argument name for the nth parameter.
194                 */
195                private final int[] lvtSlotIndex;
196
197                public LocalVariableTableVisitor(Class<?> clazz, Map<Executable, String[]> map, String name, String desc, boolean isStatic) {
198                        super(SpringAsmInfo.ASM_VERSION);
199                        this.clazz = clazz;
200                        this.executableMap = map;
201                        this.name = name;
202                        this.args = Type.getArgumentTypes(desc);
203                        this.parameterNames = new String[this.args.length];
204                        this.isStatic = isStatic;
205                        this.lvtSlotIndex = computeLvtSlotIndices(isStatic, this.args);
206                }
207
208                @Override
209                public void visitLocalVariable(String name, String description, String signature, Label start, Label end, int index) {
210                        this.hasLvtInfo = true;
211                        for (int i = 0; i < this.lvtSlotIndex.length; i++) {
212                                if (this.lvtSlotIndex[i] == index) {
213                                        this.parameterNames[i] = name;
214                                }
215                        }
216                }
217
218                @Override
219                public void visitEnd() {
220                        if (this.hasLvtInfo || (this.isStatic && this.parameterNames.length == 0)) {
221                                // visitLocalVariable will never be called for static no args methods
222                                // which doesn't use any local variables.
223                                // This means that hasLvtInfo could be false for that kind of methods
224                                // even if the class has local variable info.
225                                this.executableMap.put(resolveExecutable(), this.parameterNames);
226                        }
227                }
228
229                private Executable resolveExecutable() {
230                        ClassLoader loader = this.clazz.getClassLoader();
231                        Class<?>[] argTypes = new Class<?>[this.args.length];
232                        for (int i = 0; i < this.args.length; i++) {
233                                argTypes[i] = ClassUtils.resolveClassName(this.args[i].getClassName(), loader);
234                        }
235                        try {
236                                if (CONSTRUCTOR.equals(this.name)) {
237                                        return this.clazz.getDeclaredConstructor(argTypes);
238                                }
239                                return this.clazz.getDeclaredMethod(this.name, argTypes);
240                        }
241                        catch (NoSuchMethodException ex) {
242                                throw new IllegalStateException("Method [" + this.name +
243                                                "] was discovered in the .class file but cannot be resolved in the class object", ex);
244                        }
245                }
246
247                private static int[] computeLvtSlotIndices(boolean isStatic, Type[] paramTypes) {
248                        int[] lvtIndex = new int[paramTypes.length];
249                        int nextIndex = (isStatic ? 0 : 1);
250                        for (int i = 0; i < paramTypes.length; i++) {
251                                lvtIndex[i] = nextIndex;
252                                if (isWideType(paramTypes[i])) {
253                                        nextIndex += 2;
254                                }
255                                else {
256                                        nextIndex++;
257                                }
258                        }
259                        return lvtIndex;
260                }
261
262                private static boolean isWideType(Type aType) {
263                        // float is not a wide type
264                        return (aType == Type.LONG_TYPE || aType == Type.DOUBLE_TYPE);
265                }
266        }
267
268}