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 45KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300
  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().indexOf("no debug info available") != -1) {
  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.indexOf(".jar") != -1) {
  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. return null;
  402. } finally {
  403. if (file != null) {
  404. file.close();
  405. }
  406. }
  407. }
  408. // public BcelObjectType addSourceObjectType(JavaClass jc) {
  409. // return addSourceObjectType(jc.getClassName(), jc, -1);
  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 fromTheMap = typeMap.get(signature);
  421. if (fromTheMap != null && !(fromTheMap 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=[" + fromTheMap + "] Class=[" + fromTheMap.getClass() + "]");
  426. throw new BCException(exceptionText.toString());
  427. }
  428. ReferenceType nameTypeX = (ReferenceType) fromTheMap;
  429. if (nameTypeX == 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. nameTypeX = new ReferenceType(signature, this);
  441. ret = buildBcelDelegate(nameTypeX, jc, artificial, true);
  442. typeMap.put(signature, nameTypeX);
  443. }
  444. } else {
  445. ret = buildBcelDelegate(nameTypeX, jc, artificial, true);
  446. }
  447. return ret;
  448. }
  449. public BcelObjectType addSourceObjectType(String classname, byte[] bytes, boolean artificial) {
  450. BcelObjectType ret = null;
  451. String signature = UnresolvedType.forName(classname).getSignature();
  452. ResolvedType fromTheMap = typeMap.get(signature);
  453. if (fromTheMap != null && !(fromTheMap 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=[" + fromTheMap + "] Class=[" + fromTheMap.getClass() + "]");
  458. throw new BCException(exceptionText.toString());
  459. }
  460. ReferenceType nameTypeX = (ReferenceType) fromTheMap;
  461. if (nameTypeX == null) {
  462. JavaClass jc = Utility.makeJavaClass(classname, bytes);
  463. if (jc.isGeneric() && isInJava5Mode()) {
  464. nameTypeX = ReferenceType.fromTypeX(UnresolvedType.forRawTypeName(jc.getClassName()), this);
  465. ret = buildBcelDelegate(nameTypeX, jc, artificial, true);
  466. ReferenceType genericRefType = new ReferenceType(UnresolvedType.forGenericTypeSignature(signature,
  467. ret.getDeclaredGenericSignature()), this);
  468. nameTypeX.setDelegate(ret);
  469. genericRefType.setDelegate(ret);
  470. nameTypeX.setGenericType(genericRefType);
  471. typeMap.put(signature, nameTypeX);
  472. } else {
  473. nameTypeX = new ReferenceType(signature, this);
  474. ret = buildBcelDelegate(nameTypeX, jc, artificial, true);
  475. typeMap.put(signature, nameTypeX);
  476. }
  477. } else {
  478. Object o = nameTypeX.getDelegate();
  479. if (!(o instanceof BcelObjectType)) {
  480. throw new IllegalStateException("For " + classname + " should be BcelObjectType, but is " + o.getClass());
  481. }
  482. ret = (BcelObjectType) o;
  483. // byte[] bs = ret.javaClass.getBytes();
  484. // if (bs.length != bytes.length) {
  485. // throw new RuntimeException("");
  486. // }
  487. // If the type is already exposed to the weaver (ret.isExposedToWeaver()) then this is likely
  488. // to be a hotswap reweave so build a new delegate, dont accidentally use the old data
  489. if (ret.isArtificial() || ret.isExposedToWeaver()) {
  490. // System.out.println("Rebuilding " + nameTypeX.getName());
  491. ret = buildBcelDelegate(nameTypeX, Utility.makeJavaClass(classname, bytes), artificial, true);
  492. } else {
  493. ret.setExposedToWeaver(true);
  494. }
  495. }
  496. return ret;
  497. }
  498. void deleteSourceObjectType(UnresolvedType ty) {
  499. typeMap.remove(ty.getSignature());
  500. }
  501. public static Member makeFieldJoinPointSignature(LazyClassGen cg, FieldInstruction fi) {
  502. ConstantPool cpg = cg.getConstantPool();
  503. return MemberImpl.field(fi.getClassName(cpg),
  504. (fi.opcode == Constants.GETSTATIC || fi.opcode == Constants.PUTSTATIC) ? Modifier.STATIC : 0, fi.getName(cpg),
  505. fi.getSignature(cpg));
  506. }
  507. public Member makeJoinPointSignatureFromMethod(LazyMethodGen mg, MemberKind kind) {
  508. Member ret = mg.getMemberView();
  509. if (ret == null) {
  510. int mods = mg.getAccessFlags();
  511. if (mg.getEnclosingClass().isInterface()) {
  512. mods |= Modifier.INTERFACE;
  513. }
  514. return new ResolvedMemberImpl(kind, UnresolvedType.forName(mg.getClassName()), mods, fromBcel(mg.getReturnType()),
  515. mg.getName(), fromBcel(mg.getArgumentTypes()));
  516. } else {
  517. return ret;
  518. }
  519. }
  520. public Member makeJoinPointSignatureForMonitorEnter(LazyClassGen cg, InstructionHandle h) {
  521. return MemberImpl.monitorEnter();
  522. }
  523. public Member makeJoinPointSignatureForMonitorExit(LazyClassGen cg, InstructionHandle h) {
  524. return MemberImpl.monitorExit();
  525. }
  526. public Member makeJoinPointSignatureForArrayConstruction(LazyClassGen cg, InstructionHandle handle) {
  527. Instruction i = handle.getInstruction();
  528. ConstantPool cpg = cg.getConstantPool();
  529. Member retval = null;
  530. if (i.opcode == Constants.ANEWARRAY) {
  531. // ANEWARRAY arrayInstruction = (ANEWARRAY)i;
  532. Type ot = i.getType(cpg);
  533. UnresolvedType ut = fromBcel(ot);
  534. ut = UnresolvedType.makeArray(ut, 1);
  535. retval = MemberImpl.method(ut, Modifier.PUBLIC, UnresolvedType.VOID, "<init>", new ResolvedType[] { INT });
  536. } else if (i instanceof MULTIANEWARRAY) {
  537. MULTIANEWARRAY arrayInstruction = (MULTIANEWARRAY) i;
  538. UnresolvedType ut = null;
  539. short dimensions = arrayInstruction.getDimensions();
  540. ObjectType ot = arrayInstruction.getLoadClassType(cpg);
  541. if (ot != null) {
  542. ut = fromBcel(ot);
  543. ut = UnresolvedType.makeArray(ut, dimensions);
  544. } else {
  545. Type t = arrayInstruction.getType(cpg);
  546. ut = fromBcel(t);
  547. }
  548. ResolvedType[] parms = new ResolvedType[dimensions];
  549. for (int ii = 0; ii < dimensions; ii++) {
  550. parms[ii] = INT;
  551. }
  552. retval = MemberImpl.method(ut, Modifier.PUBLIC, UnresolvedType.VOID, "<init>", parms);
  553. } else if (i.opcode == Constants.NEWARRAY) {
  554. // NEWARRAY arrayInstruction = (NEWARRAY)i;
  555. Type ot = i.getType();
  556. UnresolvedType ut = fromBcel(ot);
  557. retval = MemberImpl.method(ut, Modifier.PUBLIC, UnresolvedType.VOID, "<init>", new ResolvedType[] { INT });
  558. } else {
  559. throw new BCException("Cannot create array construction signature for this non-array instruction:" + i);
  560. }
  561. return retval;
  562. }
  563. public Member makeJoinPointSignatureForMethodInvocation(LazyClassGen cg, InvokeInstruction ii) {
  564. ConstantPool cpg = cg.getConstantPool();
  565. String name = ii.getName(cpg);
  566. String declaring = ii.getClassName(cpg);
  567. UnresolvedType declaringType = null;
  568. String signature = ii.getSignature(cpg);
  569. int modifier = (ii instanceof INVOKEINTERFACE) ? Modifier.INTERFACE
  570. : (ii.opcode == Constants.INVOKESTATIC) ? Modifier.STATIC : (ii.opcode == Constants.INVOKESPECIAL && !name
  571. .equals("<init>")) ? Modifier.PRIVATE : 0;
  572. // in Java 1.4 and after, static method call of super class within
  573. // subclass method appears
  574. // as declared by the subclass in the bytecode - but they are not
  575. // see #104212
  576. if (ii.opcode == Constants.INVOKESTATIC) {
  577. ResolvedType appearsDeclaredBy = resolve(declaring);
  578. // look for the method there
  579. for (Iterator<ResolvedMember> iterator = appearsDeclaredBy.getMethods(true, true); iterator.hasNext();) {
  580. ResolvedMember method = iterator.next();
  581. if (Modifier.isStatic(method.getModifiers())) {
  582. if (name.equals(method.getName()) && signature.equals(method.getSignature())) {
  583. // we found it
  584. declaringType = method.getDeclaringType();
  585. break;
  586. }
  587. }
  588. }
  589. }
  590. if (declaringType == null) {
  591. if (declaring.charAt(0) == '[') {
  592. declaringType = UnresolvedType.forSignature(declaring);
  593. } else {
  594. declaringType = UnresolvedType.forName(declaring);
  595. }
  596. }
  597. return MemberImpl.method(declaringType, modifier, name, signature);
  598. }
  599. @Override
  600. public String toString() {
  601. StringBuffer buf = new StringBuffer();
  602. buf.append("BcelWorld(");
  603. // buf.append(shadowMungerMap);
  604. buf.append(")");
  605. return buf.toString();
  606. }
  607. /**
  608. * Retrieve a bcel delegate for an aspect - this will return NULL if the delegate is an EclipseSourceType and not a
  609. * BcelObjectType - this happens quite often when incrementally compiling.
  610. */
  611. public static BcelObjectType getBcelObjectType(ResolvedType concreteAspect) {
  612. if (concreteAspect == null) {
  613. return null;
  614. }
  615. if (!(concreteAspect instanceof ReferenceType)) { // Might be Missing
  616. return null;
  617. }
  618. ReferenceTypeDelegate rtDelegate = ((ReferenceType) concreteAspect).getDelegate();
  619. if (rtDelegate instanceof BcelObjectType) {
  620. return (BcelObjectType) rtDelegate;
  621. } else {
  622. return null;
  623. }
  624. }
  625. public void tidyUp() {
  626. // At end of compile, close any open files so deletion of those archives
  627. // is possible
  628. classPath.closeArchives();
  629. typeMap.report();
  630. typeMap.demote(true);
  631. // ResolvedType.resetPrimitives();
  632. }
  633. // / The repository interface methods
  634. public JavaClass findClass(String className) {
  635. return lookupJavaClass(classPath, className);
  636. }
  637. public JavaClass loadClass(String className) throws ClassNotFoundException {
  638. return lookupJavaClass(classPath, className);
  639. }
  640. public void storeClass(JavaClass clazz) {
  641. // doesn't need to do anything
  642. }
  643. public void removeClass(JavaClass clazz) {
  644. throw new RuntimeException("Not implemented");
  645. }
  646. public JavaClass loadClass(Class clazz) throws ClassNotFoundException {
  647. throw new RuntimeException("Not implemented");
  648. }
  649. public void clear() {
  650. delegate.clear();
  651. // throw new RuntimeException("Not implemented");
  652. }
  653. /**
  654. * 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
  655. * this method is intended to undo that... see pr85132
  656. */
  657. @Override
  658. public void validateType(UnresolvedType type) {
  659. ResolvedType result = typeMap.get(type.getSignature());
  660. if (result == null) {
  661. return; // We haven't heard of it yet
  662. }
  663. if (!result.isExposedToWeaver()) {
  664. return; // cant need resetting
  665. }
  666. result.ensureConsistent();
  667. // If we want to rebuild it 'from scratch' then:
  668. // ClassParser cp = new ClassParser(new
  669. // ByteArrayInputStream(newbytes),new String(cs));
  670. // try {
  671. // rt.setDelegate(makeBcelObjectType(rt,cp.parse(),true));
  672. // } catch (ClassFormatException e) {
  673. // e.printStackTrace();
  674. // } catch (IOException e) {
  675. // e.printStackTrace();
  676. // }
  677. }
  678. /**
  679. * Apply a single declare parents - return true if we change the type
  680. */
  681. private boolean applyDeclareParents(DeclareParents p, ResolvedType onType) {
  682. boolean didSomething = false;
  683. List<ResolvedType> newParents = p.findMatchingNewParents(onType, true);
  684. if (!newParents.isEmpty()) {
  685. didSomething = true;
  686. BcelObjectType classType = BcelWorld.getBcelObjectType(onType);
  687. // System.err.println("need to do declare parents for: " + onType);
  688. for (ResolvedType newParent : newParents) {
  689. // We set it here so that the imminent matching for ITDs can
  690. // succeed - we still haven't done the necessary changes to the class file
  691. // itself (like transform super calls) - that is done in
  692. // BcelTypeMunger.mungeNewParent()
  693. // classType.addParent(newParent);
  694. onType.addParent(newParent);
  695. ResolvedTypeMunger newParentMunger = new NewParentTypeMunger(newParent, p.getDeclaringType());
  696. newParentMunger.setSourceLocation(p.getSourceLocation());
  697. onType.addInterTypeMunger(new BcelTypeMunger(newParentMunger, getCrosscuttingMembersSet()
  698. .findAspectDeclaringParents(p)), false);
  699. }
  700. }
  701. return didSomething;
  702. }
  703. /**
  704. * Apply a declare @type - return true if we change the type
  705. */
  706. private boolean applyDeclareAtType(DeclareAnnotation decA, ResolvedType onType, boolean reportProblems) {
  707. boolean didSomething = false;
  708. if (decA.matches(onType)) {
  709. if (onType.hasAnnotation(decA.getAnnotation().getType())) {
  710. // already has it
  711. return false;
  712. }
  713. AnnotationAJ annoX = decA.getAnnotation();
  714. // check the annotation is suitable for the target
  715. boolean isOK = checkTargetOK(decA, onType, annoX);
  716. if (isOK) {
  717. didSomething = true;
  718. ResolvedTypeMunger newAnnotationTM = new AnnotationOnTypeMunger(annoX);
  719. newAnnotationTM.setSourceLocation(decA.getSourceLocation());
  720. onType.addInterTypeMunger(new BcelTypeMunger(newAnnotationTM, decA.getAspect().resolve(this)), false);
  721. decA.copyAnnotationTo(onType);
  722. }
  723. }
  724. return didSomething;
  725. }
  726. /**
  727. * Apply the specified declare @field construct to any matching fields in the specified type.
  728. * @param deca the declare annotation targeting fields
  729. * @param type the type to check for members matching the declare annotation
  730. * @return true if something matched and the type was modified
  731. */
  732. private boolean applyDeclareAtField(DeclareAnnotation deca, ResolvedType type) {
  733. boolean changedType = false;
  734. ResolvedMember[] fields = type.getDeclaredFields();
  735. for (ResolvedMember field: fields) {
  736. if (deca.matches(field, this)) {
  737. AnnotationAJ anno = deca.getAnnotation();
  738. if (!field.hasAnnotation(anno.getType())) {
  739. field.addAnnotation(anno);
  740. changedType=true;
  741. }
  742. }
  743. }
  744. return changedType;
  745. }
  746. /**
  747. * Checks for an @target() on the annotation and if found ensures it allows the annotation to be attached to the target type
  748. * that matched.
  749. */
  750. private boolean checkTargetOK(DeclareAnnotation decA, ResolvedType onType, AnnotationAJ annoX) {
  751. if (annoX.specifiesTarget()) {
  752. if ((onType.isAnnotation() && !annoX.allowedOnAnnotationType()) || (!annoX.allowedOnRegularType())) {
  753. return false;
  754. }
  755. }
  756. return true;
  757. }
  758. // Hmmm - very similar to the code in BcelWeaver.weaveParentTypeMungers -
  759. // this code
  760. // doesn't need to produce errors/warnings though as it won't really be
  761. // weaving.
  762. protected void weaveInterTypeDeclarations(ResolvedType onType) {
  763. List<DeclareParents> declareParentsList = getCrosscuttingMembersSet().getDeclareParents();
  764. if (onType.isRawType()) {
  765. onType = onType.getGenericType();
  766. }
  767. onType.clearInterTypeMungers();
  768. List<DeclareParents> decpToRepeat = new ArrayList<DeclareParents>();
  769. boolean aParentChangeOccurred = false;
  770. boolean anAnnotationChangeOccurred = false;
  771. // First pass - apply all decp mungers
  772. for (Iterator<DeclareParents> i = declareParentsList.iterator(); i.hasNext();) {
  773. DeclareParents decp = i.next();
  774. boolean typeChanged = applyDeclareParents(decp, onType);
  775. if (typeChanged) {
  776. aParentChangeOccurred = true;
  777. } else { // Perhaps it would have matched if a 'dec @type' had
  778. // modified the type
  779. if (!decp.getChild().isStarAnnotation()) {
  780. decpToRepeat.add(decp);
  781. }
  782. }
  783. }
  784. // Still first pass - apply all dec @type mungers
  785. for (DeclareAnnotation decA : getCrosscuttingMembersSet().getDeclareAnnotationOnTypes()) {
  786. boolean typeChanged = applyDeclareAtType(decA, onType, true);
  787. if (typeChanged) {
  788. anAnnotationChangeOccurred = true;
  789. }
  790. }
  791. // apply declare @field
  792. for (DeclareAnnotation deca: getCrosscuttingMembersSet().getDeclareAnnotationOnFields()) {
  793. if (applyDeclareAtField(deca,onType)) {
  794. anAnnotationChangeOccurred = true;
  795. }
  796. }
  797. while ((aParentChangeOccurred || anAnnotationChangeOccurred) && !decpToRepeat.isEmpty()) {
  798. anAnnotationChangeOccurred = aParentChangeOccurred = false;
  799. List<DeclareParents> decpToRepeatNextTime = new ArrayList<DeclareParents>();
  800. for (DeclareParents decp: decpToRepeat) {
  801. if (applyDeclareParents(decp, onType)) {
  802. aParentChangeOccurred = true;
  803. } else {
  804. decpToRepeatNextTime.add(decp);
  805. }
  806. }
  807. for (DeclareAnnotation deca: getCrosscuttingMembersSet().getDeclareAnnotationOnTypes()) {
  808. if (applyDeclareAtType(deca, onType, false)) {
  809. anAnnotationChangeOccurred = true;
  810. }
  811. }
  812. for (DeclareAnnotation deca: getCrosscuttingMembersSet().getDeclareAnnotationOnFields()) {
  813. if (applyDeclareAtField(deca, onType)) {
  814. anAnnotationChangeOccurred = true;
  815. }
  816. }
  817. decpToRepeat = decpToRepeatNextTime;
  818. }
  819. }
  820. @Override
  821. public IWeavingSupport getWeavingSupport() {
  822. return bcelWeavingSupport;
  823. }
  824. @Override
  825. public void reportCheckerMatch(Checker checker, Shadow shadow) {
  826. IMessage iMessage = new Message(checker.getMessage(shadow), shadow.toString(), checker.isError() ? IMessage.ERROR
  827. : IMessage.WARNING, shadow.getSourceLocation(), null, new ISourceLocation[] { checker.getSourceLocation() }, true,
  828. 0, -1, -1);
  829. getMessageHandler().handleMessage(iMessage);
  830. if (getCrossReferenceHandler() != null) {
  831. getCrossReferenceHandler()
  832. .addCrossReference(
  833. checker.getSourceLocation(),
  834. shadow.getSourceLocation(),
  835. (checker.isError() ? IRelationship.Kind.DECLARE_ERROR.getName() : IRelationship.Kind.DECLARE_WARNING
  836. .getName()), false);
  837. }
  838. if (getModel() != null) {
  839. AsmRelationshipProvider.addDeclareErrorOrWarningRelationship(getModelAsAsmManager(), shadow, checker);
  840. }
  841. }
  842. public AsmManager getModelAsAsmManager() {
  843. return (AsmManager) getModel(); // For now... always an AsmManager in a bcel environment
  844. }
  845. void raiseError(String message) {
  846. getMessageHandler().handleMessage(MessageUtil.error(message));
  847. }
  848. /**
  849. * These are aop.xml files that can be used to alter the aspects that actually apply from those passed in - and also their scope
  850. * of application to other files in the system.
  851. *
  852. * @param xmlFiles list of File objects representing any aop.xml files passed in to configure the build process
  853. */
  854. public void setXmlFiles(List<File> xmlFiles) {
  855. if (!isXmlConfiguredWorld && !xmlFiles.isEmpty()) {
  856. raiseError("xml configuration files only supported by the compiler when -xmlConfigured option specified");
  857. return;
  858. }
  859. if (!xmlFiles.isEmpty()) {
  860. xmlConfiguration = new WeavingXmlConfig(this, WeavingXmlConfig.MODE_COMPILE);
  861. }
  862. for (File xmlfile : xmlFiles) {
  863. try {
  864. Definition d = DocumentParser.parse(xmlfile.toURI().toURL());
  865. xmlConfiguration.add(d);
  866. } catch (MalformedURLException e) {
  867. raiseError("Unexpected problem processing XML config file '" + xmlfile.getName() + "' :" + e.getMessage());
  868. } catch (Exception e) {
  869. raiseError("Unexpected problem processing XML config file '" + xmlfile.getName() + "' :" + e.getMessage());
  870. }
  871. }
  872. }
  873. /**
  874. * Add a scoped aspects where the scoping was defined in an aop.xml file and this world is being used in a LTW configuration
  875. */
  876. public void addScopedAspect(String name, String scope) {
  877. this.isXmlConfiguredWorld = true;
  878. if (xmlConfiguration == null) {
  879. xmlConfiguration = new WeavingXmlConfig(this, WeavingXmlConfig.MODE_LTW);
  880. }
  881. xmlConfiguration.addScopedAspect(name, scope);
  882. }
  883. public void setXmlConfigured(boolean b) {
  884. this.isXmlConfiguredWorld = b;
  885. }
  886. @Override
  887. public boolean isXmlConfigured() {
  888. return isXmlConfiguredWorld && xmlConfiguration != null;
  889. }
  890. public WeavingXmlConfig getXmlConfiguration() {
  891. return xmlConfiguration;
  892. }
  893. @Override
  894. public boolean isAspectIncluded(ResolvedType aspectType) {
  895. if (!isXmlConfigured()) {
  896. return true;
  897. }
  898. return xmlConfiguration.specifiesInclusionOfAspect(aspectType.getName());
  899. }
  900. @Override
  901. public TypePattern getAspectScope(ResolvedType declaringType) {
  902. return xmlConfiguration.getScopeFor(declaringType.getName());
  903. }
  904. @Override
  905. public boolean hasUnsatisfiedDependency(ResolvedType aspectType) {
  906. String aspectName = aspectType.getName();
  907. if (aspectType.hasAnnotations()) {
  908. AnnotationAJ[] annos = aspectType.getAnnotations();
  909. for (AnnotationAJ anno: annos) {
  910. if (anno.getTypeName().equals("org.aspectj.lang.annotation.RequiredTypes")) {
  911. String values = anno.getStringFormOfValue("value"); // Example: "[A,org.foo.Bar]"
  912. if (values != null && values.length() > 2) {
  913. values = values.substring(1,values.length()-1);
  914. StringTokenizer tokenizer = new StringTokenizer(values,",");
  915. boolean anythingMissing = false;
  916. while (tokenizer.hasMoreElements()) {
  917. String requiredTypeName = tokenizer.nextToken();
  918. ResolvedType rt = resolve(UnresolvedType.forName(requiredTypeName));
  919. if (rt.isMissing()) {
  920. if (!getMessageHandler().isIgnoring(IMessage.INFO)) {
  921. getMessageHandler().handleMessage(
  922. MessageUtil.info("deactivating aspect '" + aspectName + "' as it requires type '"
  923. + requiredTypeName + "' which cannot be found on the classpath"));
  924. }
  925. anythingMissing = true;
  926. if (aspectRequiredTypes == null) {
  927. aspectRequiredTypes = new HashMap<String,String>();
  928. }
  929. // Record that it has an invalid type reference
  930. aspectRequiredTypes.put(aspectName,requiredTypeName);
  931. }
  932. }
  933. if (anythingMissing) {
  934. return true;
  935. }
  936. else {
  937. return false;
  938. }
  939. }
  940. else {
  941. // no value specified for annotation
  942. return false;
  943. }
  944. }
  945. }
  946. }
  947. if (aspectRequiredTypes == null) {
  948. // no aspects require anything, so there can be no unsatisfied dependencies
  949. return false;
  950. }
  951. if (!aspectRequiredTypesProcessed.contains(aspectName)) {
  952. String requiredTypeName = aspectRequiredTypes.get(aspectName);
  953. if (requiredTypeName==null) {
  954. aspectRequiredTypesProcessed.add(aspectName);
  955. return false;
  956. } else {
  957. ResolvedType rt = resolve(UnresolvedType.forName(requiredTypeName));
  958. if (!rt.isMissing()) {
  959. aspectRequiredTypesProcessed.add(aspectName);
  960. aspectRequiredTypes.remove(aspectName);
  961. return false;
  962. } else {
  963. if (!getMessageHandler().isIgnoring(IMessage.INFO)) {
  964. getMessageHandler().handleMessage(
  965. MessageUtil.info("deactivating aspect '" + aspectName + "' as it requires type '"
  966. + requiredTypeName + "' which cannot be found on the classpath"));
  967. }
  968. aspectRequiredTypesProcessed.add(aspectName);
  969. return true;
  970. }
  971. }
  972. }
  973. return aspectRequiredTypes.containsKey(aspectName);
  974. }
  975. private List<String> aspectRequiredTypesProcessed = new ArrayList<String>();
  976. private Map<String, String> aspectRequiredTypes = null;
  977. public void addAspectRequires(String aspectClassName, String requiredType) {
  978. if (aspectRequiredTypes == null) {
  979. aspectRequiredTypes = new HashMap<String, String>();
  980. }
  981. aspectRequiredTypes.put(aspectClassName,requiredType);
  982. }
  983. /**
  984. * A WeavingXmlConfig is initially a collection of definitions from XML files - once the world is ready and weaving is running
  985. * it will initialize and transform those definitions into an optimized set of values (eg. resolve type patterns and string
  986. * names to real entities). It can then answer questions quickly: (1) is this aspect included in the weaving? (2) Is there a
  987. * scope specified for this aspect and does it include type X?
  988. *
  989. */
  990. static class WeavingXmlConfig {
  991. final static int MODE_COMPILE = 1;
  992. final static int MODE_LTW = 2;
  993. private int mode;
  994. private boolean initialized = false; // Lazily done
  995. private List<Definition> definitions = new ArrayList<Definition>();
  996. private List<String> resolvedIncludedAspects = new ArrayList<String>();
  997. private Map<String, TypePattern> scopes = new HashMap<String, TypePattern>();
  998. // these are not set for LTW mode (exclusion of these fast match patterns is handled before the weaver/world are used)
  999. private List<String> includedFastMatchPatterns = Collections.emptyList();
  1000. private List<TypePattern> includedPatterns = Collections.emptyList();
  1001. private List<String> excludedFastMatchPatterns = Collections.emptyList();
  1002. private List<TypePattern> excludedPatterns = Collections.emptyList();
  1003. private BcelWorld world;
  1004. public WeavingXmlConfig(BcelWorld bcelWorld, int mode) {
  1005. this.world = bcelWorld;
  1006. this.mode = mode;
  1007. }
  1008. public void add(Definition d) {
  1009. definitions.add(d);
  1010. }
  1011. public void addScopedAspect(String aspectName, String scope) {
  1012. ensureInitialized();
  1013. resolvedIncludedAspects.add(aspectName);
  1014. try {
  1015. TypePattern scopePattern = new PatternParser(scope).parseTypePattern();
  1016. scopePattern.resolve(world);
  1017. scopes.put(aspectName, scopePattern);
  1018. if (!world.getMessageHandler().isIgnoring(IMessage.INFO)) {
  1019. world.getMessageHandler().handleMessage(
  1020. MessageUtil.info("Aspect '" + aspectName + "' is scoped to apply against types matching pattern '"
  1021. + scopePattern.toString() + "'"));
  1022. }
  1023. } catch (Exception e) {
  1024. world.getMessageHandler().handleMessage(
  1025. MessageUtil.error("Unable to parse scope as type pattern. Scope was '" + scope + "': " + e.getMessage()));
  1026. }
  1027. }
  1028. public void ensureInitialized() {
  1029. if (!initialized) {
  1030. try {
  1031. resolvedIncludedAspects = new ArrayList<String>();
  1032. // Process the definitions into something more optimal
  1033. for (Definition definition : definitions) {
  1034. List<String> aspectNames = definition.getAspectClassNames();
  1035. for (String name : aspectNames) {
  1036. resolvedIncludedAspects.add(name);
  1037. // TODO check for existence?
  1038. // ResolvedType resolvedAspect = resolve(UnresolvedType.forName(name));
  1039. // if (resolvedAspect.isMissing()) {
  1040. // // ERROR
  1041. // } else {
  1042. // resolvedIncludedAspects.add(resolvedAspect);
  1043. // }
  1044. String scope = definition.getScopeForAspect(name);
  1045. if (scope != null) {
  1046. // Resolve the type pattern
  1047. try {
  1048. TypePattern scopePattern = new PatternParser(scope).parseTypePattern();
  1049. scopePattern.resolve(world);
  1050. scopes.put(name, scopePattern);
  1051. if (!world.getMessageHandler().isIgnoring(IMessage.INFO)) {
  1052. world.getMessageHandler().handleMessage(
  1053. MessageUtil.info("Aspect '" + name
  1054. + "' is scoped to apply against types matching pattern '"
  1055. + scopePattern.toString() + "'"));
  1056. }
  1057. } catch (Exception e) {
  1058. // TODO definitions should remember which file they came from, for inclusion in this message
  1059. world.getMessageHandler().handleMessage(
  1060. MessageUtil.error("Unable to parse scope as type pattern. Scope was '" + scope + "': "
  1061. + e.getMessage()));
  1062. }
  1063. }
  1064. }
  1065. try {
  1066. List<String> includePatterns = definition.getIncludePatterns();
  1067. if (includePatterns.size() > 0) {
  1068. includedPatterns = new ArrayList<TypePattern>();
  1069. includedFastMatchPatterns = new ArrayList<String>();
  1070. }
  1071. for (String includePattern : includePatterns) {
  1072. if (includePattern.endsWith("..*")) {
  1073. // from 'blah.blah.blah..*' leave the 'blah.blah.blah.'
  1074. includedFastMatchPatterns.add(includePattern.substring(0, includePattern.length() - 2));
  1075. } else {
  1076. TypePattern includedPattern = new PatternParser(includePattern).parseTypePattern();
  1077. includedPatterns.add(includedPattern);
  1078. }
  1079. }
  1080. List<String> excludePatterns = definition.getExcludePatterns();
  1081. if (excludePatterns.size() > 0) {
  1082. excludedPatterns = new ArrayList<TypePattern>();
  1083. excludedFastMatchPatterns = new ArrayList<String>();
  1084. }
  1085. for (String excludePattern : excludePatterns) {
  1086. if (excludePattern.endsWith("..*")) {
  1087. // from 'blah.blah.blah..*' leave the 'blah.blah.blah.'
  1088. excludedFastMatchPatterns.add(excludePattern.substring(0, excludePattern.length() - 2));
  1089. } else {
  1090. TypePattern excludedPattern = new PatternParser(excludePattern).parseTypePattern();
  1091. excludedPatterns.add(excludedPattern);
  1092. }
  1093. }
  1094. } catch (ParserException pe) {
  1095. // TODO definitions should remember which file they came from, for inclusion in this message
  1096. world.getMessageHandler().handleMessage(
  1097. MessageUtil.error("Unable to parse type pattern: " + pe.getMessage()));
  1098. }
  1099. }
  1100. } finally {
  1101. initialized = true;
  1102. }
  1103. }
  1104. }
  1105. public boolean specifiesInclusionOfAspect(String name) {
  1106. ensureInitialized();
  1107. return resolvedIncludedAspects.contains(name);
  1108. }
  1109. public TypePattern getScopeFor(String name) {
  1110. return scopes.get(name);
  1111. }
  1112. // Can't quite follow the same rules for exclusion as used for loadtime weaving:
  1113. // "The set of types to be woven are those types matched by at least one weaver include element and not matched by any
  1114. // weaver
  1115. // exclude element. If there are no weaver include statements then all non-excluded types are included."
  1116. // Since if the weaver is seeing it during this kind of build, the type is implicitly included. So all we should check
  1117. // for is exclusion
  1118. public boolean excludesType(ResolvedType type) {
  1119. if (mode == MODE_LTW) {
  1120. return false;
  1121. }
  1122. String typename = type.getName();
  1123. boolean excluded = false;
  1124. for (String excludedPattern : excludedFastMatchPatterns) {
  1125. if (typename.startsWith(excludedPattern)) {
  1126. excluded = true;
  1127. break;
  1128. }
  1129. }
  1130. if (!excluded) {
  1131. for (TypePattern excludedPattern : excludedPatterns) {
  1132. if (excludedPattern.matchesStatically(type)) {
  1133. excluded = true;
  1134. break;
  1135. }
  1136. }
  1137. }
  1138. return excluded;
  1139. }
  1140. }
  1141. public TypeMap getTypeMap() {
  1142. return typeMap;
  1143. }
  1144. public boolean isLoadtimeWeaving() {
  1145. return false;
  1146. }
  1147. public void addTypeDelegateResolver(TypeDelegateResolver typeDelegateResolver) {
  1148. if (typeDelegateResolvers == null) {
  1149. typeDelegateResolvers = new ArrayList<TypeDelegateResolver>();
  1150. }
  1151. typeDelegateResolvers.add(typeDelegateResolver);
  1152. }
  1153. public void classWriteEvent(char[][] compoundName) {
  1154. typeMap.classWriteEvent(new String(CharOperation.concatWith(compoundName, '.')));
  1155. }
  1156. /**
  1157. * Force demote a type.
  1158. */
  1159. public void demote(ResolvedType type) {
  1160. typeMap.demote(type);
  1161. }
  1162. }