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