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.

BcelWorld.java 47KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328
  1. /* *******************************************************************
  2. * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
  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. * Alexandre Vasseur perClause support for @AJ aspects
  12. * ******************************************************************/
  13. package org.aspectj.weaver.bcel;
  14. import java.io.File;
  15. import java.io.IOException;
  16. import java.lang.reflect.Modifier;
  17. import java.net.MalformedURLException;
  18. import java.util.ArrayList;
  19. import java.util.Collections;
  20. import java.util.HashMap;
  21. import java.util.Iterator;
  22. import java.util.List;
  23. import java.util.Map;
  24. import java.util.StringTokenizer;
  25. import org.aspectj.apache.bcel.Constants;
  26. import org.aspectj.apache.bcel.classfile.ClassParser;
  27. import org.aspectj.apache.bcel.classfile.ConstantPool;
  28. import org.aspectj.apache.bcel.classfile.JavaClass;
  29. import org.aspectj.apache.bcel.generic.FieldInstruction;
  30. import org.aspectj.apache.bcel.generic.INVOKEINTERFACE;
  31. import org.aspectj.apache.bcel.generic.Instruction;
  32. import org.aspectj.apache.bcel.generic.InstructionHandle;
  33. import org.aspectj.apache.bcel.generic.InvokeInstruction;
  34. import org.aspectj.apache.bcel.generic.MULTIANEWARRAY;
  35. import org.aspectj.apache.bcel.generic.ObjectType;
  36. import org.aspectj.apache.bcel.generic.Type;
  37. import org.aspectj.apache.bcel.util.ClassLoaderReference;
  38. import org.aspectj.apache.bcel.util.ClassLoaderRepository;
  39. import org.aspectj.apache.bcel.util.ClassPath;
  40. import org.aspectj.apache.bcel.util.NonCachingClassLoaderRepository;
  41. import org.aspectj.apache.bcel.util.Repository;
  42. import org.aspectj.asm.AsmManager;
  43. import org.aspectj.asm.IRelationship;
  44. import org.aspectj.asm.internal.CharOperation;
  45. import org.aspectj.bridge.IMessage;
  46. import org.aspectj.bridge.IMessageHandler;
  47. import org.aspectj.bridge.ISourceLocation;
  48. import org.aspectj.bridge.Message;
  49. import org.aspectj.bridge.MessageUtil;
  50. import org.aspectj.bridge.WeaveMessage;
  51. import org.aspectj.weaver.Advice;
  52. import org.aspectj.weaver.AdviceKind;
  53. import org.aspectj.weaver.AnnotationAJ;
  54. import org.aspectj.weaver.AnnotationOnTypeMunger;
  55. import org.aspectj.weaver.BCException;
  56. import org.aspectj.weaver.Checker;
  57. import org.aspectj.weaver.ICrossReferenceHandler;
  58. import org.aspectj.weaver.IWeavingSupport;
  59. import org.aspectj.weaver.Member;
  60. import org.aspectj.weaver.MemberImpl;
  61. import org.aspectj.weaver.MemberKind;
  62. import org.aspectj.weaver.NewParentTypeMunger;
  63. import org.aspectj.weaver.ReferenceType;
  64. import org.aspectj.weaver.ReferenceTypeDelegate;
  65. import org.aspectj.weaver.ResolvedMember;
  66. import org.aspectj.weaver.ResolvedMemberImpl;
  67. import org.aspectj.weaver.ResolvedType;
  68. import org.aspectj.weaver.ResolvedTypeMunger;
  69. import org.aspectj.weaver.Shadow;
  70. import org.aspectj.weaver.ShadowMunger;
  71. import org.aspectj.weaver.UnresolvedType;
  72. import org.aspectj.weaver.World;
  73. import org.aspectj.weaver.loadtime.definition.Definition;
  74. import org.aspectj.weaver.loadtime.definition.DocumentParser;
  75. import org.aspectj.weaver.model.AsmRelationshipProvider;
  76. import org.aspectj.weaver.patterns.DeclareAnnotation;
  77. import org.aspectj.weaver.patterns.DeclareParents;
  78. import org.aspectj.weaver.patterns.ParserException;
  79. import org.aspectj.weaver.patterns.PatternParser;
  80. import org.aspectj.weaver.patterns.TypePattern;
  81. import org.aspectj.weaver.tools.Trace;
  82. import org.aspectj.weaver.tools.TraceFactory;
  83. public class BcelWorld extends World implements Repository {
  84. private final ClassPathManager classPath;
  85. protected Repository delegate;
  86. private BcelWeakClassLoaderReference loaderRef;
  87. private final BcelWeavingSupport bcelWeavingSupport = new BcelWeavingSupport();
  88. private boolean isXmlConfiguredWorld = false;
  89. private WeavingXmlConfig xmlConfiguration;
  90. private List<TypeDelegateResolver> typeDelegateResolvers;
  91. private static Trace trace = TraceFactory.getTraceFactory().getTrace(BcelWorld.class);
  92. public BcelWorld() {
  93. this("");
  94. }
  95. public BcelWorld(String cp) {
  96. this(makeDefaultClasspath(cp), IMessageHandler.THROW, null);
  97. }
  98. public IRelationship.Kind determineRelKind(ShadowMunger munger) {
  99. AdviceKind ak = ((Advice) munger).getKind();
  100. if (ak.getKey() == AdviceKind.Before.getKey()) {
  101. return IRelationship.Kind.ADVICE_BEFORE;
  102. } else if (ak.getKey() == AdviceKind.After.getKey()) {
  103. return IRelationship.Kind.ADVICE_AFTER;
  104. } else if (ak.getKey() == AdviceKind.AfterThrowing.getKey()) {
  105. return IRelationship.Kind.ADVICE_AFTERTHROWING;
  106. } else if (ak.getKey() == AdviceKind.AfterReturning.getKey()) {
  107. return IRelationship.Kind.ADVICE_AFTERRETURNING;
  108. } else if (ak.getKey() == AdviceKind.Around.getKey()) {
  109. return IRelationship.Kind.ADVICE_AROUND;
  110. } else if (ak.getKey() == AdviceKind.CflowEntry.getKey() || ak.getKey() == AdviceKind.CflowBelowEntry.getKey()
  111. || ak.getKey() == AdviceKind.InterInitializer.getKey() || ak.getKey() == AdviceKind.PerCflowEntry.getKey()
  112. || ak.getKey() == AdviceKind.PerCflowBelowEntry.getKey() || ak.getKey() == AdviceKind.PerThisEntry.getKey()
  113. || ak.getKey() == AdviceKind.PerTargetEntry.getKey() || ak.getKey() == AdviceKind.Softener.getKey()
  114. || ak.getKey() == AdviceKind.PerTypeWithinEntry.getKey()) {
  115. // System.err.println("Dont want a message about this: "+ak);
  116. return null;
  117. }
  118. throw new RuntimeException("Shadow.determineRelKind: What the hell is it? " + ak);
  119. }
  120. @Override
  121. public void reportMatch(ShadowMunger munger, Shadow shadow) {
  122. if (getCrossReferenceHandler() != null) {
  123. getCrossReferenceHandler().addCrossReference(munger.getSourceLocation(), // What is being applied
  124. shadow.getSourceLocation(), // Where is it being applied
  125. determineRelKind(munger).getName(), // What kind of advice?
  126. ((Advice) munger).hasDynamicTests() // Is a runtime test being stuffed in the code?
  127. );
  128. }
  129. if (!getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) {
  130. reportWeavingMessage(munger, shadow);
  131. }
  132. if (getModel() != null) {
  133. AsmRelationshipProvider.addAdvisedRelationship(getModelAsAsmManager(), shadow, munger);
  134. }
  135. }
  136. /*
  137. * Report a message about the advice weave that has occurred. Some messing about to make it pretty ! This code is just asking
  138. * for an NPE to occur ...
  139. */
  140. private void reportWeavingMessage(ShadowMunger munger, Shadow shadow) {
  141. Advice advice = (Advice) munger;
  142. AdviceKind aKind = advice.getKind();
  143. // Only report on interesting advice kinds ...
  144. if (aKind == null || advice.getConcreteAspect() == null) {
  145. // We suspect someone is programmatically driving the weaver
  146. // (e.g. IdWeaveTestCase in the weaver testcases)
  147. return;
  148. }
  149. if (!(aKind.equals(AdviceKind.Before) || aKind.equals(AdviceKind.After) || aKind.equals(AdviceKind.AfterReturning)
  150. || aKind.equals(AdviceKind.AfterThrowing) || aKind.equals(AdviceKind.Around) || aKind.equals(AdviceKind.Softener))) {
  151. return;
  152. }
  153. // synchronized blocks are implemented with multiple monitor_exit instructions in the bytecode
  154. // (one for normal exit from the method, one for abnormal exit), we only want to tell the user
  155. // once we have advised the end of the sync block, even though under the covers we will have
  156. // woven both exit points
  157. if (shadow.getKind() == Shadow.SynchronizationUnlock) {
  158. if (advice.lastReportedMonitorExitJoinpointLocation == null) {
  159. // this is the first time through, let's continue...
  160. advice.lastReportedMonitorExitJoinpointLocation = shadow.getSourceLocation();
  161. } else {
  162. if (areTheSame(shadow.getSourceLocation(), advice.lastReportedMonitorExitJoinpointLocation)) {
  163. // Don't report it again!
  164. advice.lastReportedMonitorExitJoinpointLocation = null;
  165. return;
  166. }
  167. // hmmm, this means some kind of nesting is going on, urgh
  168. advice.lastReportedMonitorExitJoinpointLocation = shadow.getSourceLocation();
  169. }
  170. }
  171. String description = advice.getKind().toString();
  172. String advisedType = shadow.getEnclosingType().getName();
  173. String advisingType = advice.getConcreteAspect().getName();
  174. Message msg = null;
  175. if (advice.getKind().equals(AdviceKind.Softener)) {
  176. msg = WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_SOFTENS, new String[] { advisedType,
  177. beautifyLocation(shadow.getSourceLocation()), advisingType, beautifyLocation(munger.getSourceLocation()) },
  178. advisedType, advisingType);
  179. } else {
  180. boolean runtimeTest = advice.hasDynamicTests();
  181. String joinPointDescription = shadow.toString();
  182. msg = WeaveMessage
  183. .constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ADVISES,
  184. new String[] { joinPointDescription, advisedType, beautifyLocation(shadow.getSourceLocation()),
  185. description, advisingType, beautifyLocation(munger.getSourceLocation()),
  186. (runtimeTest ? " [with runtime test]" : "") }, advisedType, advisingType);
  187. // Boolean.toString(runtimeTest)});
  188. }
  189. getMessageHandler().handleMessage(msg);
  190. }
  191. private boolean areTheSame(ISourceLocation locA, ISourceLocation locB) {
  192. if (locA == null) {
  193. return locB == null;
  194. }
  195. if (locB == null) {
  196. return false;
  197. }
  198. if (locA.getLine() != locB.getLine()) {
  199. return false;
  200. }
  201. File fA = locA.getSourceFile();
  202. File fB = locA.getSourceFile();
  203. if (fA == null) {
  204. return fB == null;
  205. }
  206. if (fB == null) {
  207. return false;
  208. }
  209. return fA.getName().equals(fB.getName());
  210. }
  211. /*
  212. * Ensure we report a nice source location - particular in the case where the source info is missing (binary weave).
  213. */
  214. private String beautifyLocation(ISourceLocation isl) {
  215. StringBuffer nice = new StringBuffer();
  216. if (isl == null || isl.getSourceFile() == null || isl.getSourceFile().getName().contains("no debug info available")) {
  217. nice.append("no debug info available");
  218. } else {
  219. // can't use File.getName() as this fails when a Linux box encounters a path created on Windows and vice-versa
  220. int takeFrom = isl.getSourceFile().getPath().lastIndexOf('/');
  221. if (takeFrom == -1) {
  222. takeFrom = isl.getSourceFile().getPath().lastIndexOf('\\');
  223. }
  224. int binary = isl.getSourceFile().getPath().lastIndexOf('!');
  225. if (binary != -1 && binary < takeFrom) {
  226. // we have been woven by a binary aspect
  227. String pathToBinaryLoc = isl.getSourceFile().getPath().substring(0, binary + 1);
  228. if (pathToBinaryLoc.contains(".jar")) {
  229. // only want to add the extra info if we're from a jar file
  230. int lastSlash = pathToBinaryLoc.lastIndexOf('/');
  231. if (lastSlash == -1) {
  232. lastSlash = pathToBinaryLoc.lastIndexOf('\\');
  233. }
  234. nice.append(pathToBinaryLoc.substring(lastSlash + 1));
  235. }
  236. }
  237. nice.append(isl.getSourceFile().getPath().substring(takeFrom + 1));
  238. if (isl.getLine() != 0) {
  239. nice.append(":").append(isl.getLine());
  240. }
  241. // if it's a binary file then also want to give the file name
  242. if (isl.getSourceFileName() != null) {
  243. nice.append("(from " + isl.getSourceFileName() + ")");
  244. }
  245. }
  246. return nice.toString();
  247. }
  248. private static List<String> makeDefaultClasspath(String cp) {
  249. List<String> classPath = new ArrayList<String>();
  250. classPath.addAll(getPathEntries(cp));
  251. classPath.addAll(getPathEntries(ClassPath.getClassPath()));
  252. return classPath;
  253. }
  254. private static List<String> getPathEntries(String s) {
  255. List<String> ret = new ArrayList<String>();
  256. StringTokenizer tok = new StringTokenizer(s, File.pathSeparator);
  257. while (tok.hasMoreTokens()) {
  258. ret.add(tok.nextToken());
  259. }
  260. return ret;
  261. }
  262. public BcelWorld(List classPath, IMessageHandler handler, ICrossReferenceHandler xrefHandler) {
  263. // this.aspectPath = new ClassPathManager(aspectPath, handler);
  264. this.classPath = new ClassPathManager(classPath, handler);
  265. setMessageHandler(handler);
  266. setCrossReferenceHandler(xrefHandler);
  267. // Tell BCEL to use us for resolving any classes
  268. delegate = this;
  269. }
  270. public BcelWorld(ClassPathManager cpm, IMessageHandler handler, ICrossReferenceHandler xrefHandler) {
  271. classPath = cpm;
  272. setMessageHandler(handler);
  273. setCrossReferenceHandler(xrefHandler);
  274. // Tell BCEL to use us for resolving any classes
  275. delegate = this;
  276. }
  277. /**
  278. * Build a World from a ClassLoader, for LTW support
  279. *
  280. * @param loader
  281. * @param handler
  282. * @param xrefHandler
  283. */
  284. public BcelWorld(ClassLoader loader, IMessageHandler handler, ICrossReferenceHandler xrefHandler) {
  285. classPath = null;
  286. loaderRef = new BcelWeakClassLoaderReference(loader);
  287. setMessageHandler(handler);
  288. setCrossReferenceHandler(xrefHandler);
  289. // Tell BCEL to use us for resolving any classes
  290. // delegate = getClassLoaderRepositoryFor(loader);
  291. }
  292. public void ensureRepositorySetup() {
  293. if (delegate == null) {
  294. delegate = getClassLoaderRepositoryFor(loaderRef);
  295. }
  296. }
  297. public Repository getClassLoaderRepositoryFor(ClassLoaderReference loader) {
  298. if (bcelRepositoryCaching) {
  299. return new ClassLoaderRepository(loader);
  300. } else {
  301. return new NonCachingClassLoaderRepository(loader);
  302. }
  303. }
  304. public void addPath(String name) {
  305. classPath.addPath(name, this.getMessageHandler());
  306. }
  307. // ---- various interactions with bcel
  308. public static Type makeBcelType(UnresolvedType type) {
  309. return Type.getType(type.getErasureSignature());
  310. }
  311. static Type[] makeBcelTypes(UnresolvedType[] types) {
  312. Type[] ret = new Type[types.length];
  313. for (int i = 0, len = types.length; i < len; i++) {
  314. ret[i] = makeBcelType(types[i]);
  315. }
  316. return ret;
  317. }
  318. public static Type[] makeBcelTypes(String[] types) {
  319. if (types == null || types.length==0 ) {
  320. return null;
  321. }
  322. Type[] ret = new Type[types.length];
  323. for (int i=0, len=types.length; i<len; i++) {
  324. ret[i] = makeBcelType(types[i]);
  325. }
  326. return ret;
  327. }
  328. public static Type makeBcelType(String type) {
  329. return Type.getType(type);
  330. }
  331. static String[] makeBcelTypesAsClassNames(UnresolvedType[] types) {
  332. String[] ret = new String[types.length];
  333. for (int i = 0, len = types.length; i < len; i++) {
  334. ret[i] = types[i].getName();
  335. }
  336. return ret;
  337. }
  338. public static UnresolvedType fromBcel(Type t) {
  339. return UnresolvedType.forSignature(t.getSignature());
  340. }
  341. static UnresolvedType[] fromBcel(Type[] ts) {
  342. UnresolvedType[] ret = new UnresolvedType[ts.length];
  343. for (int i = 0, len = ts.length; i < len; i++) {
  344. ret[i] = fromBcel(ts[i]);
  345. }
  346. return ret;
  347. }
  348. public ResolvedType resolve(Type t) {
  349. return resolve(fromBcel(t));
  350. }
  351. @Override
  352. protected ReferenceTypeDelegate resolveDelegate(ReferenceType ty) {
  353. String name = ty.getName();
  354. ensureAdvancedConfigurationProcessed();
  355. JavaClass jc = lookupJavaClass(classPath, name);
  356. if (jc == null) {
  357. // Anyone else to ask?
  358. if (typeDelegateResolvers != null) {
  359. for (TypeDelegateResolver tdr : typeDelegateResolvers) {
  360. ReferenceTypeDelegate delegate = tdr.getDelegate(ty);
  361. if (delegate != null) {
  362. return delegate;
  363. }
  364. }
  365. }
  366. return null;
  367. } else {
  368. return buildBcelDelegate(ty, jc, false, false);
  369. }
  370. }
  371. public BcelObjectType buildBcelDelegate(ReferenceType type, JavaClass jc, boolean artificial, boolean exposedToWeaver) {
  372. BcelObjectType ret = new BcelObjectType(type, jc, artificial, exposedToWeaver);
  373. return ret;
  374. }
  375. private JavaClass lookupJavaClass(ClassPathManager classPath, String name) {
  376. if (classPath == null) {
  377. try {
  378. ensureRepositorySetup();
  379. JavaClass jc = delegate.loadClass(name);
  380. if (trace.isTraceEnabled()) {
  381. trace.event("lookupJavaClass", this, new Object[] { name, jc });
  382. }
  383. return jc;
  384. } catch (ClassNotFoundException e) {
  385. if (trace.isTraceEnabled()) {
  386. trace.error("Unable to find class '" + name + "' in repository", e);
  387. }
  388. return null;
  389. }
  390. }
  391. ClassPathManager.ClassFile file = null;
  392. try {
  393. file = classPath.find(UnresolvedType.forName(name));
  394. if (file == null) {
  395. return null;
  396. }
  397. ClassParser parser = new ClassParser(file.getInputStream(), file.getPath());
  398. JavaClass jc = parser.parse();
  399. return jc;
  400. } catch (IOException ioe) {
  401. if (trace.isTraceEnabled()) {
  402. trace.error("IOException whilst processing class",ioe);
  403. }
  404. return null;
  405. } finally {
  406. if (file != null) {
  407. file.close();
  408. }
  409. }
  410. }
  411. public BcelObjectType addSourceObjectType(JavaClass jc, boolean artificial) {
  412. return addSourceObjectType(jc.getClassName(), jc, artificial);
  413. }
  414. public BcelObjectType addSourceObjectType(String classname, JavaClass jc, boolean artificial) {
  415. BcelObjectType ret = null;
  416. if (!jc.getClassName().equals(classname)) {
  417. throw new RuntimeException(jc.getClassName() + "!=" + classname);
  418. }
  419. String signature = UnresolvedType.forName(jc.getClassName()).getSignature();
  420. ResolvedType resolvedTypeFromTypeMap = typeMap.get(signature);
  421. if (resolvedTypeFromTypeMap != null && !(resolvedTypeFromTypeMap instanceof ReferenceType)) {
  422. // what on earth is it then? See pr 112243
  423. StringBuffer exceptionText = new StringBuffer();
  424. exceptionText.append("Found invalid (not a ReferenceType) entry in the type map. ");
  425. exceptionText.append("Signature=[" + signature + "] Found=[" + resolvedTypeFromTypeMap + "] Class=[" + resolvedTypeFromTypeMap.getClass() + "]");
  426. throw new BCException(exceptionText.toString());
  427. }
  428. ReferenceType referenceTypeFromTypeMap = (ReferenceType) resolvedTypeFromTypeMap;
  429. if (referenceTypeFromTypeMap == null) {
  430. if (jc.isGeneric() && isInJava5Mode()) {
  431. ReferenceType rawType = ReferenceType.fromTypeX(UnresolvedType.forRawTypeName(jc.getClassName()), this);
  432. ret = buildBcelDelegate(rawType, jc, artificial, true);
  433. ReferenceType genericRefType = new ReferenceType(UnresolvedType.forGenericTypeSignature(signature,
  434. ret.getDeclaredGenericSignature()), this);
  435. rawType.setDelegate(ret);
  436. genericRefType.setDelegate(ret);
  437. rawType.setGenericType(genericRefType);
  438. typeMap.put(signature, rawType);
  439. } else {
  440. referenceTypeFromTypeMap = new ReferenceType(signature, this);
  441. ret = buildBcelDelegate(referenceTypeFromTypeMap, jc, artificial, true);
  442. typeMap.put(signature, referenceTypeFromTypeMap);
  443. }
  444. } else {
  445. ret = buildBcelDelegate(referenceTypeFromTypeMap, jc, artificial, true);
  446. }
  447. return ret;
  448. }
  449. public BcelObjectType addSourceObjectType(String classname, byte[] bytes, boolean artificial) {
  450. BcelObjectType retval = null;
  451. String signature = UnresolvedType.forName(classname).getSignature();
  452. ResolvedType resolvedTypeFromTypeMap = typeMap.get(signature);
  453. if (resolvedTypeFromTypeMap != null && !(resolvedTypeFromTypeMap instanceof ReferenceType)) {
  454. // what on earth is it then? See pr 112243
  455. StringBuffer exceptionText = new StringBuffer();
  456. exceptionText.append("Found invalid (not a ReferenceType) entry in the type map. ");
  457. exceptionText.append("Signature=[" + signature + "] Found=[" + resolvedTypeFromTypeMap + "] Class=[" + resolvedTypeFromTypeMap.getClass() + "]");
  458. throw new BCException(exceptionText.toString());
  459. }
  460. ReferenceType referenceTypeFromTypeMap = (ReferenceType) resolvedTypeFromTypeMap;
  461. if (referenceTypeFromTypeMap == null) {
  462. JavaClass jc = Utility.makeJavaClass(classname, bytes);
  463. if (jc.isGeneric() && isInJava5Mode()) {
  464. referenceTypeFromTypeMap = ReferenceType.fromTypeX(UnresolvedType.forRawTypeName(jc.getClassName()), this);
  465. retval = buildBcelDelegate(referenceTypeFromTypeMap, jc, artificial, true);
  466. ReferenceType genericRefType = new ReferenceType(UnresolvedType.forGenericTypeSignature(signature,
  467. retval.getDeclaredGenericSignature()), this);
  468. referenceTypeFromTypeMap.setDelegate(retval);
  469. genericRefType.setDelegate(retval);
  470. referenceTypeFromTypeMap.setGenericType(genericRefType);
  471. typeMap.put(signature, referenceTypeFromTypeMap);
  472. } else {
  473. referenceTypeFromTypeMap = new ReferenceType(signature, this);
  474. retval = buildBcelDelegate(referenceTypeFromTypeMap, jc, artificial, true);
  475. typeMap.put(signature, referenceTypeFromTypeMap);
  476. }
  477. } else {
  478. ReferenceTypeDelegate existingDelegate = referenceTypeFromTypeMap.getDelegate();
  479. if (!(existingDelegate instanceof BcelObjectType)) {
  480. throw new IllegalStateException("For " + classname + " should be BcelObjectType, but is " + existingDelegate.getClass());
  481. }
  482. retval = (BcelObjectType) existingDelegate;
  483. // Note1: If the type is already exposed to the weaver (retval.isExposedToWeaver()) then this is likely
  484. // to be a hotswap reweave so build a new delegate, don't accidentally use the old data.
  485. // Note2: Also seen when LTW and another agent precedes the AspectJ agent. Earlier in LTW
  486. // a type is resolved (and ends up in the typemap but not exposed to the weaver at that time)
  487. // then later LTW actually is attempted on this type. We end up here with different
  488. // bytes to the current delegate if the earlier agent has modified them. See PR488216
  489. // if (retval.isArtificial() || retval.isExposedToWeaver()) {
  490. retval = buildBcelDelegate(referenceTypeFromTypeMap, Utility.makeJavaClass(classname, bytes), artificial, true);
  491. // }
  492. }
  493. return retval;
  494. }
  495. void deleteSourceObjectType(UnresolvedType ty) {
  496. typeMap.remove(ty.getSignature());
  497. }
  498. public static Member makeFieldJoinPointSignature(LazyClassGen cg, FieldInstruction fi) {
  499. ConstantPool cpg = cg.getConstantPool();
  500. return MemberImpl.field(fi.getClassName(cpg),
  501. (fi.opcode == Constants.GETSTATIC || fi.opcode == Constants.PUTSTATIC) ? Modifier.STATIC : 0, fi.getName(cpg),
  502. fi.getSignature(cpg));
  503. }
  504. public Member makeJoinPointSignatureFromMethod(LazyMethodGen mg, MemberKind kind) {
  505. Member ret = mg.getMemberView();
  506. if (ret == null) {
  507. int mods = mg.getAccessFlags();
  508. if (mg.getEnclosingClass().isInterface()) {
  509. mods |= Modifier.INTERFACE;
  510. }
  511. return new ResolvedMemberImpl(kind, UnresolvedType.forName(mg.getClassName()), mods, fromBcel(mg.getReturnType()),
  512. mg.getName(), fromBcel(mg.getArgumentTypes()));
  513. } else {
  514. return ret;
  515. }
  516. }
  517. public Member makeJoinPointSignatureForMonitorEnter(LazyClassGen cg, InstructionHandle h) {
  518. return MemberImpl.monitorEnter();
  519. }
  520. public Member makeJoinPointSignatureForMonitorExit(LazyClassGen cg, InstructionHandle h) {
  521. return MemberImpl.monitorExit();
  522. }
  523. public Member makeJoinPointSignatureForArrayConstruction(LazyClassGen cg, InstructionHandle handle) {
  524. Instruction i = handle.getInstruction();
  525. ConstantPool cpg = cg.getConstantPool();
  526. Member retval = null;
  527. if (i.opcode == Constants.ANEWARRAY) {
  528. // ANEWARRAY arrayInstruction = (ANEWARRAY)i;
  529. Type ot = i.getType(cpg);
  530. UnresolvedType ut = fromBcel(ot);
  531. ut = UnresolvedType.makeArray(ut, 1);
  532. retval = MemberImpl.method(ut, Modifier.PUBLIC, UnresolvedType.VOID, "<init>", new ResolvedType[] { INT });
  533. } else if (i instanceof MULTIANEWARRAY) {
  534. MULTIANEWARRAY arrayInstruction = (MULTIANEWARRAY) i;
  535. UnresolvedType ut = null;
  536. short dimensions = arrayInstruction.getDimensions();
  537. ObjectType ot = arrayInstruction.getLoadClassType(cpg);
  538. if (ot != null) {
  539. ut = fromBcel(ot);
  540. ut = UnresolvedType.makeArray(ut, dimensions);
  541. } else {
  542. Type t = arrayInstruction.getType(cpg);
  543. ut = fromBcel(t);
  544. }
  545. ResolvedType[] parms = new ResolvedType[dimensions];
  546. for (int ii = 0; ii < dimensions; ii++) {
  547. parms[ii] = INT;
  548. }
  549. retval = MemberImpl.method(ut, Modifier.PUBLIC, UnresolvedType.VOID, "<init>", parms);
  550. } else if (i.opcode == Constants.NEWARRAY) {
  551. // NEWARRAY arrayInstruction = (NEWARRAY)i;
  552. Type ot = i.getType();
  553. UnresolvedType ut = fromBcel(ot);
  554. retval = MemberImpl.method(ut, Modifier.PUBLIC, UnresolvedType.VOID, "<init>", new ResolvedType[] { INT });
  555. } else {
  556. throw new BCException("Cannot create array construction signature for this non-array instruction:" + i);
  557. }
  558. return retval;
  559. }
  560. public Member makeJoinPointSignatureForMethodInvocation(LazyClassGen cg, InvokeInstruction ii) {
  561. ConstantPool cpg = cg.getConstantPool();
  562. String name = ii.getName(cpg);
  563. String declaring = ii.getClassName(cpg);
  564. UnresolvedType declaringType = null;
  565. String signature = ii.getSignature(cpg);
  566. // 307147
  567. if (name.startsWith("ajc$privMethod$")) {
  568. // The invoke is on a privileged accessor. These may be created for different
  569. // kinds of target, not necessarily just private methods. In bug 307147 it is
  570. // for a private method. This code is identifying the particular case in 307147
  571. try {
  572. declaringType = UnresolvedType.forName(declaring);
  573. String typeNameAsFoundInAccessorName = declaringType.getName().replace('.', '_');
  574. int indexInAccessorName = name.lastIndexOf(typeNameAsFoundInAccessorName);
  575. if (indexInAccessorName != -1) {
  576. String methodName = name.substring(indexInAccessorName+typeNameAsFoundInAccessorName.length()+1);
  577. ResolvedType resolvedDeclaringType = declaringType.resolve(this);
  578. ResolvedMember[] methods = resolvedDeclaringType.getDeclaredMethods();
  579. for (ResolvedMember method: methods) {
  580. if (method.getName().equals(methodName) && method.getSignature().equals(signature) && Modifier.isPrivate(method.getModifiers())) {
  581. return method;
  582. }
  583. }
  584. }
  585. } catch (Exception e) {
  586. // Remove this once confident above code isn't having unexpected side effects
  587. // Added 1.8.7
  588. e.printStackTrace();
  589. }
  590. }
  591. int modifier = (ii instanceof INVOKEINTERFACE) ? Modifier.INTERFACE
  592. : (ii.opcode == Constants.INVOKESTATIC) ? Modifier.STATIC : (ii.opcode == Constants.INVOKESPECIAL && !name
  593. .equals("<init>")) ? Modifier.PRIVATE : 0;
  594. // in Java 1.4 and after, static method call of super class within
  595. // subclass method appears
  596. // as declared by the subclass in the bytecode - but they are not
  597. // see #104212
  598. if (ii.opcode == Constants.INVOKESTATIC) {
  599. ResolvedType appearsDeclaredBy = resolve(declaring);
  600. // look for the method there
  601. for (Iterator<ResolvedMember> iterator = appearsDeclaredBy.getMethods(true, true); iterator.hasNext();) {
  602. ResolvedMember method = iterator.next();
  603. if (Modifier.isStatic(method.getModifiers())) {
  604. if (name.equals(method.getName()) && signature.equals(method.getSignature())) {
  605. // we found it
  606. declaringType = method.getDeclaringType();
  607. break;
  608. }
  609. }
  610. }
  611. }
  612. if (declaringType == null) {
  613. if (declaring.charAt(0) == '[') {
  614. declaringType = UnresolvedType.forSignature(declaring);
  615. } else {
  616. declaringType = UnresolvedType.forName(declaring);
  617. }
  618. }
  619. return MemberImpl.method(declaringType, modifier, name, signature);
  620. }
  621. @Override
  622. public String toString() {
  623. StringBuffer buf = new StringBuffer();
  624. buf.append("BcelWorld(");
  625. // buf.append(shadowMungerMap);
  626. buf.append(")");
  627. return buf.toString();
  628. }
  629. /**
  630. * Retrieve a bcel delegate for an aspect - this will return NULL if the delegate is an EclipseSourceType and not a
  631. * BcelObjectType - this happens quite often when incrementally compiling.
  632. */
  633. public static BcelObjectType getBcelObjectType(ResolvedType concreteAspect) {
  634. if (concreteAspect == null) {
  635. return null;
  636. }
  637. if (!(concreteAspect instanceof ReferenceType)) { // Might be Missing
  638. return null;
  639. }
  640. ReferenceTypeDelegate rtDelegate = ((ReferenceType) concreteAspect).getDelegate();
  641. if (rtDelegate instanceof BcelObjectType) {
  642. return (BcelObjectType) rtDelegate;
  643. } else {
  644. return null;
  645. }
  646. }
  647. public void tidyUp() {
  648. // At end of compile, close any open files so deletion of those archives
  649. // is possible
  650. classPath.closeArchives();
  651. typeMap.report();
  652. typeMap.demote(true);
  653. // ResolvedType.resetPrimitives();
  654. }
  655. // / The repository interface methods
  656. @Override
  657. public JavaClass findClass(String className) {
  658. return lookupJavaClass(classPath, className);
  659. }
  660. @Override
  661. public JavaClass loadClass(String className) throws ClassNotFoundException {
  662. return lookupJavaClass(classPath, className);
  663. }
  664. @Override
  665. public void storeClass(JavaClass clazz) {
  666. // doesn't need to do anything
  667. }
  668. @Override
  669. public void removeClass(JavaClass clazz) {
  670. throw new RuntimeException("Not implemented");
  671. }
  672. @Override
  673. public JavaClass loadClass(Class clazz) throws ClassNotFoundException {
  674. throw new RuntimeException("Not implemented");
  675. }
  676. @Override
  677. public void clear() {
  678. delegate.clear();
  679. // throw new RuntimeException("Not implemented");
  680. }
  681. /**
  682. * The aim of this method is to make sure a particular type is 'ok'. Some operations on the delegate for a type modify it and
  683. * this method is intended to undo that... see pr85132
  684. */
  685. @Override
  686. public void validateType(UnresolvedType type) {
  687. ResolvedType result = typeMap.get(type.getSignature());
  688. if (result == null) {
  689. return; // We haven't heard of it yet
  690. }
  691. if (!result.isExposedToWeaver()) {
  692. return; // cant need resetting
  693. }
  694. result.ensureConsistent();
  695. // If we want to rebuild it 'from scratch' then:
  696. // ClassParser cp = new ClassParser(new
  697. // ByteArrayInputStream(newbytes),new String(cs));
  698. // try {
  699. // rt.setDelegate(makeBcelObjectType(rt,cp.parse(),true));
  700. // } catch (ClassFormatException e) {
  701. // e.printStackTrace();
  702. // } catch (IOException e) {
  703. // e.printStackTrace();
  704. // }
  705. }
  706. /**
  707. * Apply a single declare parents - return true if we change the type
  708. */
  709. private boolean applyDeclareParents(DeclareParents p, ResolvedType onType) {
  710. boolean didSomething = false;
  711. List<ResolvedType> newParents = p.findMatchingNewParents(onType, true);
  712. if (!newParents.isEmpty()) {
  713. didSomething = true;
  714. BcelObjectType classType = BcelWorld.getBcelObjectType(onType);
  715. // System.err.println("need to do declare parents for: " + onType);
  716. for (ResolvedType newParent : newParents) {
  717. // We set it here so that the imminent matching for ITDs can
  718. // succeed - we still haven't done the necessary changes to the class file
  719. // itself (like transform super calls) - that is done in
  720. // BcelTypeMunger.mungeNewParent()
  721. // classType.addParent(newParent);
  722. onType.addParent(newParent);
  723. ResolvedTypeMunger newParentMunger = new NewParentTypeMunger(newParent, p.getDeclaringType());
  724. newParentMunger.setSourceLocation(p.getSourceLocation());
  725. onType.addInterTypeMunger(new BcelTypeMunger(newParentMunger, getCrosscuttingMembersSet()
  726. .findAspectDeclaringParents(p)), false);
  727. }
  728. }
  729. return didSomething;
  730. }
  731. /**
  732. * Apply a declare @type - return true if we change the type
  733. */
  734. private boolean applyDeclareAtType(DeclareAnnotation decA, ResolvedType onType, boolean reportProblems) {
  735. boolean didSomething = false;
  736. if (decA.matches(onType)) {
  737. if (onType.hasAnnotation(decA.getAnnotation().getType())) {
  738. // already has it
  739. return false;
  740. }
  741. AnnotationAJ annoX = decA.getAnnotation();
  742. // check the annotation is suitable for the target
  743. boolean isOK = checkTargetOK(decA, onType, annoX);
  744. if (isOK) {
  745. didSomething = true;
  746. ResolvedTypeMunger newAnnotationTM = new AnnotationOnTypeMunger(annoX);
  747. newAnnotationTM.setSourceLocation(decA.getSourceLocation());
  748. onType.addInterTypeMunger(new BcelTypeMunger(newAnnotationTM, decA.getAspect().resolve(this)), false);
  749. decA.copyAnnotationTo(onType);
  750. }
  751. }
  752. return didSomething;
  753. }
  754. /**
  755. * Apply the specified declare @field construct to any matching fields in the specified type.
  756. * @param deca the declare annotation targeting fields
  757. * @param type the type to check for members matching the declare annotation
  758. * @return true if something matched and the type was modified
  759. */
  760. private boolean applyDeclareAtField(DeclareAnnotation deca, ResolvedType type) {
  761. boolean changedType = false;
  762. ResolvedMember[] fields = type.getDeclaredFields();
  763. for (ResolvedMember field: fields) {
  764. if (deca.matches(field, this)) {
  765. AnnotationAJ anno = deca.getAnnotation();
  766. if (!field.hasAnnotation(anno.getType())) {
  767. field.addAnnotation(anno);
  768. changedType=true;
  769. }
  770. }
  771. }
  772. return changedType;
  773. }
  774. /**
  775. * Checks for an @target() on the annotation and if found ensures it allows the annotation to be attached to the target type
  776. * that matched.
  777. */
  778. private boolean checkTargetOK(DeclareAnnotation decA, ResolvedType onType, AnnotationAJ annoX) {
  779. if (annoX.specifiesTarget()) {
  780. if ((onType.isAnnotation() && !annoX.allowedOnAnnotationType()) || (!annoX.allowedOnRegularType())) {
  781. return false;
  782. }
  783. }
  784. return true;
  785. }
  786. // Hmmm - very similar to the code in BcelWeaver.weaveParentTypeMungers -
  787. // this code
  788. // doesn't need to produce errors/warnings though as it won't really be
  789. // weaving.
  790. protected void weaveInterTypeDeclarations(ResolvedType onType) {
  791. List<DeclareParents> declareParentsList = getCrosscuttingMembersSet().getDeclareParents();
  792. if (onType.isRawType()) {
  793. onType = onType.getGenericType();
  794. }
  795. onType.clearInterTypeMungers();
  796. List<DeclareParents> decpToRepeat = new ArrayList<DeclareParents>();
  797. boolean aParentChangeOccurred = false;
  798. boolean anAnnotationChangeOccurred = false;
  799. // First pass - apply all decp mungers
  800. for (DeclareParents decp : declareParentsList) {
  801. boolean typeChanged = applyDeclareParents(decp, onType);
  802. if (typeChanged) {
  803. aParentChangeOccurred = true;
  804. } else { // Perhaps it would have matched if a 'dec @type' had
  805. // modified the type
  806. if (!decp.getChild().isStarAnnotation()) {
  807. decpToRepeat.add(decp);
  808. }
  809. }
  810. }
  811. // Still first pass - apply all dec @type mungers
  812. for (DeclareAnnotation decA : getCrosscuttingMembersSet().getDeclareAnnotationOnTypes()) {
  813. boolean typeChanged = applyDeclareAtType(decA, onType, true);
  814. if (typeChanged) {
  815. anAnnotationChangeOccurred = true;
  816. }
  817. }
  818. // apply declare @field
  819. for (DeclareAnnotation deca: getCrosscuttingMembersSet().getDeclareAnnotationOnFields()) {
  820. if (applyDeclareAtField(deca,onType)) {
  821. anAnnotationChangeOccurred = true;
  822. }
  823. }
  824. while ((aParentChangeOccurred || anAnnotationChangeOccurred) && !decpToRepeat.isEmpty()) {
  825. anAnnotationChangeOccurred = aParentChangeOccurred = false;
  826. List<DeclareParents> decpToRepeatNextTime = new ArrayList<DeclareParents>();
  827. for (DeclareParents decp: decpToRepeat) {
  828. if (applyDeclareParents(decp, onType)) {
  829. aParentChangeOccurred = true;
  830. } else {
  831. decpToRepeatNextTime.add(decp);
  832. }
  833. }
  834. for (DeclareAnnotation deca: getCrosscuttingMembersSet().getDeclareAnnotationOnTypes()) {
  835. if (applyDeclareAtType(deca, onType, false)) {
  836. anAnnotationChangeOccurred = true;
  837. }
  838. }
  839. for (DeclareAnnotation deca: getCrosscuttingMembersSet().getDeclareAnnotationOnFields()) {
  840. if (applyDeclareAtField(deca, onType)) {
  841. anAnnotationChangeOccurred = true;
  842. }
  843. }
  844. decpToRepeat = decpToRepeatNextTime;
  845. }
  846. }
  847. @Override
  848. public IWeavingSupport getWeavingSupport() {
  849. return bcelWeavingSupport;
  850. }
  851. @Override
  852. public void reportCheckerMatch(Checker checker, Shadow shadow) {
  853. IMessage iMessage = new Message(checker.getMessage(shadow), shadow.toString(), checker.isError() ? IMessage.ERROR
  854. : IMessage.WARNING, shadow.getSourceLocation(), null, new ISourceLocation[] { checker.getSourceLocation() }, true,
  855. 0, -1, -1);
  856. getMessageHandler().handleMessage(iMessage);
  857. if (getCrossReferenceHandler() != null) {
  858. getCrossReferenceHandler()
  859. .addCrossReference(
  860. checker.getSourceLocation(),
  861. shadow.getSourceLocation(),
  862. (checker.isError() ? IRelationship.Kind.DECLARE_ERROR.getName() : IRelationship.Kind.DECLARE_WARNING
  863. .getName()), false);
  864. }
  865. if (getModel() != null) {
  866. AsmRelationshipProvider.addDeclareErrorOrWarningRelationship(getModelAsAsmManager(), shadow, checker);
  867. }
  868. }
  869. public AsmManager getModelAsAsmManager() {
  870. return (AsmManager) getModel(); // For now... always an AsmManager in a bcel environment
  871. }
  872. void raiseError(String message) {
  873. getMessageHandler().handleMessage(MessageUtil.error(message));
  874. }
  875. /**
  876. * These are aop.xml files that can be used to alter the aspects that actually apply from those passed in - and also their scope
  877. * of application to other files in the system.
  878. *
  879. * @param xmlFiles list of File objects representing any aop.xml files passed in to configure the build process
  880. */
  881. public void setXmlFiles(List<File> xmlFiles) {
  882. if (!isXmlConfiguredWorld && !xmlFiles.isEmpty()) {
  883. raiseError("xml configuration files only supported by the compiler when -xmlConfigured option specified");
  884. return;
  885. }
  886. if (!xmlFiles.isEmpty()) {
  887. xmlConfiguration = new WeavingXmlConfig(this, WeavingXmlConfig.MODE_COMPILE);
  888. }
  889. for (File xmlfile : xmlFiles) {
  890. try {
  891. Definition d = DocumentParser.parse(xmlfile.toURI().toURL());
  892. xmlConfiguration.add(d);
  893. } catch (MalformedURLException e) {
  894. raiseError("Unexpected problem processing XML config file '" + xmlfile.getName() + "' :" + e.getMessage());
  895. } catch (Exception e) {
  896. raiseError("Unexpected problem processing XML config file '" + xmlfile.getName() + "' :" + e.getMessage());
  897. }
  898. }
  899. }
  900. /**
  901. * Add a scoped aspects where the scoping was defined in an aop.xml file and this world is being used in a LTW configuration
  902. */
  903. public void addScopedAspect(String name, String scope) {
  904. this.isXmlConfiguredWorld = true;
  905. if (xmlConfiguration == null) {
  906. xmlConfiguration = new WeavingXmlConfig(this, WeavingXmlConfig.MODE_LTW);
  907. }
  908. xmlConfiguration.addScopedAspect(name, scope);
  909. }
  910. public void setXmlConfigured(boolean b) {
  911. this.isXmlConfiguredWorld = b;
  912. }
  913. @Override
  914. public boolean isXmlConfigured() {
  915. return isXmlConfiguredWorld && xmlConfiguration != null;
  916. }
  917. public WeavingXmlConfig getXmlConfiguration() {
  918. return xmlConfiguration;
  919. }
  920. @Override
  921. public boolean isAspectIncluded(ResolvedType aspectType) {
  922. if (!isXmlConfigured()) {
  923. return true;
  924. }
  925. return xmlConfiguration.specifiesInclusionOfAspect(aspectType.getName());
  926. }
  927. @Override
  928. public TypePattern getAspectScope(ResolvedType declaringType) {
  929. return xmlConfiguration.getScopeFor(declaringType.getName());
  930. }
  931. @Override
  932. public boolean hasUnsatisfiedDependency(ResolvedType aspectType) {
  933. String aspectName = aspectType.getName();
  934. if (aspectType.hasAnnotations()) {
  935. AnnotationAJ[] annos = aspectType.getAnnotations();
  936. for (AnnotationAJ anno: annos) {
  937. if (anno.getTypeName().equals("org.aspectj.lang.annotation.RequiredTypes")) {
  938. String values = anno.getStringFormOfValue("value"); // Example: "[A,org.foo.Bar]"
  939. if (values != null && values.length() > 2) {
  940. values = values.substring(1,values.length()-1);
  941. StringTokenizer tokenizer = new StringTokenizer(values,",");
  942. boolean anythingMissing = false;
  943. while (tokenizer.hasMoreElements()) {
  944. String requiredTypeName = tokenizer.nextToken();
  945. ResolvedType rt = resolve(UnresolvedType.forName(requiredTypeName));
  946. if (rt.isMissing()) {
  947. if (!getMessageHandler().isIgnoring(IMessage.INFO)) {
  948. getMessageHandler().handleMessage(
  949. MessageUtil.info("deactivating aspect '" + aspectName + "' as it requires type '"
  950. + requiredTypeName + "' which cannot be found on the classpath"));
  951. }
  952. anythingMissing = true;
  953. if (aspectRequiredTypes == null) {
  954. aspectRequiredTypes = new HashMap<String,String>();
  955. }
  956. // Record that it has an invalid type reference
  957. aspectRequiredTypes.put(aspectName,requiredTypeName);
  958. }
  959. }
  960. if (anythingMissing) {
  961. return true;
  962. }
  963. else {
  964. return false;
  965. }
  966. }
  967. else {
  968. // no value specified for annotation
  969. return false;
  970. }
  971. }
  972. }
  973. }
  974. if (aspectRequiredTypes == null) {
  975. // no aspects require anything, so there can be no unsatisfied dependencies
  976. return false;
  977. }
  978. if (!aspectRequiredTypesProcessed.contains(aspectName)) {
  979. String requiredTypeName = aspectRequiredTypes.get(aspectName);
  980. if (requiredTypeName==null) {
  981. aspectRequiredTypesProcessed.add(aspectName);
  982. return false;
  983. } else {
  984. ResolvedType rt = resolve(UnresolvedType.forName(requiredTypeName));
  985. if (!rt.isMissing()) {
  986. aspectRequiredTypesProcessed.add(aspectName);
  987. aspectRequiredTypes.remove(aspectName);
  988. return false;
  989. } else {
  990. if (!getMessageHandler().isIgnoring(IMessage.INFO)) {
  991. getMessageHandler().handleMessage(
  992. MessageUtil.info("deactivating aspect '" + aspectName + "' as it requires type '"
  993. + requiredTypeName + "' which cannot be found on the classpath"));
  994. }
  995. aspectRequiredTypesProcessed.add(aspectName);
  996. return true;
  997. }
  998. }
  999. }
  1000. return aspectRequiredTypes.containsKey(aspectName);
  1001. }
  1002. private List<String> aspectRequiredTypesProcessed = new ArrayList<String>();
  1003. private Map<String, String> aspectRequiredTypes = null;
  1004. public void addAspectRequires(String aspectClassName, String requiredType) {
  1005. if (aspectRequiredTypes == null) {
  1006. aspectRequiredTypes = new HashMap<String, String>();
  1007. }
  1008. aspectRequiredTypes.put(aspectClassName,requiredType);
  1009. }
  1010. /**
  1011. * A WeavingXmlConfig is initially a collection of definitions from XML files - once the world is ready and weaving is running
  1012. * it will initialize and transform those definitions into an optimized set of values (eg. resolve type patterns and string
  1013. * names to real entities). It can then answer questions quickly: (1) is this aspect included in the weaving? (2) Is there a
  1014. * scope specified for this aspect and does it include type X?
  1015. *
  1016. */
  1017. static class WeavingXmlConfig {
  1018. final static int MODE_COMPILE = 1;
  1019. final static int MODE_LTW = 2;
  1020. private int mode;
  1021. private boolean initialized = false; // Lazily done
  1022. private List<Definition> definitions = new ArrayList<Definition>();
  1023. private List<String> resolvedIncludedAspects = new ArrayList<String>();
  1024. private Map<String, TypePattern> scopes = new HashMap<String, TypePattern>();
  1025. // these are not set for LTW mode (exclusion of these fast match patterns is handled before the weaver/world are used)
  1026. private List<String> includedFastMatchPatterns = Collections.emptyList();
  1027. private List<TypePattern> includedPatterns = Collections.emptyList();
  1028. private List<String> excludedFastMatchPatterns = Collections.emptyList();
  1029. private List<TypePattern> excludedPatterns = Collections.emptyList();
  1030. private BcelWorld world;
  1031. public WeavingXmlConfig(BcelWorld bcelWorld, int mode) {
  1032. this.world = bcelWorld;
  1033. this.mode = mode;
  1034. }
  1035. public void add(Definition d) {
  1036. definitions.add(d);
  1037. }
  1038. public void addScopedAspect(String aspectName, String scope) {
  1039. ensureInitialized();
  1040. resolvedIncludedAspects.add(aspectName);
  1041. try {
  1042. TypePattern scopePattern = new PatternParser(scope).parseTypePattern();
  1043. scopePattern.resolve(world);
  1044. scopes.put(aspectName, scopePattern);
  1045. if (!world.getMessageHandler().isIgnoring(IMessage.INFO)) {
  1046. world.getMessageHandler().handleMessage(
  1047. MessageUtil.info("Aspect '" + aspectName + "' is scoped to apply against types matching pattern '"
  1048. + scopePattern.toString() + "'"));
  1049. }
  1050. } catch (Exception e) {
  1051. world.getMessageHandler().handleMessage(
  1052. MessageUtil.error("Unable to parse scope as type pattern. Scope was '" + scope + "': " + e.getMessage()));
  1053. }
  1054. }
  1055. public void ensureInitialized() {
  1056. if (!initialized) {
  1057. try {
  1058. resolvedIncludedAspects = new ArrayList<String>();
  1059. // Process the definitions into something more optimal
  1060. for (Definition definition : definitions) {
  1061. List<String> aspectNames = definition.getAspectClassNames();
  1062. for (String name : aspectNames) {
  1063. resolvedIncludedAspects.add(name);
  1064. // TODO check for existence?
  1065. // ResolvedType resolvedAspect = resolve(UnresolvedType.forName(name));
  1066. // if (resolvedAspect.isMissing()) {
  1067. // // ERROR
  1068. // } else {
  1069. // resolvedIncludedAspects.add(resolvedAspect);
  1070. // }
  1071. String scope = definition.getScopeForAspect(name);
  1072. if (scope != null) {
  1073. // Resolve the type pattern
  1074. try {
  1075. TypePattern scopePattern = new PatternParser(scope).parseTypePattern();
  1076. scopePattern.resolve(world);
  1077. scopes.put(name, scopePattern);
  1078. if (!world.getMessageHandler().isIgnoring(IMessage.INFO)) {
  1079. world.getMessageHandler().handleMessage(
  1080. MessageUtil.info("Aspect '" + name
  1081. + "' is scoped to apply against types matching pattern '"
  1082. + scopePattern.toString() + "'"));
  1083. }
  1084. } catch (Exception e) {
  1085. // TODO definitions should remember which file they came from, for inclusion in this message
  1086. world.getMessageHandler().handleMessage(
  1087. MessageUtil.error("Unable to parse scope as type pattern. Scope was '" + scope + "': "
  1088. + e.getMessage()));
  1089. }
  1090. }
  1091. }
  1092. try {
  1093. List<String> includePatterns = definition.getIncludePatterns();
  1094. if (includePatterns.size() > 0) {
  1095. includedPatterns = new ArrayList<TypePattern>();
  1096. includedFastMatchPatterns = new ArrayList<String>();
  1097. }
  1098. for (String includePattern : includePatterns) {
  1099. if (includePattern.endsWith("..*")) {
  1100. // from 'blah.blah.blah..*' leave the 'blah.blah.blah.'
  1101. includedFastMatchPatterns.add(includePattern.substring(0, includePattern.length() - 2));
  1102. } else {
  1103. TypePattern includedPattern = new PatternParser(includePattern).parseTypePattern();
  1104. includedPatterns.add(includedPattern);
  1105. }
  1106. }
  1107. List<String> excludePatterns = definition.getExcludePatterns();
  1108. if (excludePatterns.size() > 0) {
  1109. excludedPatterns = new ArrayList<TypePattern>();
  1110. excludedFastMatchPatterns = new ArrayList<String>();
  1111. }
  1112. for (String excludePattern : excludePatterns) {
  1113. if (excludePattern.endsWith("..*")) {
  1114. // from 'blah.blah.blah..*' leave the 'blah.blah.blah.'
  1115. excludedFastMatchPatterns.add(excludePattern.substring(0, excludePattern.length() - 2));
  1116. } else {
  1117. TypePattern excludedPattern = new PatternParser(excludePattern).parseTypePattern();
  1118. excludedPatterns.add(excludedPattern);
  1119. }
  1120. }
  1121. } catch (ParserException pe) {
  1122. // TODO definitions should remember which file they came from, for inclusion in this message
  1123. world.getMessageHandler().handleMessage(
  1124. MessageUtil.error("Unable to parse type pattern: " + pe.getMessage()));
  1125. }
  1126. }
  1127. } finally {
  1128. initialized = true;
  1129. }
  1130. }
  1131. }
  1132. public boolean specifiesInclusionOfAspect(String name) {
  1133. ensureInitialized();
  1134. return resolvedIncludedAspects.contains(name);
  1135. }
  1136. public TypePattern getScopeFor(String name) {
  1137. return scopes.get(name);
  1138. }
  1139. // Can't quite follow the same rules for exclusion as used for loadtime weaving:
  1140. // "The set of types to be woven are those types matched by at least one weaver include element and not matched by any
  1141. // weaver
  1142. // exclude element. If there are no weaver include statements then all non-excluded types are included."
  1143. // Since if the weaver is seeing it during this kind of build, the type is implicitly included. So all we should check
  1144. // for is exclusion
  1145. public boolean excludesType(ResolvedType type) {
  1146. if (mode == MODE_LTW) {
  1147. return false;
  1148. }
  1149. String typename = type.getName();
  1150. boolean excluded = false;
  1151. for (String excludedPattern : excludedFastMatchPatterns) {
  1152. if (typename.startsWith(excludedPattern)) {
  1153. excluded = true;
  1154. break;
  1155. }
  1156. }
  1157. if (!excluded) {
  1158. for (TypePattern excludedPattern : excludedPatterns) {
  1159. if (excludedPattern.matchesStatically(type)) {
  1160. excluded = true;
  1161. break;
  1162. }
  1163. }
  1164. }
  1165. return excluded;
  1166. }
  1167. }
  1168. @Override
  1169. public TypeMap getTypeMap() {
  1170. return typeMap;
  1171. }
  1172. @Override
  1173. public boolean isLoadtimeWeaving() {
  1174. return false;
  1175. }
  1176. public void addTypeDelegateResolver(TypeDelegateResolver typeDelegateResolver) {
  1177. if (typeDelegateResolvers == null) {
  1178. typeDelegateResolvers = new ArrayList<TypeDelegateResolver>();
  1179. }
  1180. typeDelegateResolvers.add(typeDelegateResolver);
  1181. }
  1182. @Override
  1183. public void classWriteEvent(char[][] compoundName) {
  1184. typeMap.classWriteEvent(new String(CharOperation.concatWith(compoundName, '.')));
  1185. }
  1186. /**
  1187. * Force demote a type.
  1188. */
  1189. public void demote(ResolvedType type) {
  1190. typeMap.demote(type);
  1191. }
  1192. }