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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023
  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. /**
  433. * @return true if built from bytes obtained from somewhere. False if built from bytes retrieved from disk.
  434. */
  435. public boolean isArtificial() {
  436. return artificial;
  437. }
  438. public void resetState() {
  439. if (javaClass == null) {
  440. // we might store the classname and allow reloading?
  441. // At this point we are relying on the world to not evict if it
  442. // might want to reweave multiple times
  443. throw new BCException("can't weave evicted type");
  444. }
  445. bitflag = 0x0000;
  446. this.annotationTypes = null;
  447. this.annotations = null;
  448. this.interfaceSignatures = null;
  449. this.superclassSignature = null;
  450. this.superclassName = null;
  451. this.fields = null;
  452. this.methods = null;
  453. this.pointcuts = null;
  454. this.perClause = null;
  455. this.weaverState = null;
  456. this.lazyClassGen = null;
  457. hasBeenWoven = false;
  458. isObject = (javaClass.getSuperclassNameIndex() == 0);
  459. isAnnotationStyleAspect = false;
  460. ensureAspectJAttributesUnpacked();
  461. }
  462. public void finishedWith() {
  463. // memory usage experiments....
  464. // this.interfaces = null;
  465. // this.superClass = null;
  466. // this.fields = null;
  467. // this.methods = null;
  468. // this.pointcuts = null;
  469. // this.perClause = null;
  470. // this.weaverState = null;
  471. // this.lazyClassGen = null;
  472. // this next line frees up memory, but need to understand incremental
  473. // implications
  474. // before leaving it in.
  475. // getResolvedTypeX().setSourceContext(null);
  476. }
  477. public WeaverStateInfo getWeaverState() {
  478. return weaverState;
  479. }
  480. void setWeaverState(WeaverStateInfo weaverState) {
  481. this.weaverState = weaverState;
  482. }
  483. public void printWackyStuff(PrintStream out) {
  484. if (typeMungers.size() > 0) {
  485. out.println(" TypeMungers: " + typeMungers);
  486. }
  487. if (declares.size() > 0) {
  488. out.println(" declares: " + declares);
  489. }
  490. }
  491. /**
  492. * Return the lazyClassGen associated with this type. For aspect types, this value will be cached, since it is used to inline
  493. * advice. For non-aspect types, this lazyClassGen is always newly constructed.
  494. */
  495. public LazyClassGen getLazyClassGen() {
  496. LazyClassGen ret = lazyClassGen;
  497. if (ret == null) {
  498. // System.err.println("creating lazy class gen for: " + this);
  499. ret = new LazyClassGen(this);
  500. // ret.print(System.err);
  501. // System.err.println("made LCG from : " +
  502. // this.getJavaClass().getSuperclassName );
  503. if (isAspect()) {
  504. lazyClassGen = ret;
  505. }
  506. }
  507. return ret;
  508. }
  509. public boolean isSynthetic() {
  510. return getResolvedTypeX().isSynthetic();
  511. }
  512. public AjAttribute.WeaverVersionInfo getWeaverVersionAttribute() {
  513. return wvInfo;
  514. }
  515. // -- annotation related
  516. public ResolvedType[] getAnnotationTypes() {
  517. ensureAnnotationsUnpacked();
  518. return annotationTypes;
  519. }
  520. public AnnotationAJ[] getAnnotations() {
  521. ensureAnnotationsUnpacked();
  522. return annotations;
  523. }
  524. public boolean hasAnnotations() {
  525. ensureAnnotationsUnpacked();
  526. return annotations.length != 0;
  527. }
  528. public boolean hasAnnotation(UnresolvedType ofType) {
  529. // Due to re-entrancy we may be in the middle of unpacking the annotations already... in which case use this slow
  530. // alternative until the stack unwinds itself
  531. if (isUnpackingAnnotations()) {
  532. AnnotationGen annos[] = javaClass.getAnnotations();
  533. if (annos == null || annos.length == 0) {
  534. return false;
  535. } else {
  536. String lookingForSignature = ofType.getSignature();
  537. for (int a = 0; a < annos.length; a++) {
  538. AnnotationGen annotation = annos[a];
  539. if (lookingForSignature.equals(annotation.getTypeSignature())) {
  540. return true;
  541. }
  542. }
  543. }
  544. return false;
  545. }
  546. ensureAnnotationsUnpacked();
  547. for (int i = 0, max = annotationTypes.length; i < max; i++) {
  548. UnresolvedType ax = annotationTypes[i];
  549. if (ax == null) {
  550. throw new RuntimeException("Annotation entry " + i + " on type " + this.getResolvedTypeX().getName() + " is null!");
  551. }
  552. if (ax.equals(ofType)) {
  553. return true;
  554. }
  555. }
  556. return false;
  557. }
  558. public boolean isAnnotationWithRuntimeRetention() {
  559. return (getRetentionPolicy() == null ? false : getRetentionPolicy().equals("RUNTIME"));
  560. }
  561. public String getRetentionPolicy() {
  562. if ((bitflag & DISCOVERED_ANNOTATION_RETENTION_POLICY) == 0) {
  563. bitflag |= DISCOVERED_ANNOTATION_RETENTION_POLICY;
  564. retentionPolicy = null; // null means we have no idea
  565. if (isAnnotation()) {
  566. ensureAnnotationsUnpacked();
  567. for (int i = annotations.length - 1; i >= 0; i--) {
  568. AnnotationAJ ax = annotations[i];
  569. if (ax.getTypeName().equals(UnresolvedType.AT_RETENTION.getName())) {
  570. List<NameValuePair> values = ((BcelAnnotation) ax).getBcelAnnotation().getValues();
  571. for (Iterator<NameValuePair> it = values.iterator(); it.hasNext();) {
  572. NameValuePair element = it.next();
  573. EnumElementValue v = (EnumElementValue) element.getValue();
  574. retentionPolicy = v.getEnumValueString();
  575. return retentionPolicy;
  576. }
  577. }
  578. }
  579. }
  580. }
  581. return retentionPolicy;
  582. }
  583. public boolean canAnnotationTargetType() {
  584. AnnotationTargetKind[] targetKinds = getAnnotationTargetKinds();
  585. if (targetKinds == null) {
  586. return true;
  587. }
  588. for (int i = 0; i < targetKinds.length; i++) {
  589. if (targetKinds[i].equals(AnnotationTargetKind.TYPE)) {
  590. return true;
  591. }
  592. }
  593. return false;
  594. }
  595. public AnnotationTargetKind[] getAnnotationTargetKinds() {
  596. if ((bitflag & DISCOVERED_ANNOTATION_TARGET_KINDS) != 0) {
  597. return annotationTargetKinds;
  598. }
  599. bitflag |= DISCOVERED_ANNOTATION_TARGET_KINDS;
  600. annotationTargetKinds = null; // null means we have no idea or the
  601. // @Target annotation hasn't been used
  602. List<AnnotationTargetKind> targetKinds = new ArrayList<AnnotationTargetKind>();
  603. if (isAnnotation()) {
  604. AnnotationAJ[] annotationsOnThisType = getAnnotations();
  605. for (int i = 0; i < annotationsOnThisType.length; i++) {
  606. AnnotationAJ a = annotationsOnThisType[i];
  607. if (a.getTypeName().equals(UnresolvedType.AT_TARGET.getName())) {
  608. Set<String> targets = a.getTargets();
  609. if (targets != null) {
  610. for (String targetKind : targets) {
  611. if (targetKind.equals("ANNOTATION_TYPE")) {
  612. targetKinds.add(AnnotationTargetKind.ANNOTATION_TYPE);
  613. } else if (targetKind.equals("CONSTRUCTOR")) {
  614. targetKinds.add(AnnotationTargetKind.CONSTRUCTOR);
  615. } else if (targetKind.equals("FIELD")) {
  616. targetKinds.add(AnnotationTargetKind.FIELD);
  617. } else if (targetKind.equals("LOCAL_VARIABLE")) {
  618. targetKinds.add(AnnotationTargetKind.LOCAL_VARIABLE);
  619. } else if (targetKind.equals("METHOD")) {
  620. targetKinds.add(AnnotationTargetKind.METHOD);
  621. } else if (targetKind.equals("PACKAGE")) {
  622. targetKinds.add(AnnotationTargetKind.PACKAGE);
  623. } else if (targetKind.equals("PARAMETER")) {
  624. targetKinds.add(AnnotationTargetKind.PARAMETER);
  625. } else if (targetKind.equals("TYPE")) {
  626. targetKinds.add(AnnotationTargetKind.TYPE);
  627. }
  628. }
  629. }
  630. }
  631. }
  632. if (!targetKinds.isEmpty()) {
  633. annotationTargetKinds = new AnnotationTargetKind[targetKinds.size()];
  634. return targetKinds.toArray(annotationTargetKinds);
  635. }
  636. }
  637. return annotationTargetKinds;
  638. }
  639. // --- unpacking methods
  640. private boolean isUnpackingAnnotations() {
  641. return (bitflag & ANNOTATION_UNPACK_IN_PROGRESS) != 0;
  642. }
  643. private void ensureAnnotationsUnpacked() {
  644. if (isUnpackingAnnotations()) {
  645. throw new BCException("Re-entered weaver instance whilst unpacking annotations on " + this.className);
  646. }
  647. if (annotationTypes == null) {
  648. try {
  649. bitflag |= ANNOTATION_UNPACK_IN_PROGRESS;
  650. AnnotationGen annos[] = javaClass.getAnnotations();
  651. if (annos == null || annos.length == 0) {
  652. annotationTypes = ResolvedType.NONE;
  653. annotations = AnnotationAJ.EMPTY_ARRAY;
  654. } else {
  655. World w = getResolvedTypeX().getWorld();
  656. annotationTypes = new ResolvedType[annos.length];
  657. annotations = new AnnotationAJ[annos.length];
  658. for (int i = 0; i < annos.length; i++) {
  659. AnnotationGen annotation = annos[i];
  660. String typeSignature = annotation.getTypeSignature();
  661. ResolvedType rType = w.resolve(UnresolvedType.forSignature(typeSignature));
  662. if (rType == null) {
  663. throw new RuntimeException("Whilst unpacking annotations on '" + getResolvedTypeX().getName()
  664. + "', failed to resolve type '" + typeSignature + "'");
  665. }
  666. annotationTypes[i] = rType;
  667. annotations[i] = new BcelAnnotation(annotation, rType);
  668. }
  669. }
  670. } finally {
  671. bitflag &= ~ANNOTATION_UNPACK_IN_PROGRESS;
  672. }
  673. }
  674. }
  675. // ---
  676. public String getDeclaredGenericSignature() {
  677. ensureGenericInfoProcessed();
  678. return declaredSignature;
  679. }
  680. private void ensureGenericSignatureUnpacked() {
  681. if ((bitflag & UNPACKED_GENERIC_SIGNATURE) != 0) {
  682. return;
  683. }
  684. bitflag |= UNPACKED_GENERIC_SIGNATURE;
  685. if (!getResolvedTypeX().getWorld().isInJava5Mode()) {
  686. return;
  687. }
  688. GenericSignature.ClassSignature cSig = getGenericClassTypeSignature();
  689. if (cSig != null) {
  690. formalsForResolution = cSig.formalTypeParameters;
  691. if (isNested()) {
  692. // we have to find any type variables from the outer type before
  693. // proceeding with resolution.
  694. GenericSignature.FormalTypeParameter[] extraFormals = getFormalTypeParametersFromOuterClass();
  695. if (extraFormals.length > 0) {
  696. List<FormalTypeParameter> allFormals = new ArrayList<FormalTypeParameter>();
  697. for (int i = 0; i < formalsForResolution.length; i++) {
  698. allFormals.add(formalsForResolution[i]);
  699. }
  700. for (int i = 0; i < extraFormals.length; i++) {
  701. allFormals.add(extraFormals[i]);
  702. }
  703. formalsForResolution = new GenericSignature.FormalTypeParameter[allFormals.size()];
  704. allFormals.toArray(formalsForResolution);
  705. }
  706. }
  707. GenericSignature.ClassTypeSignature superSig = cSig.superclassSignature;
  708. try {
  709. // this.superClass =
  710. // BcelGenericSignatureToTypeXConverter.classTypeSignature2TypeX(
  711. // superSig, formalsForResolution,
  712. // getResolvedTypeX().getWorld());
  713. ResolvedType rt = BcelGenericSignatureToTypeXConverter.classTypeSignature2TypeX(superSig, formalsForResolution,
  714. getResolvedTypeX().getWorld());
  715. this.superclassSignature = rt.getSignature();
  716. this.superclassName = rt.getName();
  717. } catch (GenericSignatureFormatException e) {
  718. // development bug, fail fast with good info
  719. throw new IllegalStateException("While determining the generic superclass of " + this.className
  720. + " with generic signature " + getDeclaredGenericSignature() + " the following error was detected: "
  721. + e.getMessage());
  722. }
  723. // this.interfaces = new
  724. // ResolvedType[cSig.superInterfaceSignatures.length];
  725. if (cSig.superInterfaceSignatures.length == 0) {
  726. this.interfaceSignatures = NO_INTERFACE_SIGS;
  727. } else {
  728. this.interfaceSignatures = new String[cSig.superInterfaceSignatures.length];
  729. for (int i = 0; i < cSig.superInterfaceSignatures.length; i++) {
  730. try {
  731. // this.interfaces[i] =
  732. // BcelGenericSignatureToTypeXConverter.
  733. // classTypeSignature2TypeX(
  734. // cSig.superInterfaceSignatures[i],
  735. // formalsForResolution,
  736. // getResolvedTypeX().getWorld());
  737. this.interfaceSignatures[i] = BcelGenericSignatureToTypeXConverter.classTypeSignature2TypeX(
  738. cSig.superInterfaceSignatures[i], formalsForResolution, getResolvedTypeX().getWorld())
  739. .getSignature();
  740. } catch (GenericSignatureFormatException e) {
  741. // development bug, fail fast with good info
  742. throw new IllegalStateException("While determing the generic superinterfaces of " + this.className
  743. + " with generic signature " + getDeclaredGenericSignature()
  744. + " the following error was detected: " + e.getMessage());
  745. }
  746. }
  747. }
  748. }
  749. if (isGeneric()) {
  750. // update resolved typex to point at generic type not raw type.
  751. ReferenceType genericType = (ReferenceType) this.resolvedTypeX.getGenericType();
  752. // genericType.setSourceContext(this.resolvedTypeX.getSourceContext());
  753. // Can be null if unpacking whilst building the bcel delegate (in call hierarchy from BcelWorld.addSourceObjectType()
  754. // line 453) - see 317139
  755. if (genericType != null) {
  756. genericType.setStartPos(this.resolvedTypeX.getStartPos());
  757. this.resolvedTypeX = genericType;
  758. }
  759. }
  760. }
  761. public GenericSignature.FormalTypeParameter[] getAllFormals() {
  762. ensureGenericSignatureUnpacked();
  763. if (formalsForResolution == null) {
  764. return new GenericSignature.FormalTypeParameter[0];
  765. } else {
  766. return formalsForResolution;
  767. }
  768. }
  769. public ResolvedType getOuterClass() {
  770. if (!isNested()) {
  771. throw new IllegalStateException("Can't get the outer class of non-nested type: " + className);
  772. }
  773. // try finding outer class name from InnerClasses attribute assigned to this class
  774. for (Attribute attr : javaClass.getAttributes()) {
  775. if (attr instanceof InnerClasses) {
  776. // search for InnerClass entry that has current class as inner and some other class as outer
  777. InnerClass[] innerClss = ((InnerClasses) attr).getInnerClasses();
  778. ConstantPool cpool = javaClass.getConstantPool();
  779. for (InnerClass innerCls : innerClss) {
  780. // skip entries that miss any necessary component, 0 index means "undefined", from JVM Spec 2nd ed. par. 4.7.5
  781. if (innerCls.getInnerClassIndex() == 0 || innerCls.getOuterClassIndex() == 0) {
  782. continue;
  783. }
  784. // resolve inner class name, check if it matches current class name
  785. ConstantClass innerClsInfo = (ConstantClass) cpool.getConstant(innerCls.getInnerClassIndex());
  786. // class names in constant pool use '/' instead of '.', from JVM Spec 2nd ed. par. 4.2
  787. String innerClsName = cpool.getConstantUtf8(innerClsInfo.getNameIndex()).getValue().replace('/', '.');
  788. if (innerClsName.compareTo(className) == 0) {
  789. // resolve outer class name
  790. ConstantClass outerClsInfo = (ConstantClass) cpool.getConstant(innerCls.getOuterClassIndex());
  791. // class names in constant pool use '/' instead of '.', from JVM Spec 2nd ed. par. 4.2
  792. String outerClsName = cpool.getConstantUtf8(outerClsInfo.getNameIndex()).getValue().replace('/', '.');
  793. UnresolvedType outer = UnresolvedType.forName(outerClsName);
  794. return outer.resolve(getResolvedTypeX().getWorld());
  795. }
  796. }
  797. }
  798. }
  799. for (Attribute attr : javaClass.getAttributes()) { // bug339300
  800. ConstantPool cpool = javaClass.getConstantPool();
  801. if (attr instanceof EnclosingMethod) {
  802. EnclosingMethod enclosingMethodAttribute = (EnclosingMethod) attr;
  803. if (enclosingMethodAttribute.getEnclosingClassIndex() != 0) {
  804. ConstantClass outerClassInfo = enclosingMethodAttribute.getEnclosingClass();
  805. String outerClassName = cpool.getConstantUtf8(outerClassInfo.getNameIndex()).getValue().replace('/', '.');
  806. UnresolvedType outer = UnresolvedType.forName(outerClassName);
  807. return outer.resolve(getResolvedTypeX().getWorld());
  808. }
  809. }
  810. }
  811. // try finding outer class name by assuming standard class name mangling convention of javac for this class
  812. int lastDollar = className.lastIndexOf('$');
  813. if (lastDollar == -1) {
  814. // Is this class damaged/obfuscated? Why did we think it was nested but couldn't find the parent using
  815. // the attributes above. For now just ignore it... I wonder when ignoring this will come back to bite!
  816. return null;
  817. }
  818. String superClassName = className.substring(0, lastDollar);
  819. UnresolvedType outer = UnresolvedType.forName(superClassName);
  820. return outer.resolve(getResolvedTypeX().getWorld());
  821. }
  822. private void ensureGenericInfoProcessed() {
  823. if ((bitflag & DISCOVERED_DECLARED_SIGNATURE) != 0) {
  824. return;
  825. }
  826. bitflag |= DISCOVERED_DECLARED_SIGNATURE;
  827. Signature sigAttr = AttributeUtils.getSignatureAttribute(javaClass.getAttributes());
  828. declaredSignature = (sigAttr == null ? null : sigAttr.getSignature());
  829. if (declaredSignature != null) {
  830. isGenericType = (declaredSignature.charAt(0) == '<');
  831. }
  832. }
  833. public boolean isGeneric() {
  834. ensureGenericInfoProcessed();
  835. return isGenericType;
  836. }
  837. @Override
  838. public String toString() {
  839. return (javaClass == null ? "BcelObjectType" : "BcelObjectTypeFor:" + className);
  840. }
  841. // --- state management
  842. public void evictWeavingState() {
  843. // Can't chuck all this away
  844. if (getResolvedTypeX().getWorld().couldIncrementalCompileFollow()) {
  845. return;
  846. }
  847. if (javaClass != null) {
  848. // Force retrieval of any lazy information
  849. ensureAnnotationsUnpacked();
  850. ensureGenericInfoProcessed();
  851. getDeclaredInterfaces();
  852. getDeclaredFields();
  853. getDeclaredMethods();
  854. // The lazyClassGen is preserved for aspects - it exists to enable
  855. // around advice
  856. // inlining since the method will need 'injecting' into the affected
  857. // class. If
  858. // XnoInline is on, we can chuck away the lazyClassGen since it
  859. // won't be required
  860. // later.
  861. if (getResolvedTypeX().getWorld().isXnoInline()) {
  862. lazyClassGen = null;
  863. }
  864. // discard expensive bytecode array containing reweavable info
  865. if (weaverState != null) {
  866. weaverState.setReweavable(false);
  867. weaverState.setUnwovenClassFileData(null);
  868. }
  869. for (int i = methods.length - 1; i >= 0; i--) {
  870. methods[i].evictWeavingState();
  871. }
  872. for (int i = fields.length - 1; i >= 0; i--) {
  873. fields[i].evictWeavingState();
  874. }
  875. javaClass = null;
  876. this.artificial = true;
  877. // setSourceContext(SourceContextImpl.UNKNOWN_SOURCE_CONTEXT); //
  878. // bit naughty
  879. // interfaces=null; // force reinit - may get us the right
  880. // instances!
  881. // superClass=null;
  882. }
  883. }
  884. public void weavingCompleted() {
  885. hasBeenWoven = true;
  886. if (getResolvedTypeX().getWorld().isRunMinimalMemory()) {
  887. evictWeavingState();
  888. }
  889. if (getSourceContext() != null && !getResolvedTypeX().isAspect()) {
  890. getSourceContext().tidy();
  891. }
  892. }
  893. public boolean hasBeenWoven() {
  894. return hasBeenWoven;
  895. }
  896. @Override
  897. public boolean copySourceContext() {
  898. return false;
  899. }
  900. public void setExposedToWeaver(boolean b) {
  901. exposedToWeaver = b;
  902. }
  903. @Override
  904. public int getCompilerVersion() {
  905. return wvInfo.getMajorVersion();
  906. }
  907. public void ensureConsistent() {
  908. superTypeReference.clear();
  909. superInterfaceReferences.clear();
  910. }
  911. public boolean isWeavable() {
  912. return true;
  913. }
  914. }