You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

BcelObjectType.java 35KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015
  1. /* *******************************************************************
  2. * Copyright (c) 2002 Contributors
  3. * All rights reserved.
  4. * This program and the accompanying materials are made available
  5. * under the terms of the Eclipse Public License v1.0
  6. * which accompanies this distribution and is available at
  7. * http://www.eclipse.org/legal/epl-v10.html
  8. *
  9. * Contributors:
  10. * PARC initial implementation
  11. * RonBodkin/AndyClement optimizations for memory consumption/speed
  12. * ******************************************************************/
  13. package org.aspectj.weaver.bcel;
  14. import java.io.PrintStream;
  15. import java.lang.ref.WeakReference;
  16. import java.lang.reflect.Modifier;
  17. import java.util.ArrayList;
  18. import java.util.Arrays;
  19. import java.util.Collection;
  20. import java.util.Collections;
  21. import java.util.Iterator;
  22. import java.util.List;
  23. import java.util.Set;
  24. import org.aspectj.apache.bcel.classfile.Attribute;
  25. import org.aspectj.apache.bcel.classfile.AttributeUtils;
  26. import org.aspectj.apache.bcel.classfile.ConstantClass;
  27. import org.aspectj.apache.bcel.classfile.ConstantPool;
  28. import org.aspectj.apache.bcel.classfile.EnclosingMethod;
  29. import org.aspectj.apache.bcel.classfile.Field;
  30. import org.aspectj.apache.bcel.classfile.InnerClass;
  31. import org.aspectj.apache.bcel.classfile.InnerClasses;
  32. import org.aspectj.apache.bcel.classfile.JavaClass;
  33. import org.aspectj.apache.bcel.classfile.Method;
  34. import org.aspectj.apache.bcel.classfile.Signature;
  35. import org.aspectj.apache.bcel.classfile.annotation.AnnotationGen;
  36. import org.aspectj.apache.bcel.classfile.annotation.EnumElementValue;
  37. import org.aspectj.apache.bcel.classfile.annotation.NameValuePair;
  38. import org.aspectj.asm.AsmManager;
  39. import org.aspectj.bridge.IMessageHandler;
  40. import org.aspectj.bridge.MessageUtil;
  41. import org.aspectj.util.GenericSignature;
  42. import org.aspectj.util.GenericSignature.FormalTypeParameter;
  43. import org.aspectj.weaver.AbstractReferenceTypeDelegate;
  44. import org.aspectj.weaver.AjAttribute;
  45. import org.aspectj.weaver.AjcMemberMaker;
  46. import org.aspectj.weaver.AnnotationAJ;
  47. import org.aspectj.weaver.AnnotationTargetKind;
  48. import org.aspectj.weaver.BCException;
  49. import org.aspectj.weaver.BindingScope;
  50. import org.aspectj.weaver.ConcreteTypeMunger;
  51. import org.aspectj.weaver.ISourceContext;
  52. import org.aspectj.weaver.ReferenceType;
  53. import org.aspectj.weaver.ResolvedMember;
  54. import org.aspectj.weaver.ResolvedPointcutDefinition;
  55. import org.aspectj.weaver.ResolvedType;
  56. import org.aspectj.weaver.SourceContextImpl;
  57. import org.aspectj.weaver.TypeVariable;
  58. import org.aspectj.weaver.UnresolvedType;
  59. import org.aspectj.weaver.WeaverStateInfo;
  60. import org.aspectj.weaver.World;
  61. import org.aspectj.weaver.bcel.BcelGenericSignatureToTypeXConverter.GenericSignatureFormatException;
  62. import org.aspectj.weaver.patterns.Declare;
  63. import org.aspectj.weaver.patterns.DeclareErrorOrWarning;
  64. import org.aspectj.weaver.patterns.DeclarePrecedence;
  65. import org.aspectj.weaver.patterns.FormalBinding;
  66. import org.aspectj.weaver.patterns.IScope;
  67. import org.aspectj.weaver.patterns.PerClause;
  68. public class BcelObjectType extends AbstractReferenceTypeDelegate {
  69. public JavaClass javaClass;
  70. private boolean artificial; // Was the BcelObject built from an artificial set of bytes? Or from the real ondisk stuff?
  71. private LazyClassGen lazyClassGen = null; // set lazily if it's an aspect
  72. private int modifiers;
  73. private String className;
  74. private String superclassSignature;
  75. private String superclassName;
  76. private String[] interfaceSignatures;
  77. private ResolvedMember[] fields = null;
  78. private ResolvedMember[] methods = null;
  79. private ResolvedType[] annotationTypes = null;
  80. private AnnotationAJ[] annotations = null;
  81. private TypeVariable[] typeVars = null;
  82. private String retentionPolicy;
  83. private AnnotationTargetKind[] annotationTargetKinds;
  84. // Aspect related stuff (pointcuts *could* be in a java class)
  85. private AjAttribute.WeaverVersionInfo wvInfo = AjAttribute.WeaverVersionInfo.UNKNOWN;
  86. private ResolvedPointcutDefinition[] pointcuts = null;
  87. private ResolvedMember[] privilegedAccess = null;
  88. private WeaverStateInfo weaverState = null;
  89. private PerClause perClause = null;
  90. private List<ConcreteTypeMunger> typeMungers = Collections.emptyList();
  91. private List<Declare> declares = Collections.emptyList();
  92. private GenericSignature.FormalTypeParameter[] formalsForResolution = null;
  93. private String declaredSignature = null;
  94. private boolean hasBeenWoven = false;
  95. private boolean isGenericType = false;
  96. private boolean isInterface;
  97. private boolean isEnum;
  98. private boolean isAnnotation;
  99. private boolean isAnonymous;
  100. private boolean isNested;
  101. private boolean isObject = false; // set upon construction
  102. private boolean isAnnotationStyleAspect = false;// set upon construction
  103. private boolean isCodeStyleAspect = false; // not redundant with field
  104. // above!
  105. private WeakReference<ResolvedType> superTypeReference = new WeakReference<ResolvedType>(null);
  106. private WeakReference<ResolvedType[]> superInterfaceReferences = new WeakReference<ResolvedType[]>(null);
  107. private int bitflag = 0x0000;
  108. // discovery bits
  109. private static final int DISCOVERED_ANNOTATION_RETENTION_POLICY = 0x0001;
  110. private static final int UNPACKED_GENERIC_SIGNATURE = 0x0002;
  111. private static final int UNPACKED_AJATTRIBUTES = 0x0004; // see note(1)
  112. // below
  113. private static final int DISCOVERED_ANNOTATION_TARGET_KINDS = 0x0008;
  114. private static final int DISCOVERED_DECLARED_SIGNATURE = 0x0010;
  115. private static final int DISCOVERED_WHETHER_ANNOTATION_STYLE = 0x0020;
  116. private static final int ANNOTATION_UNPACK_IN_PROGRESS = 0x0100;
  117. private static final String[] NO_INTERFACE_SIGS = new String[] {};
  118. /*
  119. * Notes: note(1): in some cases (perclause inheritance) we encounter unpacked state when calling getPerClause
  120. *
  121. * note(2): A BcelObjectType is 'damaged' if it has been modified from what was original constructed from the bytecode. This
  122. * currently happens if the parents are modified or an annotation is added - ideally BcelObjectType should be immutable but
  123. * that's a bigger piece of work. XXX
  124. */
  125. BcelObjectType(ReferenceType resolvedTypeX, JavaClass javaClass, boolean artificial, boolean exposedToWeaver) {
  126. super(resolvedTypeX, exposedToWeaver);
  127. this.javaClass = javaClass;
  128. this.artificial = artificial;
  129. initializeFromJavaclass();
  130. // ATAJ: set the delegate right now for @AJ pointcut, else it is done
  131. // too late to lookup
  132. // @AJ pc refs annotation in class hierarchy
  133. resolvedTypeX.setDelegate(this);
  134. ISourceContext sourceContext = resolvedTypeX.getSourceContext();
  135. if (sourceContext == SourceContextImpl.UNKNOWN_SOURCE_CONTEXT) {
  136. sourceContext = new SourceContextImpl(this);
  137. setSourceContext(sourceContext);
  138. }
  139. // this should only ever be java.lang.Object which is
  140. // the only class in Java-1.4 with no superclasses
  141. isObject = (javaClass.getSuperclassNameIndex() == 0);
  142. ensureAspectJAttributesUnpacked();
  143. // if (sourceContext instanceof SourceContextImpl) {
  144. // ((SourceContextImpl)sourceContext).setSourceFileName(javaClass.
  145. // getSourceFileName());
  146. // }
  147. setSourcefilename(javaClass.getSourceFileName());
  148. }
  149. // repeat initialization
  150. public void setJavaClass(JavaClass newclass, boolean artificial) {
  151. this.javaClass = newclass;
  152. this.artificial = artificial;
  153. resetState();
  154. initializeFromJavaclass();
  155. }
  156. @Override
  157. public boolean isCacheable() {
  158. return true;
  159. }
  160. private void initializeFromJavaclass() {
  161. isInterface = javaClass.isInterface();
  162. isEnum = javaClass.isEnum();
  163. isAnnotation = javaClass.isAnnotation();
  164. isAnonymous = javaClass.isAnonymous();
  165. isNested = javaClass.isNested();
  166. modifiers = javaClass.getModifiers();
  167. superclassName = javaClass.getSuperclassName();
  168. className = javaClass.getClassName();
  169. cachedGenericClassTypeSignature = null;
  170. }
  171. // --- getters
  172. // Java related
  173. public boolean isInterface() {
  174. return isInterface;
  175. }
  176. public boolean isEnum() {
  177. return isEnum;
  178. }
  179. public boolean isAnnotation() {
  180. return isAnnotation;
  181. }
  182. public boolean isAnonymous() {
  183. return isAnonymous;
  184. }
  185. public boolean isNested() {
  186. return isNested;
  187. }
  188. public int getModifiers() {
  189. return modifiers;
  190. }
  191. /**
  192. * Must take into account generic signature
  193. */
  194. public ResolvedType getSuperclass() {
  195. if (isObject) {
  196. return null;
  197. }
  198. ResolvedType supertype = superTypeReference.get();
  199. if (supertype == null) {
  200. ensureGenericSignatureUnpacked();
  201. if (superclassSignature == null) {
  202. if (superclassName == null) {
  203. superclassName = javaClass.getSuperclassName();
  204. }
  205. superclassSignature = getResolvedTypeX().getWorld().resolve(UnresolvedType.forName(superclassName)).getSignature();
  206. }
  207. World world = getResolvedTypeX().getWorld();
  208. supertype = world.resolve(UnresolvedType.forSignature(superclassSignature));
  209. superTypeReference = new WeakReference<ResolvedType>(supertype);
  210. }
  211. return supertype;
  212. }
  213. public World getWorld() {
  214. return getResolvedTypeX().getWorld();
  215. }
  216. /**
  217. * Retrieves the declared interfaces - this allows for the generic signature on a type. If specified then the generic signature
  218. * is used to work out the types - this gets around the results of erasure when the class was originally compiled.
  219. */
  220. public ResolvedType[] getDeclaredInterfaces() {
  221. ResolvedType[] cachedInterfaceTypes = superInterfaceReferences.get();
  222. if (cachedInterfaceTypes == null) {
  223. ensureGenericSignatureUnpacked();
  224. ResolvedType[] interfaceTypes = null;
  225. if (interfaceSignatures == null) {
  226. String[] names = javaClass.getInterfaceNames();
  227. if (names.length == 0) {
  228. interfaceSignatures = NO_INTERFACE_SIGS;
  229. interfaceTypes = ResolvedType.NONE;
  230. } else {
  231. interfaceSignatures = new String[names.length];
  232. interfaceTypes = new ResolvedType[names.length];
  233. for (int i = 0, len = names.length; i < len; i++) {
  234. interfaceTypes[i] = getResolvedTypeX().getWorld().resolve(UnresolvedType.forName(names[i]));
  235. interfaceSignatures[i] = interfaceTypes[i].getSignature();
  236. }
  237. }
  238. } else {
  239. interfaceTypes = new ResolvedType[interfaceSignatures.length];
  240. for (int i = 0, len = interfaceSignatures.length; i < len; i++) {
  241. interfaceTypes[i] = getResolvedTypeX().getWorld().resolve(UnresolvedType.forSignature(interfaceSignatures[i]));
  242. }
  243. }
  244. superInterfaceReferences = new WeakReference<ResolvedType[]>(interfaceTypes);
  245. return interfaceTypes;
  246. } else {
  247. return cachedInterfaceTypes;
  248. }
  249. }
  250. public ResolvedMember[] getDeclaredMethods() {
  251. ensureGenericSignatureUnpacked();
  252. if (methods == null) {
  253. Method[] ms = javaClass.getMethods();
  254. ResolvedMember[] newMethods = new ResolvedMember[ms.length];
  255. for (int i = ms.length - 1; i >= 0; i--) {
  256. newMethods[i] = new BcelMethod(this, ms[i]);
  257. }
  258. methods = newMethods;
  259. }
  260. return methods;
  261. }
  262. public ResolvedMember[] getDeclaredFields() {
  263. ensureGenericSignatureUnpacked();
  264. if (fields == null) {
  265. Field[] fs = javaClass.getFields();
  266. ResolvedMember[] newfields = new ResolvedMember[fs.length];
  267. for (int i = 0, len = fs.length; i < len; i++) {
  268. newfields[i] = new BcelField(this, fs[i]);
  269. }
  270. fields = newfields;
  271. }
  272. return fields;
  273. }
  274. public TypeVariable[] getTypeVariables() {
  275. if (!isGeneric()) {
  276. return TypeVariable.NONE;
  277. }
  278. if (typeVars == null) {
  279. GenericSignature.ClassSignature classSig = getGenericClassTypeSignature();
  280. typeVars = new TypeVariable[classSig.formalTypeParameters.length];
  281. for (int i = 0; i < typeVars.length; i++) {
  282. GenericSignature.FormalTypeParameter ftp = classSig.formalTypeParameters[i];
  283. try {
  284. typeVars[i] = BcelGenericSignatureToTypeXConverter.formalTypeParameter2TypeVariable(ftp,
  285. classSig.formalTypeParameters, getResolvedTypeX().getWorld());
  286. } catch (GenericSignatureFormatException e) {
  287. // this is a development bug, so fail fast with good info
  288. throw new IllegalStateException("While getting the type variables for type " + this.toString()
  289. + " with generic signature " + classSig + " the following error condition was detected: "
  290. + e.getMessage());
  291. }
  292. }
  293. }
  294. return typeVars;
  295. }
  296. public Collection<ConcreteTypeMunger> getTypeMungers() {
  297. return typeMungers;
  298. }
  299. public Collection<Declare> getDeclares() {
  300. return declares;
  301. }
  302. public Collection<ResolvedMember> getPrivilegedAccesses() {
  303. if (privilegedAccess == null) {
  304. return Collections.emptyList();
  305. }
  306. return Arrays.asList(privilegedAccess);
  307. }
  308. public ResolvedMember[] getDeclaredPointcuts() {
  309. return pointcuts;
  310. }
  311. public boolean isAspect() {
  312. return perClause != null;
  313. }
  314. /**
  315. * Check if the type is an @AJ aspect (no matter if used from an LTW point of view). Such aspects are annotated with @Aspect
  316. *
  317. * @return true for @AJ aspect
  318. */
  319. public boolean isAnnotationStyleAspect() {
  320. if ((bitflag & DISCOVERED_WHETHER_ANNOTATION_STYLE) == 0) {
  321. bitflag |= DISCOVERED_WHETHER_ANNOTATION_STYLE;
  322. isAnnotationStyleAspect = !isCodeStyleAspect && hasAnnotation(AjcMemberMaker.ASPECT_ANNOTATION);
  323. }
  324. return isAnnotationStyleAspect;
  325. }
  326. /**
  327. * Process any org.aspectj.weaver attributes stored against the class.
  328. */
  329. private void ensureAspectJAttributesUnpacked() {
  330. if ((bitflag & UNPACKED_AJATTRIBUTES) != 0) {
  331. return;
  332. }
  333. bitflag |= UNPACKED_AJATTRIBUTES;
  334. IMessageHandler msgHandler = getResolvedTypeX().getWorld().getMessageHandler();
  335. // Pass in empty list that can store things for readAj5 to process
  336. List<AjAttribute> l = null;
  337. try {
  338. l = Utility.readAjAttributes(className, javaClass.getAttributes(), getResolvedTypeX().getSourceContext(),
  339. getResolvedTypeX().getWorld(), AjAttribute.WeaverVersionInfo.UNKNOWN,
  340. new BcelConstantPoolReader(javaClass.getConstantPool()));
  341. } catch (RuntimeException re) {
  342. throw new RuntimeException("Problem processing attributes in " + javaClass.getFileName(), re);
  343. }
  344. List<ResolvedPointcutDefinition> pointcuts = new ArrayList<ResolvedPointcutDefinition>();
  345. typeMungers = new ArrayList<ConcreteTypeMunger>();
  346. declares = new ArrayList<Declare>();
  347. processAttributes(l, pointcuts, false);
  348. ReferenceType type = getResolvedTypeX();
  349. AsmManager asmManager = ((BcelWorld) type.getWorld()).getModelAsAsmManager();
  350. l = AtAjAttributes.readAj5ClassAttributes(asmManager, javaClass, type, type.getSourceContext(), msgHandler,
  351. isCodeStyleAspect);
  352. AjAttribute.Aspect deferredAspectAttribute = processAttributes(l, pointcuts, true);
  353. if (pointcuts.size() == 0) {
  354. this.pointcuts = ResolvedPointcutDefinition.NO_POINTCUTS;
  355. } else {
  356. this.pointcuts = pointcuts.toArray(new ResolvedPointcutDefinition[pointcuts.size()]);
  357. }
  358. resolveAnnotationDeclares(l);
  359. if (deferredAspectAttribute != null) {
  360. // we can finally process the aspect and its associated perclause...
  361. perClause = deferredAspectAttribute.reifyFromAtAspectJ(this.getResolvedTypeX());
  362. }
  363. if (isAspect() && !Modifier.isAbstract(getModifiers()) && isGeneric()) {
  364. msgHandler.handleMessage(MessageUtil.error("The generic aspect '" + getResolvedTypeX().getName()
  365. + "' must be declared abstract", getResolvedTypeX().getSourceLocation()));
  366. }
  367. }
  368. private AjAttribute.Aspect processAttributes(List<AjAttribute> attributeList, List<ResolvedPointcutDefinition> pointcuts,
  369. boolean fromAnnotations) {
  370. AjAttribute.Aspect deferredAspectAttribute = null;
  371. for (AjAttribute a : attributeList) {
  372. if (a instanceof AjAttribute.Aspect) {
  373. if (fromAnnotations) {
  374. deferredAspectAttribute = (AjAttribute.Aspect) a;
  375. } else {
  376. perClause = ((AjAttribute.Aspect) a).reify(this.getResolvedTypeX());
  377. isCodeStyleAspect = true;
  378. }
  379. } else if (a instanceof AjAttribute.PointcutDeclarationAttribute) {
  380. pointcuts.add(((AjAttribute.PointcutDeclarationAttribute) a).reify());
  381. } else if (a instanceof AjAttribute.WeaverState) {
  382. weaverState = ((AjAttribute.WeaverState) a).reify();
  383. } else if (a instanceof AjAttribute.TypeMunger) {
  384. typeMungers.add(((AjAttribute.TypeMunger) a).reify(getResolvedTypeX().getWorld(), getResolvedTypeX()));
  385. } else if (a instanceof AjAttribute.DeclareAttribute) {
  386. declares.add(((AjAttribute.DeclareAttribute) a).getDeclare());
  387. } else if (a instanceof AjAttribute.PrivilegedAttribute) {
  388. AjAttribute.PrivilegedAttribute privAttribute = (AjAttribute.PrivilegedAttribute) a;
  389. privilegedAccess = privAttribute.getAccessedMembers();
  390. } else if (a instanceof AjAttribute.SourceContextAttribute) {
  391. if (getResolvedTypeX().getSourceContext() instanceof SourceContextImpl) {
  392. AjAttribute.SourceContextAttribute sca = (AjAttribute.SourceContextAttribute) a;
  393. ((SourceContextImpl) getResolvedTypeX().getSourceContext()).configureFromAttribute(sca.getSourceFileName(),
  394. sca.getLineBreaks());
  395. setSourcefilename(sca.getSourceFileName());
  396. }
  397. } else if (a instanceof AjAttribute.WeaverVersionInfo) {
  398. // Set the weaver version used to build this type
  399. wvInfo = (AjAttribute.WeaverVersionInfo) a;
  400. } else {
  401. throw new BCException("bad attribute " + a);
  402. }
  403. }
  404. return deferredAspectAttribute;
  405. }
  406. /**
  407. * Extra processing step needed because declares that come from annotations are not pre-resolved. We can't do the resolution
  408. * until *after* the pointcuts have been resolved.
  409. */
  410. private void resolveAnnotationDeclares(List<AjAttribute> attributeList) {
  411. FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0];
  412. IScope bindingScope = new BindingScope(getResolvedTypeX(), getResolvedTypeX().getSourceContext(), bindings);
  413. for (Iterator<AjAttribute> iter = attributeList.iterator(); iter.hasNext();) {
  414. AjAttribute a = iter.next();
  415. if (a instanceof AjAttribute.DeclareAttribute) {
  416. Declare decl = (((AjAttribute.DeclareAttribute) a).getDeclare());
  417. if (decl instanceof DeclareErrorOrWarning) {
  418. decl.resolve(bindingScope);
  419. } else if (decl instanceof DeclarePrecedence) {
  420. ((DeclarePrecedence) decl).setScopeForResolution(bindingScope);
  421. }
  422. }
  423. }
  424. }
  425. public PerClause getPerClause() {
  426. ensureAspectJAttributesUnpacked();
  427. return perClause;
  428. }
  429. public JavaClass getJavaClass() {
  430. return javaClass;
  431. }
  432. public boolean isArtificial() {
  433. return artificial;
  434. }
  435. public void resetState() {
  436. if (javaClass == null) {
  437. // we might store the classname and allow reloading?
  438. // At this point we are relying on the world to not evict if it
  439. // might want to reweave multiple times
  440. throw new BCException("can't weave evicted type");
  441. }
  442. bitflag = 0x0000;
  443. this.annotationTypes = null;
  444. this.annotations = null;
  445. this.interfaceSignatures = null;
  446. this.superclassSignature = null;
  447. this.superclassName = null;
  448. this.fields = null;
  449. this.methods = null;
  450. this.pointcuts = null;
  451. this.perClause = null;
  452. this.weaverState = null;
  453. this.lazyClassGen = null;
  454. hasBeenWoven = false;
  455. isObject = (javaClass.getSuperclassNameIndex() == 0);
  456. isAnnotationStyleAspect = false;
  457. ensureAspectJAttributesUnpacked();
  458. }
  459. public void finishedWith() {
  460. // memory usage experiments....
  461. // this.interfaces = null;
  462. // this.superClass = null;
  463. // this.fields = null;
  464. // this.methods = null;
  465. // this.pointcuts = null;
  466. // this.perClause = null;
  467. // this.weaverState = null;
  468. // this.lazyClassGen = null;
  469. // this next line frees up memory, but need to understand incremental
  470. // implications
  471. // before leaving it in.
  472. // getResolvedTypeX().setSourceContext(null);
  473. }
  474. public WeaverStateInfo getWeaverState() {
  475. return weaverState;
  476. }
  477. void setWeaverState(WeaverStateInfo weaverState) {
  478. this.weaverState = weaverState;
  479. }
  480. public void printWackyStuff(PrintStream out) {
  481. if (typeMungers.size() > 0) {
  482. out.println(" TypeMungers: " + typeMungers);
  483. }
  484. if (declares.size() > 0) {
  485. out.println(" declares: " + declares);
  486. }
  487. }
  488. /**
  489. * Return the lazyClassGen associated with this type. For aspect types, this value will be cached, since it is used to inline
  490. * advice. For non-aspect types, this lazyClassGen is always newly constructed.
  491. */
  492. public LazyClassGen getLazyClassGen() {
  493. LazyClassGen ret = lazyClassGen;
  494. if (ret == null) {
  495. // System.err.println("creating lazy class gen for: " + this);
  496. ret = new LazyClassGen(this);
  497. // ret.print(System.err);
  498. // System.err.println("made LCG from : " +
  499. // this.getJavaClass().getSuperclassName );
  500. if (isAspect()) {
  501. lazyClassGen = ret;
  502. }
  503. }
  504. return ret;
  505. }
  506. public boolean isSynthetic() {
  507. return getResolvedTypeX().isSynthetic();
  508. }
  509. public AjAttribute.WeaverVersionInfo getWeaverVersionAttribute() {
  510. return wvInfo;
  511. }
  512. // -- annotation related
  513. public ResolvedType[] getAnnotationTypes() {
  514. ensureAnnotationsUnpacked();
  515. return annotationTypes;
  516. }
  517. public AnnotationAJ[] getAnnotations() {
  518. ensureAnnotationsUnpacked();
  519. return annotations;
  520. }
  521. public boolean hasAnnotations() {
  522. ensureAnnotationsUnpacked();
  523. return annotations.length != 0;
  524. }
  525. public boolean hasAnnotation(UnresolvedType ofType) {
  526. // Due to re-entrancy we may be in the middle of unpacking the annotations already... in which case use this slow
  527. // alternative until the stack unwinds itself
  528. if (isUnpackingAnnotations()) {
  529. AnnotationGen annos[] = javaClass.getAnnotations();
  530. if (annos == null || annos.length == 0) {
  531. return false;
  532. } else {
  533. String lookingForSignature = ofType.getSignature();
  534. for (int a = 0; a < annos.length; a++) {
  535. AnnotationGen annotation = annos[a];
  536. if (lookingForSignature.equals(annotation.getTypeSignature())) {
  537. return true;
  538. }
  539. }
  540. }
  541. return false;
  542. }
  543. ensureAnnotationsUnpacked();
  544. for (int i = 0, max = annotationTypes.length; i < max; i++) {
  545. UnresolvedType ax = annotationTypes[i];
  546. if (ax == null) {
  547. throw new RuntimeException("Annotation entry " + i + " on type " + this.getResolvedTypeX().getName() + " is null!");
  548. }
  549. if (ax.equals(ofType)) {
  550. return true;
  551. }
  552. }
  553. return false;
  554. }
  555. public boolean isAnnotationWithRuntimeRetention() {
  556. return (getRetentionPolicy() == null ? false : getRetentionPolicy().equals("RUNTIME"));
  557. }
  558. public String getRetentionPolicy() {
  559. if ((bitflag & DISCOVERED_ANNOTATION_RETENTION_POLICY) == 0) {
  560. bitflag |= DISCOVERED_ANNOTATION_RETENTION_POLICY;
  561. retentionPolicy = null; // null means we have no idea
  562. if (isAnnotation()) {
  563. ensureAnnotationsUnpacked();
  564. for (int i = annotations.length - 1; i >= 0; i--) {
  565. AnnotationAJ ax = annotations[i];
  566. if (ax.getTypeName().equals(UnresolvedType.AT_RETENTION.getName())) {
  567. List<NameValuePair> values = ((BcelAnnotation) ax).getBcelAnnotation().getValues();
  568. for (Iterator<NameValuePair> it = values.iterator(); it.hasNext();) {
  569. NameValuePair element = it.next();
  570. EnumElementValue v = (EnumElementValue) element.getValue();
  571. retentionPolicy = v.getEnumValueString();
  572. return retentionPolicy;
  573. }
  574. }
  575. }
  576. }
  577. }
  578. return retentionPolicy;
  579. }
  580. public boolean canAnnotationTargetType() {
  581. AnnotationTargetKind[] targetKinds = getAnnotationTargetKinds();
  582. if (targetKinds == null) {
  583. return true;
  584. }
  585. for (int i = 0; i < targetKinds.length; i++) {
  586. if (targetKinds[i].equals(AnnotationTargetKind.TYPE)) {
  587. return true;
  588. }
  589. }
  590. return false;
  591. }
  592. public AnnotationTargetKind[] getAnnotationTargetKinds() {
  593. if ((bitflag & DISCOVERED_ANNOTATION_TARGET_KINDS) != 0) {
  594. return annotationTargetKinds;
  595. }
  596. bitflag |= DISCOVERED_ANNOTATION_TARGET_KINDS;
  597. annotationTargetKinds = null; // null means we have no idea or the
  598. // @Target annotation hasn't been used
  599. List<AnnotationTargetKind> targetKinds = new ArrayList<AnnotationTargetKind>();
  600. if (isAnnotation()) {
  601. AnnotationAJ[] annotationsOnThisType = getAnnotations();
  602. for (int i = 0; i < annotationsOnThisType.length; i++) {
  603. AnnotationAJ a = annotationsOnThisType[i];
  604. if (a.getTypeName().equals(UnresolvedType.AT_TARGET.getName())) {
  605. Set<String> targets = a.getTargets();
  606. if (targets != null) {
  607. for (String targetKind : targets) {
  608. if (targetKind.equals("ANNOTATION_TYPE")) {
  609. targetKinds.add(AnnotationTargetKind.ANNOTATION_TYPE);
  610. } else if (targetKind.equals("CONSTRUCTOR")) {
  611. targetKinds.add(AnnotationTargetKind.CONSTRUCTOR);
  612. } else if (targetKind.equals("FIELD")) {
  613. targetKinds.add(AnnotationTargetKind.FIELD);
  614. } else if (targetKind.equals("LOCAL_VARIABLE")) {
  615. targetKinds.add(AnnotationTargetKind.LOCAL_VARIABLE);
  616. } else if (targetKind.equals("METHOD")) {
  617. targetKinds.add(AnnotationTargetKind.METHOD);
  618. } else if (targetKind.equals("PACKAGE")) {
  619. targetKinds.add(AnnotationTargetKind.PACKAGE);
  620. } else if (targetKind.equals("PARAMETER")) {
  621. targetKinds.add(AnnotationTargetKind.PARAMETER);
  622. } else if (targetKind.equals("TYPE")) {
  623. targetKinds.add(AnnotationTargetKind.TYPE);
  624. }
  625. }
  626. }
  627. }
  628. }
  629. if (!targetKinds.isEmpty()) {
  630. annotationTargetKinds = new AnnotationTargetKind[targetKinds.size()];
  631. return targetKinds.toArray(annotationTargetKinds);
  632. }
  633. }
  634. return annotationTargetKinds;
  635. }
  636. // --- unpacking methods
  637. private boolean isUnpackingAnnotations() {
  638. return (bitflag & ANNOTATION_UNPACK_IN_PROGRESS) != 0;
  639. }
  640. private void ensureAnnotationsUnpacked() {
  641. if (isUnpackingAnnotations()) {
  642. throw new BCException("Re-entered weaver instance whilst unpacking annotations on " + this.className);
  643. }
  644. if (annotationTypes == null) {
  645. try {
  646. bitflag |= ANNOTATION_UNPACK_IN_PROGRESS;
  647. AnnotationGen annos[] = javaClass.getAnnotations();
  648. if (annos == null || annos.length == 0) {
  649. annotationTypes = ResolvedType.NONE;
  650. annotations = AnnotationAJ.EMPTY_ARRAY;
  651. } else {
  652. World w = getResolvedTypeX().getWorld();
  653. annotationTypes = new ResolvedType[annos.length];
  654. annotations = new AnnotationAJ[annos.length];
  655. for (int i = 0; i < annos.length; i++) {
  656. AnnotationGen annotation = annos[i];
  657. String typeSignature = annotation.getTypeSignature();
  658. ResolvedType rType = w.resolve(UnresolvedType.forSignature(typeSignature));
  659. if (rType == null) {
  660. throw new RuntimeException("Whilst unpacking annotations on '" + getResolvedTypeX().getName()
  661. + "', failed to resolve type '" + typeSignature + "'");
  662. }
  663. annotationTypes[i] = rType;
  664. annotations[i] = new BcelAnnotation(annotation, rType);
  665. }
  666. }
  667. } finally {
  668. bitflag &= ~ANNOTATION_UNPACK_IN_PROGRESS;
  669. }
  670. }
  671. }
  672. // ---
  673. public String getDeclaredGenericSignature() {
  674. ensureGenericInfoProcessed();
  675. return declaredSignature;
  676. }
  677. private void ensureGenericSignatureUnpacked() {
  678. if ((bitflag & UNPACKED_GENERIC_SIGNATURE) != 0) {
  679. return;
  680. }
  681. bitflag |= UNPACKED_GENERIC_SIGNATURE;
  682. if (!getResolvedTypeX().getWorld().isInJava5Mode()) {
  683. return;
  684. }
  685. GenericSignature.ClassSignature cSig = getGenericClassTypeSignature();
  686. if (cSig != null) {
  687. formalsForResolution = cSig.formalTypeParameters;
  688. if (isNested()) {
  689. // we have to find any type variables from the outer type before
  690. // proceeding with resolution.
  691. GenericSignature.FormalTypeParameter[] extraFormals = getFormalTypeParametersFromOuterClass();
  692. if (extraFormals.length > 0) {
  693. List<FormalTypeParameter> allFormals = new ArrayList<FormalTypeParameter>();
  694. for (int i = 0; i < formalsForResolution.length; i++) {
  695. allFormals.add(formalsForResolution[i]);
  696. }
  697. for (int i = 0; i < extraFormals.length; i++) {
  698. allFormals.add(extraFormals[i]);
  699. }
  700. formalsForResolution = new GenericSignature.FormalTypeParameter[allFormals.size()];
  701. allFormals.toArray(formalsForResolution);
  702. }
  703. }
  704. GenericSignature.ClassTypeSignature superSig = cSig.superclassSignature;
  705. try {
  706. // this.superClass =
  707. // BcelGenericSignatureToTypeXConverter.classTypeSignature2TypeX(
  708. // superSig, formalsForResolution,
  709. // getResolvedTypeX().getWorld());
  710. ResolvedType rt = BcelGenericSignatureToTypeXConverter.classTypeSignature2TypeX(superSig, formalsForResolution,
  711. getResolvedTypeX().getWorld());
  712. this.superclassSignature = rt.getSignature();
  713. this.superclassName = rt.getName();
  714. } catch (GenericSignatureFormatException e) {
  715. // development bug, fail fast with good info
  716. throw new IllegalStateException("While determining the generic superclass of " + this.className
  717. + " with generic signature " + getDeclaredGenericSignature() + " the following error was detected: "
  718. + e.getMessage());
  719. }
  720. // this.interfaces = new
  721. // ResolvedType[cSig.superInterfaceSignatures.length];
  722. if (cSig.superInterfaceSignatures.length == 0) {
  723. this.interfaceSignatures = NO_INTERFACE_SIGS;
  724. } else {
  725. this.interfaceSignatures = new String[cSig.superInterfaceSignatures.length];
  726. for (int i = 0; i < cSig.superInterfaceSignatures.length; i++) {
  727. try {
  728. // this.interfaces[i] =
  729. // BcelGenericSignatureToTypeXConverter.
  730. // classTypeSignature2TypeX(
  731. // cSig.superInterfaceSignatures[i],
  732. // formalsForResolution,
  733. // getResolvedTypeX().getWorld());
  734. this.interfaceSignatures[i] = BcelGenericSignatureToTypeXConverter.classTypeSignature2TypeX(
  735. cSig.superInterfaceSignatures[i], formalsForResolution, getResolvedTypeX().getWorld())
  736. .getSignature();
  737. } catch (GenericSignatureFormatException e) {
  738. // development bug, fail fast with good info
  739. throw new IllegalStateException("While determing the generic superinterfaces of " + this.className
  740. + " with generic signature " + getDeclaredGenericSignature()
  741. + " the following error was detected: " + e.getMessage());
  742. }
  743. }
  744. }
  745. }
  746. if (isGeneric()) {
  747. // update resolved typex to point at generic type not raw type.
  748. ReferenceType genericType = (ReferenceType) this.resolvedTypeX.getGenericType();
  749. // genericType.setSourceContext(this.resolvedTypeX.getSourceContext());
  750. // Can be null if unpacking whilst building the bcel delegate (in call hierarchy from BcelWorld.addSourceObjectType()
  751. // line 453) - see 317139
  752. if (genericType != null) {
  753. genericType.setStartPos(this.resolvedTypeX.getStartPos());
  754. this.resolvedTypeX = genericType;
  755. }
  756. }
  757. }
  758. public GenericSignature.FormalTypeParameter[] getAllFormals() {
  759. ensureGenericSignatureUnpacked();
  760. if (formalsForResolution == null) {
  761. return new GenericSignature.FormalTypeParameter[0];
  762. } else {
  763. return formalsForResolution;
  764. }
  765. }
  766. public ResolvedType getOuterClass() {
  767. if (!isNested()) {
  768. throw new IllegalStateException("Can't get the outer class of non-nested type: " + className);
  769. }
  770. // try finding outer class name from InnerClasses attribute assigned to this class
  771. for (Attribute attr : javaClass.getAttributes()) {
  772. if (attr instanceof InnerClasses) {
  773. // search for InnerClass entry that has current class as inner and some other class as outer
  774. InnerClass[] innerClss = ((InnerClasses) attr).getInnerClasses();
  775. ConstantPool cpool = javaClass.getConstantPool();
  776. for (InnerClass innerCls : innerClss) {
  777. // skip entries that miss any necessary component, 0 index means "undefined", from JVM Spec 2nd ed. par. 4.7.5
  778. if (innerCls.getInnerClassIndex() == 0 || innerCls.getOuterClassIndex() == 0) {
  779. continue;
  780. }
  781. // resolve inner class name, check if it matches current class name
  782. ConstantClass innerClsInfo = (ConstantClass) cpool.getConstant(innerCls.getInnerClassIndex());
  783. // class names in constant pool use '/' instead of '.', from JVM Spec 2nd ed. par. 4.2
  784. String innerClsName = cpool.getConstantUtf8(innerClsInfo.getNameIndex()).getValue().replace('/', '.');
  785. if (innerClsName.compareTo(className) == 0) {
  786. // resolve outer class name
  787. ConstantClass outerClsInfo = (ConstantClass) cpool.getConstant(innerCls.getOuterClassIndex());
  788. // class names in constant pool use '/' instead of '.', from JVM Spec 2nd ed. par. 4.2
  789. String outerClsName = cpool.getConstantUtf8(outerClsInfo.getNameIndex()).getValue().replace('/', '.');
  790. UnresolvedType outer = UnresolvedType.forName(outerClsName);
  791. return outer.resolve(getResolvedTypeX().getWorld());
  792. }
  793. }
  794. }
  795. }
  796. for (Attribute attr : javaClass.getAttributes()) { // bug339300
  797. ConstantPool cpool = javaClass.getConstantPool();
  798. if (attr instanceof EnclosingMethod) {
  799. EnclosingMethod enclosingMethodAttribute = (EnclosingMethod) attr;
  800. if (enclosingMethodAttribute.getEnclosingClassIndex() != 0) {
  801. ConstantClass outerClassInfo = enclosingMethodAttribute.getEnclosingClass();
  802. String outerClassName = cpool.getConstantUtf8(outerClassInfo.getNameIndex()).getValue().replace('/', '.');
  803. UnresolvedType outer = UnresolvedType.forName(outerClassName);
  804. return outer.resolve(getResolvedTypeX().getWorld());
  805. }
  806. }
  807. }
  808. // try finding outer class name by assuming standard class name mangling convention of javac for this class
  809. int lastDollar = className.lastIndexOf('$');
  810. String superClassName = className.substring(0, lastDollar);
  811. UnresolvedType outer = UnresolvedType.forName(superClassName);
  812. return outer.resolve(getResolvedTypeX().getWorld());
  813. }
  814. private void ensureGenericInfoProcessed() {
  815. if ((bitflag & DISCOVERED_DECLARED_SIGNATURE) != 0) {
  816. return;
  817. }
  818. bitflag |= DISCOVERED_DECLARED_SIGNATURE;
  819. Signature sigAttr = AttributeUtils.getSignatureAttribute(javaClass.getAttributes());
  820. declaredSignature = (sigAttr == null ? null : sigAttr.getSignature());
  821. if (declaredSignature != null) {
  822. isGenericType = (declaredSignature.charAt(0) == '<');
  823. }
  824. }
  825. public boolean isGeneric() {
  826. ensureGenericInfoProcessed();
  827. return isGenericType;
  828. }
  829. @Override
  830. public String toString() {
  831. return (javaClass == null ? "BcelObjectType" : "BcelObjectTypeFor:" + className);
  832. }
  833. // --- state management
  834. public void evictWeavingState() {
  835. // Can't chuck all this away
  836. if (getResolvedTypeX().getWorld().couldIncrementalCompileFollow()) {
  837. return;
  838. }
  839. if (javaClass != null) {
  840. // Force retrieval of any lazy information
  841. ensureAnnotationsUnpacked();
  842. ensureGenericInfoProcessed();
  843. getDeclaredInterfaces();
  844. getDeclaredFields();
  845. getDeclaredMethods();
  846. // The lazyClassGen is preserved for aspects - it exists to enable
  847. // around advice
  848. // inlining since the method will need 'injecting' into the affected
  849. // class. If
  850. // XnoInline is on, we can chuck away the lazyClassGen since it
  851. // won't be required
  852. // later.
  853. if (getResolvedTypeX().getWorld().isXnoInline()) {
  854. lazyClassGen = null;
  855. }
  856. // discard expensive bytecode array containing reweavable info
  857. if (weaverState != null) {
  858. weaverState.setReweavable(false);
  859. weaverState.setUnwovenClassFileData(null);
  860. }
  861. for (int i = methods.length - 1; i >= 0; i--) {
  862. methods[i].evictWeavingState();
  863. }
  864. for (int i = fields.length - 1; i >= 0; i--) {
  865. fields[i].evictWeavingState();
  866. }
  867. javaClass = null;
  868. this.artificial = true;
  869. // setSourceContext(SourceContextImpl.UNKNOWN_SOURCE_CONTEXT); //
  870. // bit naughty
  871. // interfaces=null; // force reinit - may get us the right
  872. // instances!
  873. // superClass=null;
  874. }
  875. }
  876. public void weavingCompleted() {
  877. hasBeenWoven = true;
  878. if (getResolvedTypeX().getWorld().isRunMinimalMemory()) {
  879. evictWeavingState();
  880. }
  881. if (getSourceContext() != null && !getResolvedTypeX().isAspect()) {
  882. getSourceContext().tidy();
  883. }
  884. }
  885. public boolean hasBeenWoven() {
  886. return hasBeenWoven;
  887. }
  888. @Override
  889. public boolean copySourceContext() {
  890. return false;
  891. }
  892. public void setExposedToWeaver(boolean b) {
  893. exposedToWeaver = b;
  894. }
  895. @Override
  896. public int getCompilerVersion() {
  897. return wvInfo.getMajorVersion();
  898. }
  899. public void ensureConsistent() {
  900. superTypeReference.clear();
  901. superInterfaceReferences.clear();
  902. }
  903. public boolean isWeavable() {
  904. return true;
  905. }
  906. }