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.

BcelWeaver.java 76KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042
  1. /* *******************************************************************
  2. * Copyright (c) 2002-2010 Contributors
  3. * All rights reserved.
  4. * This program and the accompanying materials are made available
  5. * under the terms of the Eclipse Public License v1.0
  6. * which accompanies this distribution and is available at
  7. * http://www.eclipse.org/legal/epl-v10.html
  8. * ******************************************************************/
  9. package org.aspectj.weaver.bcel;
  10. import java.io.ByteArrayInputStream;
  11. import java.io.File;
  12. import java.io.FileFilter;
  13. import java.io.FileInputStream;
  14. import java.io.FileNotFoundException;
  15. import java.io.IOException;
  16. import java.io.InputStream;
  17. import java.io.OutputStream;
  18. import java.util.ArrayList;
  19. import java.util.Collection;
  20. import java.util.Collections;
  21. import java.util.Comparator;
  22. import java.util.Enumeration;
  23. import java.util.HashMap;
  24. import java.util.HashSet;
  25. import java.util.Iterator;
  26. import java.util.List;
  27. import java.util.Map;
  28. import java.util.Set;
  29. import java.util.jar.Attributes;
  30. import java.util.jar.Attributes.Name;
  31. import java.util.jar.JarEntry;
  32. import java.util.jar.JarFile;
  33. import java.util.jar.Manifest;
  34. import java.util.zip.ZipEntry;
  35. import java.util.zip.ZipInputStream;
  36. import java.util.zip.ZipOutputStream;
  37. import org.aspectj.apache.bcel.classfile.ClassParser;
  38. import org.aspectj.apache.bcel.classfile.JavaClass;
  39. import org.aspectj.asm.AsmManager;
  40. import org.aspectj.asm.IProgramElement;
  41. import org.aspectj.asm.internal.AspectJElementHierarchy;
  42. import org.aspectj.bridge.IMessage;
  43. import org.aspectj.bridge.ISourceLocation;
  44. import org.aspectj.bridge.Message;
  45. import org.aspectj.bridge.MessageUtil;
  46. import org.aspectj.bridge.SourceLocation;
  47. import org.aspectj.bridge.WeaveMessage;
  48. import org.aspectj.bridge.context.CompilationAndWeavingContext;
  49. import org.aspectj.bridge.context.ContextToken;
  50. import org.aspectj.util.FileUtil;
  51. import org.aspectj.util.FuzzyBoolean;
  52. import org.aspectj.weaver.Advice;
  53. import org.aspectj.weaver.AdviceKind;
  54. import org.aspectj.weaver.AnnotationAJ;
  55. import org.aspectj.weaver.AnnotationOnTypeMunger;
  56. import org.aspectj.weaver.BCException;
  57. import org.aspectj.weaver.CompressingDataOutputStream;
  58. import org.aspectj.weaver.ConcreteTypeMunger;
  59. import org.aspectj.weaver.CrosscuttingMembersSet;
  60. import org.aspectj.weaver.CustomMungerFactory;
  61. import org.aspectj.weaver.IClassFileProvider;
  62. import org.aspectj.weaver.IUnwovenClassFile;
  63. import org.aspectj.weaver.IWeaveRequestor;
  64. import org.aspectj.weaver.NewParentTypeMunger;
  65. import org.aspectj.weaver.ReferenceType;
  66. import org.aspectj.weaver.ReferenceTypeDelegate;
  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.WeaverMessages;
  73. import org.aspectj.weaver.WeaverStateInfo;
  74. import org.aspectj.weaver.World;
  75. import org.aspectj.weaver.model.AsmRelationshipProvider;
  76. import org.aspectj.weaver.patterns.AndPointcut;
  77. import org.aspectj.weaver.patterns.BindingPattern;
  78. import org.aspectj.weaver.patterns.BindingTypePattern;
  79. import org.aspectj.weaver.patterns.ConcreteCflowPointcut;
  80. import org.aspectj.weaver.patterns.DeclareAnnotation;
  81. import org.aspectj.weaver.patterns.DeclareParents;
  82. import org.aspectj.weaver.patterns.DeclareTypeErrorOrWarning;
  83. import org.aspectj.weaver.patterns.FastMatchInfo;
  84. import org.aspectj.weaver.patterns.IfPointcut;
  85. import org.aspectj.weaver.patterns.KindedPointcut;
  86. import org.aspectj.weaver.patterns.NameBindingPointcut;
  87. import org.aspectj.weaver.patterns.NotPointcut;
  88. import org.aspectj.weaver.patterns.OrPointcut;
  89. import org.aspectj.weaver.patterns.Pointcut;
  90. import org.aspectj.weaver.patterns.PointcutRewriter;
  91. import org.aspectj.weaver.patterns.WithinPointcut;
  92. import org.aspectj.weaver.tools.Trace;
  93. import org.aspectj.weaver.tools.TraceFactory;
  94. /**
  95. *
  96. * @author PARC
  97. * @author Andy Clement
  98. * @author Alexandre Vasseur
  99. */
  100. public class BcelWeaver {
  101. public static final String CLOSURE_CLASS_PREFIX = "$Ajc";
  102. public static final String SYNTHETIC_CLASS_POSTFIX = "$ajc";
  103. private static Trace trace = TraceFactory.getTraceFactory().getTrace(BcelWeaver.class);
  104. private transient final BcelWorld world;
  105. private final CrosscuttingMembersSet xcutSet;
  106. private boolean inReweavableMode = false;
  107. private transient List<UnwovenClassFile> addedClasses = new ArrayList<UnwovenClassFile>();
  108. private transient List<String> deletedTypenames = new ArrayList<String>();
  109. // These four are setup by prepareForWeave
  110. private transient List<ShadowMunger> shadowMungerList = null;
  111. private transient List<ConcreteTypeMunger> typeMungerList = null;
  112. private transient List<ConcreteTypeMunger> lateTypeMungerList = null;
  113. private transient List<DeclareParents> declareParentsList = null;
  114. private Manifest manifest = null;
  115. private boolean needToReweaveWorld = false;
  116. private boolean isBatchWeave = true;
  117. private ZipOutputStream zipOutputStream;
  118. private CustomMungerFactory customMungerFactory;
  119. public BcelWeaver(BcelWorld world) {
  120. super();
  121. if (trace.isTraceEnabled()) {
  122. trace.enter("<init>", this, world);
  123. }
  124. this.world = world;
  125. this.xcutSet = world.getCrosscuttingMembersSet();
  126. if (trace.isTraceEnabled()) {
  127. trace.exit("<init>");
  128. }
  129. }
  130. /**
  131. * Add the given aspect to the weaver. The type is resolved to support DOT for static inner classes as well as DOLLAR
  132. *
  133. * @param aspectName
  134. * @return aspect
  135. */
  136. public ResolvedType addLibraryAspect(String aspectName) {
  137. if (trace.isTraceEnabled()) {
  138. trace.enter("addLibraryAspect", this, aspectName);
  139. }
  140. // 1 - resolve as is
  141. UnresolvedType unresolvedT = UnresolvedType.forName(aspectName);
  142. unresolvedT.setNeedsModifiableDelegate(true);
  143. ResolvedType type = world.resolve(unresolvedT, true);
  144. if (type.isMissing()) {
  145. // fallback on inner class lookup mechanism
  146. String fixedName = aspectName;
  147. int hasDot = fixedName.lastIndexOf('.');
  148. while (hasDot > 0) {
  149. // System.out.println("BcelWeaver.addLibraryAspect " + fixedName);
  150. char[] fixedNameChars = fixedName.toCharArray();
  151. fixedNameChars[hasDot] = '$';
  152. fixedName = new String(fixedNameChars);
  153. hasDot = fixedName.lastIndexOf('.');
  154. UnresolvedType ut = UnresolvedType.forName(fixedName);
  155. ut.setNeedsModifiableDelegate(true);
  156. type = world.resolve(ut, true);
  157. if (!type.isMissing()) {
  158. break;
  159. }
  160. }
  161. }
  162. // System.out.println("type: " + type + " for " + aspectName);
  163. if (type.isAspect()) {
  164. // Bug 119657 ensure we use the unwoven aspect
  165. WeaverStateInfo wsi = type.getWeaverState();
  166. if (wsi != null && wsi.isReweavable()) {
  167. BcelObjectType classType = getClassType(type.getName());
  168. JavaClass wovenJavaClass = classType.getJavaClass();
  169. byte[] bytes = wsi.getUnwovenClassFileData(wovenJavaClass.getBytes());
  170. JavaClass unwovenJavaClass = Utility.makeJavaClass(wovenJavaClass.getFileName(), bytes);
  171. world.storeClass(unwovenJavaClass);
  172. classType.setJavaClass(unwovenJavaClass, true);
  173. // classType.setJavaClass(Utility.makeJavaClass(classType.
  174. // getJavaClass().getFileName(),
  175. // wsi.getUnwovenClassFileData(classType.getJavaClass().getBytes(
  176. // ))));
  177. }
  178. // TODO AV - happens to reach that a lot of time: for each type
  179. // flagged reweavable X for each aspect in the weaverstate
  180. // => mainly for nothing for LTW - pbly for something in incremental
  181. // build...
  182. xcutSet.addOrReplaceAspect(type);
  183. if (trace.isTraceEnabled()) {
  184. trace.exit("addLibraryAspect", type);
  185. }
  186. if (type.getSuperclass().isAspect()) {
  187. // If the supertype includes ITDs and the user has not included
  188. // that aspect in the aop.xml, they will
  189. // not get picked up, which can give unusual behaviour! See bug
  190. // 223094
  191. // This change causes us to pick up the super aspect regardless
  192. // of what was said in the aop.xml - giving
  193. // predictable behaviour. If the user also supplied it, there
  194. // will be no problem other than the second
  195. // addition overriding the first
  196. addLibraryAspect(type.getSuperclass().getName());
  197. }
  198. return type;
  199. } else {
  200. if (type.isMissing()) {
  201. // May not be found if not visible to the classloader that can see the aop.xml during LTW
  202. IMessage message = new Message("The specified aspect '"+aspectName+"' cannot be found", null, true);
  203. world.getMessageHandler().handleMessage(message);
  204. } else {
  205. IMessage message = new Message("Cannot register '"+aspectName+"' because the type found with that name is not an aspect", null, true);
  206. world.getMessageHandler().handleMessage(message);
  207. }
  208. return null;
  209. }
  210. }
  211. /**
  212. *
  213. * @param inFile directory containing classes or zip/jar class archive
  214. */
  215. public void addLibraryJarFile(File inFile) throws IOException {
  216. List<ResolvedType> addedAspects = null;
  217. if (inFile.isDirectory()) {
  218. addedAspects = addAspectsFromDirectory(inFile);
  219. } else {
  220. addedAspects = addAspectsFromJarFile(inFile);
  221. }
  222. for (ResolvedType addedAspect : addedAspects) {
  223. xcutSet.addOrReplaceAspect(addedAspect);
  224. }
  225. }
  226. private List<ResolvedType> addAspectsFromJarFile(File inFile) throws FileNotFoundException, IOException {
  227. ZipInputStream inStream = new ZipInputStream(new FileInputStream(inFile)); // ??? buffered
  228. List<ResolvedType> addedAspects = new ArrayList<ResolvedType>();
  229. try {
  230. while (true) {
  231. ZipEntry entry = inStream.getNextEntry();
  232. if (entry == null) {
  233. break;
  234. }
  235. if (entry.isDirectory() || !entry.getName().endsWith(".class")) {
  236. continue;
  237. }
  238. // FIXME ASC performance? of this alternative soln.
  239. int size = (int) entry.getSize();
  240. ClassParser parser = new ClassParser(new ByteArrayInputStream(FileUtil.readAsByteArray(inStream)), entry.getName());
  241. JavaClass jc = parser.parse();
  242. inStream.closeEntry();
  243. ResolvedType type = world.addSourceObjectType(jc, false).getResolvedTypeX();
  244. type.setBinaryPath(inFile.getAbsolutePath());
  245. if (type.isAspect()) {
  246. addedAspects.add(type);
  247. } else {
  248. world.demote(type);
  249. }
  250. }
  251. } finally {
  252. inStream.close();
  253. }
  254. return addedAspects;
  255. }
  256. /**
  257. * Look for .class files that represent aspects in the supplied directory - return the list of accumulated aspects.
  258. *
  259. * @param directory the directory in which to look for Aspect .class files
  260. * @return the list of discovered aspects
  261. * @throws FileNotFoundException
  262. * @throws IOException
  263. */
  264. private List<ResolvedType> addAspectsFromDirectory(File directory) throws FileNotFoundException, IOException {
  265. List<ResolvedType> addedAspects = new ArrayList<ResolvedType>();
  266. File[] classFiles = FileUtil.listFiles(directory, new FileFilter() {
  267. public boolean accept(File pathname) {
  268. return pathname.getName().endsWith(".class");
  269. }
  270. });
  271. for (File classFile : classFiles) {
  272. FileInputStream fis = new FileInputStream(classFile);
  273. byte[] classBytes = FileUtil.readAsByteArray(fis);
  274. ResolvedType aspectType = isAspect(classBytes, classFile.getAbsolutePath(), directory);
  275. if (aspectType != null) {
  276. addedAspects.add(aspectType);
  277. }
  278. fis.close();
  279. }
  280. return addedAspects;
  281. }
  282. /**
  283. * Determine if the supplied bytes represent an aspect, if they do then create a ResolvedType instance for the aspect and return
  284. * it, otherwise return null
  285. *
  286. * @param classbytes the classbytes that might represent an aspect
  287. * @param name the name of the class
  288. * @param directory directory which contained the class file
  289. * @return a ResolvedType if the classbytes represent an aspect, otherwise null
  290. */
  291. private ResolvedType isAspect(byte[] classbytes, String name, File dir) throws IOException {
  292. ClassParser parser = new ClassParser(new ByteArrayInputStream(classbytes), name);
  293. JavaClass jc = parser.parse();
  294. ResolvedType type = world.addSourceObjectType(jc, false).getResolvedTypeX();
  295. String typeName = type.getName().replace('.', File.separatorChar);
  296. int end = name.lastIndexOf(typeName + ".class");
  297. String binaryPath = null;
  298. // if end is -1 then something weird happened, the class file is not in
  299. // the correct place, something like
  300. // bin/A.class when the declaration for A specifies it is in a package.
  301. if (end == -1) {
  302. binaryPath = dir.getAbsolutePath();
  303. } else {
  304. binaryPath = name.substring(0, end - 1);
  305. }
  306. type.setBinaryPath(binaryPath);
  307. if (type.isAspect()) {
  308. return type;
  309. } else {
  310. // immediately demote the type we just added since it will have
  311. // have been stuffed into the permanent map (assumed to be
  312. // an aspect)
  313. world.demote(type);
  314. return null;
  315. }
  316. }
  317. // // The ANT copy task should be used to copy resources across.
  318. // private final static boolean
  319. // CopyResourcesFromInpathDirectoriesToOutput=false;
  320. /**
  321. * Add any .class files in the directory to the outdir. Anything other than .class files in the directory (or its
  322. * subdirectories) are considered resources and are also copied.
  323. *
  324. */
  325. public List<UnwovenClassFile> addDirectoryContents(File inFile, File outDir) throws IOException {
  326. List<UnwovenClassFile> addedClassFiles = new ArrayList<UnwovenClassFile>();
  327. // Get a list of all files (i.e. everything that isnt a directory)
  328. File[] files = FileUtil.listFiles(inFile, new FileFilter() {
  329. public boolean accept(File f) {
  330. boolean accept = !f.isDirectory();
  331. return accept;
  332. }
  333. });
  334. // For each file, add it either as a real .class file or as a resource
  335. for (int i = 0; i < files.length; i++) {
  336. addedClassFiles.add(addClassFile(files[i], inFile, outDir));
  337. }
  338. return addedClassFiles;
  339. }
  340. /**
  341. * Adds all class files in the jar
  342. */
  343. public List<UnwovenClassFile> addJarFile(File inFile, File outDir, boolean canBeDirectory) {
  344. // System.err.println("? addJarFile(" + inFile + ", " + outDir + ")");
  345. List<UnwovenClassFile> addedClassFiles = new ArrayList<UnwovenClassFile>();
  346. needToReweaveWorld = true;
  347. JarFile inJar = null;
  348. try {
  349. // Is this a directory we are looking at?
  350. if (inFile.isDirectory() && canBeDirectory) {
  351. addedClassFiles.addAll(addDirectoryContents(inFile, outDir));
  352. } else {
  353. inJar = new JarFile(inFile);
  354. try {
  355. addManifest(inJar.getManifest());
  356. Enumeration entries = inJar.entries();
  357. while (entries.hasMoreElements()) {
  358. JarEntry entry = (JarEntry) entries.nextElement();
  359. InputStream inStream = inJar.getInputStream(entry);
  360. byte[] bytes = FileUtil.readAsByteArray(inStream);
  361. String filename = entry.getName();
  362. // System.out.println("? addJarFile() filename='" + filename
  363. // + "'");
  364. UnwovenClassFile classFile = new UnwovenClassFile(new File(outDir, filename).getAbsolutePath(), bytes);
  365. if (filename.endsWith(".class")) {
  366. ReferenceType type = this.addClassFile(classFile, false);
  367. StringBuffer sb = new StringBuffer();
  368. sb.append(inFile.getAbsolutePath());
  369. sb.append("!");
  370. sb.append(entry.getName());
  371. type.setBinaryPath(sb.toString());
  372. addedClassFiles.add(classFile);
  373. }
  374. // else if (!entry.isDirectory()) {
  375. //
  376. // /* bug-44190 Copy meta-data */
  377. // addResource(filename,classFile);
  378. // }
  379. inStream.close();
  380. }
  381. } finally {
  382. inJar.close();
  383. }
  384. inJar.close();
  385. }
  386. } catch (FileNotFoundException ex) {
  387. IMessage message = new Message("Could not find input jar file " + inFile.getPath() + ", ignoring", new SourceLocation(
  388. inFile, 0), false);
  389. world.getMessageHandler().handleMessage(message);
  390. } catch (IOException ex) {
  391. IMessage message = new Message("Could not read input jar file " + inFile.getPath() + "(" + ex.getMessage() + ")",
  392. new SourceLocation(inFile, 0), true);
  393. world.getMessageHandler().handleMessage(message);
  394. } finally {
  395. if (inJar != null) {
  396. try {
  397. inJar.close();
  398. } catch (IOException ex) {
  399. IMessage message = new Message("Could not close input jar file " + inFile.getPath() + "(" + ex.getMessage()
  400. + ")", new SourceLocation(inFile, 0), true);
  401. world.getMessageHandler().handleMessage(message);
  402. }
  403. }
  404. }
  405. return addedClassFiles;
  406. }
  407. public boolean needToReweaveWorld() {
  408. return needToReweaveWorld;
  409. }
  410. /**
  411. * Should be addOrReplace
  412. */
  413. public ReferenceType addClassFile(UnwovenClassFile classFile, boolean fromInpath) {
  414. addedClasses.add(classFile);
  415. ReferenceType type = world.addSourceObjectType(classFile.getJavaClass(), false).getResolvedTypeX();
  416. if (fromInpath) {
  417. type.setBinaryPath(classFile.getFilename());
  418. }
  419. return type;
  420. }
  421. public UnwovenClassFile addClassFile(File classFile, File inPathDir, File outDir) throws IOException {
  422. FileInputStream fis = new FileInputStream(classFile);
  423. byte[] bytes = FileUtil.readAsByteArray(fis);
  424. // String relativePath = files[i].getPath();
  425. // ASSERT:
  426. // files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath()
  427. // or we are in trouble...
  428. String filename = classFile.getAbsolutePath().substring(inPathDir.getAbsolutePath().length() + 1);
  429. UnwovenClassFile ucf = new UnwovenClassFile(new File(outDir, filename).getAbsolutePath(), bytes);
  430. if (filename.endsWith(".class")) {
  431. // System.err.println(
  432. // "BCELWeaver: processing class from input directory "+classFile);
  433. StringBuffer sb = new StringBuffer();
  434. sb.append(inPathDir.getAbsolutePath());
  435. sb.append("!");
  436. sb.append(filename);
  437. ReferenceType type = this.addClassFile(ucf, false);
  438. type.setBinaryPath(sb.toString());
  439. }
  440. fis.close();
  441. return ucf;
  442. }
  443. public void deleteClassFile(String typename) {
  444. deletedTypenames.add(typename);
  445. world.deleteSourceObjectType(UnresolvedType.forName(typename));
  446. }
  447. // ---- weave preparation
  448. public void setIsBatchWeave(boolean b) {
  449. isBatchWeave = b;
  450. }
  451. public void prepareForWeave() {
  452. if (trace.isTraceEnabled()) {
  453. trace.enter("prepareForWeave", this);
  454. }
  455. needToReweaveWorld = xcutSet.hasChangedSinceLastReset();
  456. // update mungers
  457. for (Iterator<UnwovenClassFile> i = addedClasses.iterator(); i.hasNext();) {
  458. UnwovenClassFile jc = i.next();
  459. String name = jc.getClassName();
  460. ResolvedType type = world.resolve(name);
  461. // No overweaving guard. If you have one then when overweaving is on the
  462. // addOrReplaceAspect will not be called when the aspect delegate changes from
  463. // EclipseSourceType to BcelObjectType. This will mean the mungers
  464. // are not picked up.
  465. if (type.isAspect()) {
  466. needToReweaveWorld |= xcutSet.addOrReplaceAspect(type);
  467. }
  468. }
  469. for (Iterator<String> i = deletedTypenames.iterator(); i.hasNext();) {
  470. String name = i.next();
  471. if (xcutSet.deleteAspect(UnresolvedType.forName(name))) {
  472. needToReweaveWorld = true;
  473. }
  474. }
  475. shadowMungerList = xcutSet.getShadowMungers();
  476. // world.debug("shadow mungers=" + shadowMungerList);
  477. rewritePointcuts(shadowMungerList);
  478. // Sometimes an error occurs during rewriting pointcuts (for example, if
  479. // ambiguous bindings
  480. // are detected) - we ought to fail the prepare when this happens
  481. // because continuing with
  482. // inconsistent pointcuts could lead to problems
  483. typeMungerList = xcutSet.getTypeMungers();
  484. lateTypeMungerList = xcutSet.getLateTypeMungers();
  485. declareParentsList = xcutSet.getDeclareParents();
  486. addCustomMungers();
  487. // The ordering here used to be based on a string compare on toString()
  488. // for the two mungers -
  489. // that breaks for the @AJ style where advice names aren't
  490. // programmatically generated. So we
  491. // have changed the sorting to be based on source location in the file -
  492. // this is reliable, in
  493. // the case of source locations missing, we assume they are 'sorted' -
  494. // i.e. the order in
  495. // which they were added to the collection is correct, this enables the
  496. // @AJ stuff to work properly.
  497. // When @AJ processing starts filling in source locations for mungers,
  498. // this code may need
  499. // a bit of alteration...
  500. Collections.sort(shadowMungerList, new Comparator<ShadowMunger>() {
  501. public int compare(ShadowMunger sm1, ShadowMunger sm2) {
  502. if (sm1.getSourceLocation() == null) {
  503. return (sm2.getSourceLocation() == null ? 0 : 1);
  504. }
  505. if (sm2.getSourceLocation() == null) {
  506. return -1;
  507. }
  508. return (sm2.getSourceLocation().getOffset() - sm1.getSourceLocation().getOffset());
  509. }
  510. });
  511. if (inReweavableMode) {
  512. world.showMessage(IMessage.INFO, WeaverMessages.format(WeaverMessages.REWEAVABLE_MODE), null, null);
  513. }
  514. if (trace.isTraceEnabled()) {
  515. trace.exit("prepareForWeave");
  516. }
  517. }
  518. private void addCustomMungers() {
  519. if (customMungerFactory != null) {
  520. for (Iterator<UnwovenClassFile> i = addedClasses.iterator(); i.hasNext();) {
  521. UnwovenClassFile jc = i.next();
  522. String name = jc.getClassName();
  523. ResolvedType type = world.resolve(name);
  524. if (type.isAspect()) {
  525. Collection<ShadowMunger> shadowMungers = customMungerFactory.createCustomShadowMungers(type);
  526. if (shadowMungers != null) {
  527. shadowMungerList.addAll(shadowMungers);
  528. }
  529. Collection<ConcreteTypeMunger> typeMungers = customMungerFactory.createCustomTypeMungers(type);
  530. if (typeMungers != null) {
  531. typeMungerList.addAll(typeMungers);
  532. }
  533. }
  534. }
  535. }
  536. }
  537. public void setCustomMungerFactory(CustomMungerFactory factory) {
  538. customMungerFactory = factory;
  539. }
  540. /*
  541. * Rewrite all of the pointcuts in the world into their most efficient form for subsequent matching. Also ensure that if
  542. * pc1.equals(pc2) then pc1 == pc2 (for non-binding pcds) by making references all point to the same instance. Since pointcuts
  543. * remember their match decision on the last shadow, this makes matching faster when many pointcuts share common elements, or
  544. * even when one single pointcut has one common element (which can be a side-effect of DNF rewriting).
  545. */
  546. private void rewritePointcuts(List<ShadowMunger> shadowMungers) {
  547. PointcutRewriter rewriter = new PointcutRewriter();
  548. for (ShadowMunger munger : shadowMungers) {
  549. Pointcut p = munger.getPointcut();
  550. Pointcut newP = rewriter.rewrite(p);
  551. // validateBindings now whilst we still have around the pointcut
  552. // that resembles what the user actually wrote in their program
  553. // text.
  554. if (munger instanceof Advice) {
  555. Advice advice = (Advice) munger;
  556. if (advice.getSignature() != null) {
  557. final int numFormals;
  558. final String names[];
  559. // If the advice is being concretized in a @AJ aspect *and*
  560. // the advice was declared in
  561. // an @AJ aspect (it could have been inherited from a code
  562. // style aspect) then
  563. // evaluate the alternative set of formals. pr125699
  564. if ((advice.getConcreteAspect().isAnnotationStyleAspect() && advice.getDeclaringAspect() != null && advice
  565. .getDeclaringAspect().resolve(world).isAnnotationStyleAspect())
  566. || advice.isAnnotationStyle()) {
  567. numFormals = advice.getBaseParameterCount();
  568. int numArgs = advice.getSignature().getParameterTypes().length;
  569. if (numFormals > 0) {
  570. names = advice.getSignature().getParameterNames(world);
  571. validateBindings(newP, p, numArgs, names);
  572. }
  573. } else {
  574. numFormals = advice.getBaseParameterCount();
  575. if (numFormals > 0) {
  576. names = advice.getBaseParameterNames(world);
  577. validateBindings(newP, p, numFormals, names);
  578. }
  579. }
  580. }
  581. }
  582. newP.m_ignoreUnboundBindingForNames = p.m_ignoreUnboundBindingForNames;
  583. munger.setPointcut(newP);
  584. }
  585. // now that we have optimized individual pointcuts, optimize
  586. // across the set of pointcuts....
  587. // Use a map from key based on pc equality, to value based on
  588. // pc identity.
  589. Map<Pointcut, Pointcut> pcMap = new HashMap<Pointcut, Pointcut>();
  590. for (ShadowMunger munger: shadowMungers) {
  591. Pointcut p = munger.getPointcut();
  592. Pointcut newP = shareEntriesFromMap(p, pcMap);
  593. newP.m_ignoreUnboundBindingForNames = p.m_ignoreUnboundBindingForNames;
  594. munger.setPointcut(newP);
  595. }
  596. }
  597. private Pointcut shareEntriesFromMap(Pointcut p, Map<Pointcut, Pointcut> pcMap) {
  598. // some things cant be shared...
  599. if (p instanceof NameBindingPointcut) {
  600. return p;
  601. }
  602. if (p instanceof IfPointcut) {
  603. return p;
  604. }
  605. if (p instanceof ConcreteCflowPointcut) {
  606. return p;
  607. }
  608. if (p instanceof AndPointcut) {
  609. AndPointcut apc = (AndPointcut) p;
  610. Pointcut left = shareEntriesFromMap(apc.getLeft(), pcMap);
  611. Pointcut right = shareEntriesFromMap(apc.getRight(), pcMap);
  612. return new AndPointcut(left, right);
  613. } else if (p instanceof OrPointcut) {
  614. OrPointcut opc = (OrPointcut) p;
  615. Pointcut left = shareEntriesFromMap(opc.getLeft(), pcMap);
  616. Pointcut right = shareEntriesFromMap(opc.getRight(), pcMap);
  617. return new OrPointcut(left, right);
  618. } else if (p instanceof NotPointcut) {
  619. NotPointcut npc = (NotPointcut) p;
  620. Pointcut not = shareEntriesFromMap(npc.getNegatedPointcut(), pcMap);
  621. return new NotPointcut(not);
  622. } else {
  623. // primitive pcd
  624. if (pcMap.containsKey(p)) { // based on equality
  625. return pcMap.get(p); // same instance (identity)
  626. } else {
  627. pcMap.put(p, p);
  628. return p;
  629. }
  630. }
  631. }
  632. // userPointcut is the pointcut that the user wrote in the program text.
  633. // dnfPointcut is the same pointcut rewritten in DNF
  634. // numFormals is the number of formal parameters in the pointcut
  635. // if numFormals > 0 then every branch of a disjunction must bind each
  636. // formal once and only once.
  637. // in addition, the left and right branches of a disjunction must hold on
  638. // join point kinds in common.
  639. private void validateBindings(Pointcut dnfPointcut, Pointcut userPointcut, int numFormals, String[] names) {
  640. if (numFormals == 0) {
  641. return; // nothing to check
  642. }
  643. if (dnfPointcut.couldMatchKinds() == Shadow.NO_SHADOW_KINDS_BITS) {
  644. return; // cant have problems if you dont match!
  645. }
  646. if (dnfPointcut instanceof OrPointcut) {
  647. OrPointcut orBasedDNFPointcut = (OrPointcut) dnfPointcut;
  648. Pointcut[] leftBindings = new Pointcut[numFormals];
  649. Pointcut[] rightBindings = new Pointcut[numFormals];
  650. validateOrBranch(orBasedDNFPointcut, userPointcut, numFormals, names, leftBindings, rightBindings);
  651. } else {
  652. Pointcut[] bindings = new Pointcut[numFormals];
  653. validateSingleBranch(dnfPointcut, userPointcut, numFormals, names, bindings);
  654. }
  655. }
  656. private void validateOrBranch(OrPointcut pc, Pointcut userPointcut, int numFormals, String[] names, Pointcut[] leftBindings,
  657. Pointcut[] rightBindings) {
  658. Pointcut left = pc.getLeft();
  659. Pointcut right = pc.getRight();
  660. if (left instanceof OrPointcut) {
  661. Pointcut[] newRightBindings = new Pointcut[numFormals];
  662. validateOrBranch((OrPointcut) left, userPointcut, numFormals, names, leftBindings, newRightBindings);
  663. } else {
  664. if (left.couldMatchKinds() != Shadow.NO_SHADOW_KINDS_BITS) {
  665. validateSingleBranch(left, userPointcut, numFormals, names, leftBindings);
  666. }
  667. }
  668. if (right instanceof OrPointcut) {
  669. Pointcut[] newLeftBindings = new Pointcut[numFormals];
  670. validateOrBranch((OrPointcut) right, userPointcut, numFormals, names, newLeftBindings, rightBindings);
  671. } else {
  672. if (right.couldMatchKinds() != Shadow.NO_SHADOW_KINDS_BITS) {
  673. validateSingleBranch(right, userPointcut, numFormals, names, rightBindings);
  674. }
  675. }
  676. int kindsInCommon = left.couldMatchKinds() & right.couldMatchKinds();
  677. if (kindsInCommon != Shadow.NO_SHADOW_KINDS_BITS && couldEverMatchSameJoinPoints(left, right)) {
  678. // we know that every branch binds every formal, so there is no
  679. // ambiguity if each branch binds it in exactly the same way...
  680. List<String> ambiguousNames = new ArrayList<String>();
  681. for (int i = 0; i < numFormals; i++) {
  682. if (leftBindings[i] == null) {
  683. if (rightBindings[i] != null) {
  684. ambiguousNames.add(names[i]);
  685. }
  686. } else if (!leftBindings[i].equals(rightBindings[i])) {
  687. ambiguousNames.add(names[i]);
  688. }
  689. }
  690. if (!ambiguousNames.isEmpty()) {
  691. raiseAmbiguityInDisjunctionError(userPointcut, ambiguousNames);
  692. }
  693. }
  694. }
  695. // pc is a pointcut that does not contain any disjunctions
  696. // check that every formal is bound (negation doesn't count).
  697. // we know that numFormals > 0 or else we would not be called
  698. private void validateSingleBranch(Pointcut pc, Pointcut userPointcut, int numFormals, String[] names, Pointcut[] bindings) {
  699. boolean[] foundFormals = new boolean[numFormals];
  700. for (int i = 0; i < foundFormals.length; i++) {
  701. foundFormals[i] = false;
  702. }
  703. validateSingleBranchRecursion(pc, userPointcut, foundFormals, names, bindings);
  704. for (int i = 0; i < foundFormals.length; i++) {
  705. if (!foundFormals[i]) {
  706. boolean ignore = false;
  707. // ATAJ soften the unbound error for implicit bindings like
  708. // JoinPoint in @AJ style
  709. for (int j = 0; j < userPointcut.m_ignoreUnboundBindingForNames.length; j++) {
  710. if (names[i] != null && names[i].equals(userPointcut.m_ignoreUnboundBindingForNames[j])) {
  711. ignore = true;
  712. break;
  713. }
  714. }
  715. if (!ignore) {
  716. raiseUnboundFormalError(names[i], userPointcut);
  717. }
  718. }
  719. }
  720. }
  721. // each formal must appear exactly once
  722. private void validateSingleBranchRecursion(Pointcut pc, Pointcut userPointcut, boolean[] foundFormals, String[] names,
  723. Pointcut[] bindings) {
  724. if (pc instanceof NotPointcut) {
  725. // nots can only appear at leaves in DNF
  726. NotPointcut not = (NotPointcut) pc;
  727. if (not.getNegatedPointcut() instanceof NameBindingPointcut) {
  728. NameBindingPointcut nnbp = (NameBindingPointcut) not.getNegatedPointcut();
  729. if (!nnbp.getBindingAnnotationTypePatterns().isEmpty() && !nnbp.getBindingTypePatterns().isEmpty()) {
  730. raiseNegationBindingError(userPointcut);
  731. }
  732. }
  733. } else if (pc instanceof AndPointcut) {
  734. AndPointcut and = (AndPointcut) pc;
  735. validateSingleBranchRecursion(and.getLeft(), userPointcut, foundFormals, names, bindings);
  736. validateSingleBranchRecursion(and.getRight(), userPointcut, foundFormals, names, bindings);
  737. } else if (pc instanceof NameBindingPointcut) {
  738. List<BindingTypePattern> bindingTypePatterns = ((NameBindingPointcut) pc).getBindingTypePatterns();
  739. for (BindingTypePattern bindingTypePattern: bindingTypePatterns) {
  740. int index = bindingTypePattern.getFormalIndex();
  741. bindings[index] = pc;
  742. if (foundFormals[index]) {
  743. raiseAmbiguousBindingError(names[index], userPointcut);
  744. } else {
  745. foundFormals[index] = true;
  746. }
  747. }
  748. List<BindingPattern> bindingAnnotationTypePatterns = ((NameBindingPointcut) pc).getBindingAnnotationTypePatterns();
  749. for (BindingPattern bindingAnnotationTypePattern: bindingAnnotationTypePatterns) {
  750. int index = bindingAnnotationTypePattern.getFormalIndex();
  751. bindings[index] = pc;
  752. if (foundFormals[index]) {
  753. raiseAmbiguousBindingError(names[index], userPointcut);
  754. } else {
  755. foundFormals[index] = true;
  756. }
  757. }
  758. } else if (pc instanceof ConcreteCflowPointcut) {
  759. ConcreteCflowPointcut cfp = (ConcreteCflowPointcut) pc;
  760. int[] slots = cfp.getUsedFormalSlots();
  761. for (int i = 0; i < slots.length; i++) {
  762. bindings[slots[i]] = cfp;
  763. if (foundFormals[slots[i]]) {
  764. raiseAmbiguousBindingError(names[slots[i]], userPointcut);
  765. } else {
  766. foundFormals[slots[i]] = true;
  767. }
  768. }
  769. }
  770. }
  771. // By returning false from this method, we are allowing binding of the same
  772. // variable on either side of an or.
  773. // Be conservative :- have to consider overriding, varargs, autoboxing,
  774. // the effects of itds (on within for example), interfaces, the fact that
  775. // join points can have multiple signatures and so on.
  776. private boolean couldEverMatchSameJoinPoints(Pointcut left, Pointcut right) {
  777. if (left instanceof OrPointcut) {
  778. OrPointcut leftOrPointcut = (OrPointcut) left;
  779. if (couldEverMatchSameJoinPoints(leftOrPointcut.getLeft(), right)) {
  780. return true;
  781. }
  782. if (couldEverMatchSameJoinPoints(leftOrPointcut.getRight(), right)) {
  783. return true;
  784. }
  785. return false;
  786. }
  787. if (right instanceof OrPointcut) {
  788. OrPointcut rightOrPointcut = (OrPointcut) right;
  789. if (couldEverMatchSameJoinPoints(left, rightOrPointcut.getLeft())) {
  790. return true;
  791. }
  792. if (couldEverMatchSameJoinPoints(left, rightOrPointcut.getRight())) {
  793. return true;
  794. }
  795. return false;
  796. }
  797. // look for withins
  798. WithinPointcut leftWithin = (WithinPointcut) findFirstPointcutIn(left, WithinPointcut.class);
  799. WithinPointcut rightWithin = (WithinPointcut) findFirstPointcutIn(right, WithinPointcut.class);
  800. if ((leftWithin != null) && (rightWithin != null)) {
  801. if (!leftWithin.couldEverMatchSameJoinPointsAs(rightWithin)) {
  802. return false;
  803. }
  804. }
  805. // look for kinded
  806. KindedPointcut leftKind = (KindedPointcut) findFirstPointcutIn(left, KindedPointcut.class);
  807. KindedPointcut rightKind = (KindedPointcut) findFirstPointcutIn(right, KindedPointcut.class);
  808. if ((leftKind != null) && (rightKind != null)) {
  809. if (!leftKind.couldEverMatchSameJoinPointsAs(rightKind)) {
  810. return false;
  811. }
  812. }
  813. return true;
  814. }
  815. private Pointcut findFirstPointcutIn(Pointcut toSearch, Class toLookFor) {
  816. if (toSearch instanceof NotPointcut) {
  817. return null;
  818. }
  819. if (toLookFor.isInstance(toSearch)) {
  820. return toSearch;
  821. }
  822. if (toSearch instanceof AndPointcut) {
  823. AndPointcut apc = (AndPointcut) toSearch;
  824. Pointcut left = findFirstPointcutIn(apc.getLeft(), toLookFor);
  825. if (left != null) {
  826. return left;
  827. }
  828. return findFirstPointcutIn(apc.getRight(), toLookFor);
  829. }
  830. return null;
  831. }
  832. /**
  833. * @param userPointcut
  834. */
  835. private void raiseNegationBindingError(Pointcut userPointcut) {
  836. world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.NEGATION_DOESNT_ALLOW_BINDING), userPointcut
  837. .getSourceContext().makeSourceLocation(userPointcut), null);
  838. }
  839. private void raiseAmbiguousBindingError(String name, Pointcut pointcut) {
  840. world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.AMBIGUOUS_BINDING, name), pointcut
  841. .getSourceContext().makeSourceLocation(pointcut), null);
  842. }
  843. /**
  844. * @param userPointcut
  845. */
  846. private void raiseAmbiguityInDisjunctionError(Pointcut userPointcut, List<String> names) {
  847. StringBuffer formalNames = new StringBuffer(names.get(0).toString());
  848. for (int i = 1; i < names.size(); i++) {
  849. formalNames.append(", ");
  850. formalNames.append(names.get(i));
  851. }
  852. world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.AMBIGUOUS_BINDING_IN_OR, formalNames), userPointcut
  853. .getSourceContext().makeSourceLocation(userPointcut), null);
  854. }
  855. /**
  856. * @param name
  857. * @param userPointcut
  858. */
  859. private void raiseUnboundFormalError(String name, Pointcut userPointcut) {
  860. world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.UNBOUND_FORMAL, name),
  861. userPointcut.getSourceLocation(), null);
  862. }
  863. public void addManifest(Manifest newManifest) {
  864. // System.out.println("? addManifest() newManifest=" + newManifest);
  865. if (manifest == null) {
  866. manifest = newManifest;
  867. }
  868. }
  869. public Manifest getManifest(boolean shouldCreate) {
  870. if (manifest == null && shouldCreate) {
  871. String WEAVER_MANIFEST_VERSION = "1.0";
  872. Attributes.Name CREATED_BY = new Name("Created-By");
  873. String WEAVER_CREATED_BY = "AspectJ Compiler";
  874. manifest = new Manifest();
  875. Attributes attributes = manifest.getMainAttributes();
  876. attributes.put(Name.MANIFEST_VERSION, WEAVER_MANIFEST_VERSION);
  877. attributes.put(CREATED_BY, WEAVER_CREATED_BY);
  878. }
  879. return manifest;
  880. }
  881. // ---- weaving
  882. // FOR TESTING
  883. public Collection<String> weave(File file) throws IOException {
  884. OutputStream os = FileUtil.makeOutputStream(file);
  885. this.zipOutputStream = new ZipOutputStream(os);
  886. prepareForWeave();
  887. Collection<String> c = weave(new IClassFileProvider() {
  888. public boolean isApplyAtAspectJMungersOnly() {
  889. return false;
  890. }
  891. public Iterator<UnwovenClassFile> getClassFileIterator() {
  892. return addedClasses.iterator();
  893. }
  894. public IWeaveRequestor getRequestor() {
  895. return new IWeaveRequestor() {
  896. public void acceptResult(IUnwovenClassFile result) {
  897. try {
  898. writeZipEntry(result.getFilename(), result.getBytes());
  899. } catch (IOException ex) {
  900. }
  901. }
  902. public void processingReweavableState() {
  903. }
  904. public void addingTypeMungers() {
  905. }
  906. public void weavingAspects() {
  907. }
  908. public void weavingClasses() {
  909. }
  910. public void weaveCompleted() {
  911. }
  912. };
  913. }
  914. });
  915. // /* BUG 40943*/
  916. // dumpResourcesToOutJar();
  917. zipOutputStream.close(); // this flushes and closes the acutal file
  918. return c;
  919. }
  920. private Set<IProgramElement> candidatesForRemoval = null;
  921. // variation of "weave" that sources class files from an external source.
  922. public Collection<String> weave(IClassFileProvider input) throws IOException {
  923. if (trace.isTraceEnabled()) {
  924. trace.enter("weave", this, input);
  925. }
  926. ContextToken weaveToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING, "");
  927. Collection<String> wovenClassNames = new ArrayList<String>();
  928. IWeaveRequestor requestor = input.getRequestor();
  929. if (world.getModel() != null && world.isMinimalModel()) {
  930. candidatesForRemoval = new HashSet<IProgramElement>();
  931. }
  932. if (world.getModel() != null && !isBatchWeave) {
  933. AsmManager manager = world.getModelAsAsmManager();
  934. for (Iterator<UnwovenClassFile> i = input.getClassFileIterator(); i.hasNext();) {
  935. UnwovenClassFile classFile = i.next();
  936. // remove all relationships where this file being woven is
  937. // the target of the relationship
  938. manager.removeRelationshipsTargettingThisType(classFile.getClassName());
  939. }
  940. }
  941. // Go through the types and ensure any 'damaged' during compile time are
  942. // repaired prior to weaving
  943. for (Iterator<UnwovenClassFile> i = input.getClassFileIterator(); i.hasNext();) {
  944. UnwovenClassFile classFile = i.next();
  945. if (classFile.shouldBeWoven()) {
  946. String className = classFile.getClassName();
  947. ResolvedType theType = world.resolve(className);
  948. if (theType != null) {
  949. theType.ensureConsistent();
  950. }
  951. }
  952. }
  953. // special case for AtAspectJMungerOnly - see #113587
  954. if (input.isApplyAtAspectJMungersOnly()) {
  955. ContextToken atAspectJMungersOnly = CompilationAndWeavingContext.enteringPhase(
  956. CompilationAndWeavingContext.PROCESSING_ATASPECTJTYPE_MUNGERS_ONLY, "");
  957. requestor.weavingAspects();
  958. // ContextToken aspectToken =
  959. CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_ASPECTS, "");
  960. for (Iterator<UnwovenClassFile> i = input.getClassFileIterator(); i.hasNext();) {
  961. UnwovenClassFile classFile = i.next();
  962. if (classFile.shouldBeWoven()) {
  963. String className = classFile.getClassName();
  964. ResolvedType theType = world.resolve(className);
  965. if (theType.isAnnotationStyleAspect()) {
  966. BcelObjectType classType = BcelWorld.getBcelObjectType(theType);
  967. if (classType == null) {
  968. throw new BCException("Can't find bcel delegate for " + className + " type=" + theType.getClass());
  969. }
  970. LazyClassGen clazz = classType.getLazyClassGen();
  971. BcelPerClauseAspectAdder selfMunger = new BcelPerClauseAspectAdder(theType, theType.getPerClause().getKind());
  972. selfMunger.forceMunge(clazz, true);
  973. classType.finishedWith();
  974. UnwovenClassFile[] newClasses = getClassFilesFor(clazz);
  975. for (int news = 0; news < newClasses.length; news++) {
  976. requestor.acceptResult(newClasses[news]);
  977. }
  978. wovenClassNames.add(classFile.getClassName());
  979. }
  980. }
  981. }
  982. requestor.weaveCompleted();
  983. CompilationAndWeavingContext.leavingPhase(atAspectJMungersOnly);
  984. return wovenClassNames;
  985. }
  986. requestor.processingReweavableState();
  987. ContextToken reweaveToken = CompilationAndWeavingContext.enteringPhase(
  988. CompilationAndWeavingContext.PROCESSING_REWEAVABLE_STATE, "");
  989. prepareToProcessReweavableState();
  990. // clear all state from files we'll be reweaving
  991. for (Iterator<UnwovenClassFile> i = input.getClassFileIterator(); i.hasNext();) {
  992. UnwovenClassFile classFile = i.next();
  993. if (classFile.shouldBeWoven()) {
  994. String className = classFile.getClassName();
  995. BcelObjectType classType = getClassType(className);
  996. // null return from getClassType() means the delegate is an eclipse
  997. // source type - so
  998. // there *cant* be any reweavable state... (he bravely claimed...)
  999. if (classType != null) {
  1000. ContextToken tok = CompilationAndWeavingContext.enteringPhase(
  1001. CompilationAndWeavingContext.PROCESSING_REWEAVABLE_STATE, className);
  1002. processReweavableStateIfPresent(className, classType);
  1003. CompilationAndWeavingContext.leavingPhase(tok);
  1004. }
  1005. }
  1006. }
  1007. CompilationAndWeavingContext.leavingPhase(reweaveToken);
  1008. ContextToken typeMungingToken = CompilationAndWeavingContext.enteringPhase(
  1009. CompilationAndWeavingContext.PROCESSING_TYPE_MUNGERS, "");
  1010. requestor.addingTypeMungers();
  1011. // We process type mungers in two groups, first mungers that change the
  1012. // type
  1013. // hierarchy, then 'normal' ITD type mungers.
  1014. // Process the types in a predictable order (rather than the order
  1015. // encountered).
  1016. // For class A, the order is superclasses of A then superinterfaces of A
  1017. // (and this mechanism is applied recursively)
  1018. List<String> typesToProcess = new ArrayList<String>();
  1019. for (Iterator<UnwovenClassFile> iter = input.getClassFileIterator(); iter.hasNext();) {
  1020. UnwovenClassFile clf = iter.next();
  1021. if (clf.shouldBeWoven()) {
  1022. typesToProcess.add(clf.getClassName());
  1023. }
  1024. }
  1025. while (typesToProcess.size() > 0) {
  1026. weaveParentsFor(typesToProcess, typesToProcess.get(0), null);
  1027. }
  1028. for (Iterator<UnwovenClassFile> i = input.getClassFileIterator(); i.hasNext();) {
  1029. UnwovenClassFile classFile = i.next();
  1030. if (classFile.shouldBeWoven()) {
  1031. String className = classFile.getClassName();
  1032. addNormalTypeMungers(className);
  1033. }
  1034. }
  1035. CompilationAndWeavingContext.leavingPhase(typeMungingToken);
  1036. requestor.weavingAspects();
  1037. ContextToken aspectToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_ASPECTS, "");
  1038. // first weave into aspects
  1039. for (Iterator<UnwovenClassFile> i = input.getClassFileIterator(); i.hasNext();) {
  1040. UnwovenClassFile classFile = i.next();
  1041. if (classFile.shouldBeWoven()) {
  1042. String className = classFile.getClassName();
  1043. ResolvedType theType = world.resolve(className);
  1044. if (theType.isAspect()) {
  1045. BcelObjectType classType = BcelWorld.getBcelObjectType(theType);
  1046. if (classType == null) {
  1047. // Sometimes.. if the Bcel Delegate couldn't be found then a
  1048. // problem occurred at compile time - on
  1049. // a previous compiler run. In this case I assert the
  1050. // delegate will still be an EclipseSourceType
  1051. // and we can ignore the problem here (the original compile
  1052. // error will be reported again from
  1053. // the eclipse source type) - pr113531
  1054. ReferenceTypeDelegate theDelegate = ((ReferenceType) theType).getDelegate();
  1055. if (theDelegate.getClass().getName().endsWith("EclipseSourceType")) {
  1056. continue;
  1057. }
  1058. throw new BCException("Can't find bcel delegate for " + className + " type=" + theType.getClass());
  1059. }
  1060. weaveAndNotify(classFile, classType, requestor);
  1061. wovenClassNames.add(className);
  1062. }
  1063. }
  1064. }
  1065. CompilationAndWeavingContext.leavingPhase(aspectToken);
  1066. requestor.weavingClasses();
  1067. ContextToken classToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_CLASSES, "");
  1068. // then weave into non-aspects
  1069. for (Iterator<UnwovenClassFile> i = input.getClassFileIterator(); i.hasNext();) {
  1070. UnwovenClassFile classFile = i.next();
  1071. if (classFile.shouldBeWoven()) {
  1072. String className = classFile.getClassName();
  1073. ResolvedType theType = world.resolve(className);
  1074. if (!theType.isAspect()) {
  1075. BcelObjectType classType = BcelWorld.getBcelObjectType(theType);
  1076. if (classType == null) {
  1077. // bug 119882 - see above comment for bug 113531
  1078. ReferenceTypeDelegate theDelegate = ((ReferenceType) theType).getDelegate();
  1079. // TODO urgh - put a method on the interface to check this,
  1080. // string compare is hideous
  1081. if (theDelegate.getClass().getName().endsWith("EclipseSourceType")) {
  1082. continue;
  1083. }
  1084. throw new BCException("Can't find bcel delegate for " + className + " type=" + theType.getClass());
  1085. }
  1086. weaveAndNotify(classFile, classType, requestor);
  1087. wovenClassNames.add(className);
  1088. }
  1089. }
  1090. }
  1091. CompilationAndWeavingContext.leavingPhase(classToken);
  1092. addedClasses.clear();
  1093. deletedTypenames.clear();
  1094. requestor.weaveCompleted();
  1095. CompilationAndWeavingContext.leavingPhase(weaveToken);
  1096. if (trace.isTraceEnabled()) {
  1097. trace.exit("weave", wovenClassNames);
  1098. }
  1099. if (world.getModel() != null && world.isMinimalModel()) {
  1100. candidatesForRemoval.clear();
  1101. }
  1102. return wovenClassNames;
  1103. }
  1104. public void allWeavingComplete() {
  1105. warnOnUnmatchedAdvice();
  1106. }
  1107. /**
  1108. * In 1.5 mode and with XLint:adviceDidNotMatch enabled, put out messages for any mungers that did not match anything.
  1109. */
  1110. private void warnOnUnmatchedAdvice() {
  1111. class AdviceLocation {
  1112. private final int lineNo;
  1113. private final UnresolvedType inAspect;
  1114. public AdviceLocation(BcelAdvice advice) {
  1115. this.lineNo = advice.getSourceLocation().getLine();
  1116. this.inAspect = advice.getDeclaringAspect();
  1117. }
  1118. @Override
  1119. public boolean equals(Object obj) {
  1120. if (!(obj instanceof AdviceLocation)) {
  1121. return false;
  1122. }
  1123. AdviceLocation other = (AdviceLocation) obj;
  1124. if (this.lineNo != other.lineNo) {
  1125. return false;
  1126. }
  1127. if (!this.inAspect.equals(other.inAspect)) {
  1128. return false;
  1129. }
  1130. return true;
  1131. }
  1132. @Override
  1133. public int hashCode() {
  1134. return 37 + 17 * lineNo + 17 * inAspect.hashCode();
  1135. }
  1136. }
  1137. // FIXME asc Should be factored out into Xlint code and done
  1138. // automatically for all xlint messages, ideally.
  1139. // if a piece of advice hasn't matched anywhere and we are in -1.5 mode,
  1140. // put out a warning
  1141. if (world.isInJava5Mode() && world.getLint().adviceDidNotMatch.isEnabled()) {
  1142. List l = world.getCrosscuttingMembersSet().getShadowMungers();
  1143. Set<AdviceLocation> alreadyWarnedLocations = new HashSet<AdviceLocation>();
  1144. for (Iterator iter = l.iterator(); iter.hasNext();) {
  1145. ShadowMunger element = (ShadowMunger) iter.next();
  1146. // This will stop us incorrectly reporting deow checkers:
  1147. if (element instanceof BcelAdvice) {
  1148. BcelAdvice ba = (BcelAdvice) element;
  1149. if (ba.getKind() == AdviceKind.CflowEntry || ba.getKind() == AdviceKind.CflowBelowEntry) {
  1150. continue;
  1151. }
  1152. if (!ba.hasMatchedSomething()) {
  1153. // Because we implement some features of AJ itself by
  1154. // creating our own kind of mungers, you sometimes
  1155. // find that ba.getSignature() is not a BcelMethod - for
  1156. // example it might be a cflow entry munger.
  1157. if (ba.getSignature() != null) {
  1158. // check we haven't already warned on this advice and line
  1159. // (cflow creates multiple mungers for the same advice)
  1160. AdviceLocation loc = new AdviceLocation(ba);
  1161. if (alreadyWarnedLocations.contains(loc)) {
  1162. continue;
  1163. } else {
  1164. alreadyWarnedLocations.add(loc);
  1165. }
  1166. if (!(ba.getSignature() instanceof BcelMethod)
  1167. || !Utility.isSuppressing(ba.getSignature(), "adviceDidNotMatch")) {
  1168. world.getLint().adviceDidNotMatch.signal(ba.getDeclaringAspect().toString(), new SourceLocation(
  1169. element.getSourceLocation().getSourceFile(), element.getSourceLocation().getLine()));
  1170. }
  1171. }
  1172. }
  1173. }
  1174. }
  1175. }
  1176. }
  1177. /**
  1178. * 'typeToWeave' is one from the 'typesForWeaving' list. This routine ensures we process supertypes (classes/interfaces) of
  1179. * 'typeToWeave' that are in the 'typesForWeaving' list before 'typeToWeave' itself. 'typesToWeave' is then removed from the
  1180. * 'typesForWeaving' list.
  1181. *
  1182. * Note: Future gotcha in here ... when supplying partial hierarchies, this algorithm may break down. If you have a hierarchy
  1183. * A>B>C and only give A and C to the weaver, it may choose to weave them in either order - but you'll probably have other
  1184. * problems if you are supplying partial hierarchies like that !
  1185. */
  1186. private void weaveParentsFor(List<String> typesForWeaving, String typeToWeave, ResolvedType resolvedTypeToWeave) {
  1187. if (resolvedTypeToWeave == null) {
  1188. // resolve it if the caller could not pass in the resolved type
  1189. resolvedTypeToWeave = world.resolve(typeToWeave);
  1190. }
  1191. ResolvedType superclassType = resolvedTypeToWeave.getSuperclass();
  1192. String superclassTypename = (superclassType == null ? null : superclassType.getName());
  1193. // PR336654 added the 'typesForWeaving.contains(superclassTypename)' clause.
  1194. // Without it we can delete all type mungers on the parents and yet we only
  1195. // add back in the declare parents related ones, not the regular ITDs.
  1196. if (superclassType != null && !superclassType.isTypeHierarchyComplete() && superclassType.isExposedToWeaver()
  1197. && typesForWeaving.contains(superclassTypename)) {
  1198. weaveParentsFor(typesForWeaving, superclassTypename, superclassType);
  1199. }
  1200. ResolvedType[] interfaceTypes = resolvedTypeToWeave.getDeclaredInterfaces();
  1201. for (ResolvedType resolvedSuperInterface : interfaceTypes) {
  1202. if (!resolvedSuperInterface.isTypeHierarchyComplete()) {
  1203. String interfaceTypename = resolvedSuperInterface.getName();
  1204. if (resolvedSuperInterface.isExposedToWeaver()) { // typesForWeaving.contains(interfaceTypename)) {
  1205. weaveParentsFor(typesForWeaving, interfaceTypename, resolvedSuperInterface);
  1206. }
  1207. }
  1208. }
  1209. ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_DECLARE_PARENTS,
  1210. resolvedTypeToWeave.getName());
  1211. // If A was processed before B (and was declared 'class A implements B') then there is no need to complete B again, it
  1212. // will have been done whilst processing A.
  1213. if (!resolvedTypeToWeave.isTypeHierarchyComplete()) {
  1214. weaveParentTypeMungers(resolvedTypeToWeave);
  1215. }
  1216. CompilationAndWeavingContext.leavingPhase(tok);
  1217. typesForWeaving.remove(typeToWeave);
  1218. resolvedTypeToWeave.tagAsTypeHierarchyComplete();
  1219. }
  1220. public void prepareToProcessReweavableState() {
  1221. }
  1222. public void processReweavableStateIfPresent(String className, BcelObjectType classType) {
  1223. // If the class is marked reweavable, check any aspects around when it
  1224. // was built are in this world
  1225. WeaverStateInfo wsi = classType.getWeaverState();
  1226. // System.out.println(">> processReweavableStateIfPresent " + className + " wsi=" + wsi);
  1227. if (wsi != null && wsi.isReweavable()) { // Check all necessary types
  1228. // are around!
  1229. world.showMessage(IMessage.INFO, WeaverMessages.format(WeaverMessages.PROCESSING_REWEAVABLE, className, classType
  1230. .getSourceLocation().getSourceFile()), null, null);
  1231. Set<String> aspectsPreviouslyInWorld = wsi.getAspectsAffectingType();
  1232. // keep track of them just to ensure unique missing aspect error
  1233. // reporting
  1234. Set<String> alreadyConfirmedReweavableState = new HashSet<String>();
  1235. for (String requiredTypeSignature : aspectsPreviouslyInWorld) {
  1236. // for (Iterator iter = aspectsPreviouslyInWorld.iterator(); iter.hasNext();) {
  1237. // String requiredTypeName = (String) iter.next();
  1238. if (!alreadyConfirmedReweavableState.contains(requiredTypeSignature)) {
  1239. ResolvedType rtx = world.resolve(UnresolvedType.forSignature(requiredTypeSignature), true);
  1240. boolean exists = !rtx.isMissing();
  1241. if (!world.isOverWeaving()) {
  1242. if (!exists) {
  1243. world.getLint().missingAspectForReweaving.signal(new String[] { rtx.getName(), className },
  1244. classType.getSourceLocation(), null);
  1245. // world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.MISSING_REWEAVABLE_TYPE,
  1246. // requiredTypeName, className), classType.getSourceLocation(), null);
  1247. } else {
  1248. // weaved in aspect that are not declared in aop.xml
  1249. // trigger an error for now
  1250. // may cause headhache for LTW and packaged lib
  1251. // without aop.xml in
  1252. // see #104218
  1253. if (!xcutSet.containsAspect(rtx)) {
  1254. world.showMessage(IMessage.ERROR, WeaverMessages.format(
  1255. WeaverMessages.REWEAVABLE_ASPECT_NOT_REGISTERED, rtx.getName(), className), null, null);
  1256. } else if (!world.getMessageHandler().isIgnoring(IMessage.INFO)) {
  1257. world.showMessage(IMessage.INFO, WeaverMessages.format(WeaverMessages.VERIFIED_REWEAVABLE_TYPE,
  1258. rtx.getName(), rtx.getSourceLocation().getSourceFile()), null, null);
  1259. }
  1260. alreadyConfirmedReweavableState.add(requiredTypeSignature);
  1261. }
  1262. }
  1263. }
  1264. }
  1265. // old:
  1266. // classType.setJavaClass(Utility.makeJavaClass(classType.getJavaClass
  1267. // ().getFileName(), wsi.getUnwovenClassFileData()));
  1268. // new: reweavable default with clever diff
  1269. if (!world.isOverWeaving()) {
  1270. byte[] ucfd = wsi.getUnwovenClassFileData();
  1271. if (ucfd.length == 0) {
  1272. // Size 0 indicates the class was previously overwoven, so you need to be overweaving now!
  1273. world.getMessageHandler().handleMessage(
  1274. MessageUtil.error(
  1275. WeaverMessages.format(WeaverMessages.MUST_KEEP_OVERWEAVING_ONCE_START,
  1276. className)));
  1277. // onType.getName(), annoX.getTypeName(), annoX.getValidTargets()),
  1278. // decA.getSourceLocation()));
  1279. } else {
  1280. byte[] bytes = wsi.getUnwovenClassFileData(classType.getJavaClass().getBytes());
  1281. JavaClass newJavaClass = Utility.makeJavaClass(classType.getJavaClass().getFileName(), bytes);
  1282. classType.setJavaClass(newJavaClass, true);
  1283. classType.getResolvedTypeX().ensureConsistent();
  1284. }
  1285. }
  1286. // } else {
  1287. // classType.resetState();
  1288. }
  1289. }
  1290. private void weaveAndNotify(UnwovenClassFile classFile, BcelObjectType classType, IWeaveRequestor requestor) throws IOException {
  1291. trace.enter("weaveAndNotify", this, new Object[] { classFile, classType, requestor });
  1292. ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_TYPE, classType
  1293. .getResolvedTypeX().getName());
  1294. LazyClassGen clazz = weaveWithoutDump(classFile, classType);
  1295. classType.finishedWith();
  1296. // clazz is null if the classfile was unchanged by weaving...
  1297. if (clazz != null) {
  1298. UnwovenClassFile[] newClasses = getClassFilesFor(clazz);
  1299. // OPTIMIZE can we avoid using the string name at all in
  1300. // UnwovenClassFile instances?
  1301. // Copy the char[] across as it means the
  1302. // WeaverAdapter.removeFromMap() can be fast!
  1303. if (newClasses[0].getClassName().equals(classFile.getClassName())) {
  1304. newClasses[0].setClassNameAsChars(classFile.getClassNameAsChars());
  1305. }
  1306. for (int i = 0; i < newClasses.length; i++) {
  1307. requestor.acceptResult(newClasses[i]);
  1308. }
  1309. } else {
  1310. requestor.acceptResult(classFile);
  1311. }
  1312. classType.weavingCompleted();
  1313. CompilationAndWeavingContext.leavingPhase(tok);
  1314. trace.exit("weaveAndNotify");
  1315. }
  1316. /**
  1317. * helper method - will return NULL if the underlying delegate is an EclipseSourceType and not a BcelObjectType
  1318. */
  1319. public BcelObjectType getClassType(String forClass) {
  1320. return BcelWorld.getBcelObjectType(world.resolve(forClass));
  1321. }
  1322. public void addParentTypeMungers(String typeName) {
  1323. weaveParentTypeMungers(world.resolve(typeName));
  1324. }
  1325. public void addNormalTypeMungers(String typeName) {
  1326. weaveNormalTypeMungers(world.resolve(typeName));
  1327. }
  1328. public UnwovenClassFile[] getClassFilesFor(LazyClassGen clazz) {
  1329. List<UnwovenClassFile.ChildClass> childClasses = clazz.getChildClasses(world);
  1330. UnwovenClassFile[] ret = new UnwovenClassFile[1 + childClasses.size()];
  1331. ret[0] = new UnwovenClassFile(clazz.getFileName(), clazz.getClassName(), clazz.getJavaClassBytesIncludingReweavable(world));
  1332. int index = 1;
  1333. for (Iterator<UnwovenClassFile.ChildClass> iter = childClasses.iterator(); iter.hasNext();) {
  1334. UnwovenClassFile.ChildClass element = iter.next();
  1335. UnwovenClassFile childClass = new UnwovenClassFile(clazz.getFileName() + "$" + element.name, element.bytes);
  1336. ret[index++] = childClass;
  1337. }
  1338. return ret;
  1339. }
  1340. /**
  1341. * Weaves new parents and annotations onto a type ("declare parents" and "declare @type")
  1342. *
  1343. * Algorithm: 1. First pass, do parents then do annotations. During this pass record: - any parent mungers that don't match but
  1344. * have a non-wild annotation type pattern - any annotation mungers that don't match 2. Multiple subsequent passes which go over
  1345. * the munger lists constructed in the first pass, repeatedly applying them until nothing changes. FIXME asc confirm that
  1346. * algorithm is optimal ??
  1347. */
  1348. public void weaveParentTypeMungers(ResolvedType onType) {
  1349. if (onType.isRawType() || onType.isParameterizedType()) {
  1350. onType = onType.getGenericType();
  1351. }
  1352. onType.clearInterTypeMungers();
  1353. List<DeclareParents> decpToRepeat = new ArrayList<DeclareParents>();
  1354. boolean aParentChangeOccurred = false;
  1355. boolean anAnnotationChangeOccurred = false;
  1356. // First pass - apply all decp mungers
  1357. for (DeclareParents decp : declareParentsList) {
  1358. boolean typeChanged = applyDeclareParents(decp, onType);
  1359. if (typeChanged) {
  1360. aParentChangeOccurred = true;
  1361. } else {
  1362. decpToRepeat.add(decp);
  1363. }
  1364. }
  1365. // Still first pass - apply all dec @type mungers
  1366. for (DeclareAnnotation decA : xcutSet.getDeclareAnnotationOnTypes()) {
  1367. boolean typeChanged = applyDeclareAtType(decA, onType, true);
  1368. if (typeChanged) {
  1369. anAnnotationChangeOccurred = true;
  1370. }
  1371. }
  1372. while ((aParentChangeOccurred || anAnnotationChangeOccurred) && !decpToRepeat.isEmpty()) {
  1373. anAnnotationChangeOccurred = aParentChangeOccurred = false;
  1374. List<DeclareParents> decpToRepeatNextTime = new ArrayList<DeclareParents>();
  1375. for (Iterator<DeclareParents> iter = decpToRepeat.iterator(); iter.hasNext();) {
  1376. DeclareParents decp = iter.next();
  1377. boolean typeChanged = applyDeclareParents(decp, onType);
  1378. if (typeChanged) {
  1379. aParentChangeOccurred = true;
  1380. } else {
  1381. decpToRepeatNextTime.add(decp);
  1382. }
  1383. }
  1384. for (DeclareAnnotation decA : xcutSet.getDeclareAnnotationOnTypes()) {
  1385. boolean typeChanged = applyDeclareAtType(decA, onType, false);
  1386. if (typeChanged) {
  1387. anAnnotationChangeOccurred = true;
  1388. }
  1389. }
  1390. decpToRepeat = decpToRepeatNextTime;
  1391. }
  1392. }
  1393. /**
  1394. * Apply a declare @type - return true if we change the type
  1395. */
  1396. private boolean applyDeclareAtType(DeclareAnnotation decA, ResolvedType onType, boolean reportProblems) {
  1397. boolean didSomething = false;
  1398. if (decA.matches(onType)) {
  1399. AnnotationAJ theAnnotation = decA.getAnnotation();
  1400. // can be null for broken code!
  1401. if (theAnnotation == null) {
  1402. return false;
  1403. }
  1404. if (onType.hasAnnotation(theAnnotation.getType())) {
  1405. // Could put out a lint here for an already annotated type ...
  1406. // if (reportProblems) {
  1407. // world.getLint().elementAlreadyAnnotated.signal(
  1408. // new
  1409. // String[]{onType.toString(),decA.getAnnotationTypeX().toString
  1410. // ()},
  1411. // onType.getSourceLocation(),new
  1412. // ISourceLocation[]{decA.getSourceLocation()});
  1413. // }
  1414. return false;
  1415. }
  1416. AnnotationAJ annoX = decA.getAnnotation();
  1417. // check the annotation is suitable for the target
  1418. boolean problemReported = verifyTargetIsOK(decA, onType, annoX, reportProblems);
  1419. if (!problemReported) {
  1420. AsmRelationshipProvider.addDeclareAnnotationRelationship(world.getModelAsAsmManager(), decA.getSourceLocation(),
  1421. onType.getSourceLocation(), false);
  1422. // TAG: WeavingMessage
  1423. if (!getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) {
  1424. getWorld().getMessageHandler().handleMessage(
  1425. WeaveMessage.constructWeavingMessage(
  1426. WeaveMessage.WEAVEMESSAGE_ANNOTATES,
  1427. new String[] { onType.toString(), Utility.beautifyLocation(onType.getSourceLocation()),
  1428. decA.getAnnotationString(), "type", decA.getAspect().toString(),
  1429. Utility.beautifyLocation(decA.getSourceLocation()) }));
  1430. }
  1431. didSomething = true;
  1432. ResolvedTypeMunger newAnnotationTM = new AnnotationOnTypeMunger(annoX);
  1433. newAnnotationTM.setSourceLocation(decA.getSourceLocation());
  1434. onType.addInterTypeMunger(new BcelTypeMunger(newAnnotationTM, decA.getAspect().resolve(world)), false);
  1435. decA.copyAnnotationTo(onType);
  1436. }
  1437. }
  1438. return didSomething;
  1439. }
  1440. /**
  1441. * Checks for an @target() on the annotation and if found ensures it allows the annotation to be attached to the target type
  1442. * that matched.
  1443. */
  1444. private boolean verifyTargetIsOK(DeclareAnnotation decA, ResolvedType onType, AnnotationAJ annoX, boolean outputProblems) {
  1445. boolean problemReported = false;
  1446. if (annoX.specifiesTarget()) {
  1447. if ((onType.isAnnotation() && !annoX.allowedOnAnnotationType()) || (!annoX.allowedOnRegularType())) {
  1448. if (outputProblems) {
  1449. if (decA.isExactPattern()) {
  1450. world.getMessageHandler().handleMessage(
  1451. MessageUtil.error(
  1452. WeaverMessages.format(WeaverMessages.INCORRECT_TARGET_FOR_DECLARE_ANNOTATION,
  1453. onType.getName(), annoX.getTypeName(), annoX.getValidTargets()),
  1454. decA.getSourceLocation()));
  1455. } else {
  1456. if (world.getLint().invalidTargetForAnnotation.isEnabled()) {
  1457. world.getLint().invalidTargetForAnnotation.signal(new String[] { onType.getName(), annoX.getTypeName(),
  1458. annoX.getValidTargets() }, decA.getSourceLocation(),
  1459. new ISourceLocation[] { onType.getSourceLocation() });
  1460. }
  1461. }
  1462. }
  1463. problemReported = true;
  1464. }
  1465. }
  1466. return problemReported;
  1467. }
  1468. /**
  1469. * Apply a single declare parents - return true if we change the type
  1470. */
  1471. private boolean applyDeclareParents(DeclareParents p, ResolvedType onType) {
  1472. boolean didSomething = false;
  1473. List<ResolvedType> newParents = p.findMatchingNewParents(onType, true);
  1474. if (!newParents.isEmpty()) {
  1475. didSomething = true;
  1476. BcelWorld.getBcelObjectType(onType);
  1477. // System.err.println("need to do declare parents for: " + onType);
  1478. for (ResolvedType newParent : newParents) {
  1479. // We set it here so that the imminent matching for ITDs can
  1480. // succeed - we still haven't done the necessary changes to the class file
  1481. // itself (like transform super calls) - that is done in
  1482. // BcelTypeMunger.mungeNewParent()
  1483. // classType.addParent(newParent);
  1484. onType.addParent(newParent);
  1485. NewParentTypeMunger newParentMunger = new NewParentTypeMunger(newParent, p.getDeclaringType());
  1486. if (p.isMixin()) {
  1487. newParentMunger.setIsMixin(true);
  1488. }
  1489. newParentMunger.setSourceLocation(p.getSourceLocation());
  1490. onType.addInterTypeMunger(new BcelTypeMunger(newParentMunger, xcutSet.findAspectDeclaringParents(p)), false);
  1491. }
  1492. }
  1493. return didSomething;
  1494. }
  1495. public void weaveNormalTypeMungers(ResolvedType onType) {
  1496. ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_TYPE_MUNGERS,
  1497. onType.getName());
  1498. if (onType.isRawType() || onType.isParameterizedType()) {
  1499. onType = onType.getGenericType();
  1500. }
  1501. for (ConcreteTypeMunger m : typeMungerList) {
  1502. if (!m.isLateMunger() && m.matches(onType)) {
  1503. onType.addInterTypeMunger(m, false);
  1504. }
  1505. }
  1506. CompilationAndWeavingContext.leavingPhase(tok);
  1507. }
  1508. // exposed for ClassLoader dynamic weaving
  1509. public LazyClassGen weaveWithoutDump(UnwovenClassFile classFile, BcelObjectType classType) throws IOException {
  1510. return weave(classFile, classType, false);
  1511. }
  1512. // FOR TESTING
  1513. LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType) throws IOException {
  1514. LazyClassGen ret = weave(classFile, classType, true);
  1515. return ret;
  1516. }
  1517. private LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType, boolean dump) throws IOException {
  1518. try {
  1519. if (classType.isSynthetic()) { // Don't touch synthetic classes
  1520. if (dump) {
  1521. dumpUnchanged(classFile);
  1522. }
  1523. return null;
  1524. }
  1525. ReferenceType resolvedClassType = classType.getResolvedTypeX();
  1526. if (world.isXmlConfigured() && world.getXmlConfiguration().excludesType(resolvedClassType)) {
  1527. if (!world.getMessageHandler().isIgnoring(IMessage.INFO)) {
  1528. world.getMessageHandler().handleMessage(
  1529. MessageUtil.info("Type '" + resolvedClassType.getName()
  1530. + "' not woven due to exclusion via XML weaver exclude section"));
  1531. }
  1532. if (dump) {
  1533. dumpUnchanged(classFile);
  1534. }
  1535. return null;
  1536. }
  1537. List<ShadowMunger> shadowMungers = fastMatch(shadowMungerList, resolvedClassType);
  1538. List<ConcreteTypeMunger> typeMungers = classType.getResolvedTypeX().getInterTypeMungers();
  1539. resolvedClassType.checkInterTypeMungers();
  1540. // Decide if we need to do actual weaving for this class
  1541. boolean mightNeedToWeave = shadowMungers.size() > 0 || typeMungers.size() > 0 || classType.isAspect()
  1542. || world.getDeclareAnnotationOnMethods().size() > 0 || world.getDeclareAnnotationOnFields().size() > 0;
  1543. // May need bridge methods if on 1.5 and something in our hierarchy is
  1544. // affected by ITDs
  1545. boolean mightNeedBridgeMethods = world.isInJava5Mode() && !classType.isInterface()
  1546. && resolvedClassType.getInterTypeMungersIncludingSupers().size() > 0;
  1547. LazyClassGen clazz = null;
  1548. if (mightNeedToWeave || mightNeedBridgeMethods) {
  1549. clazz = classType.getLazyClassGen();
  1550. // System.err.println("got lazy gen: " + clazz + ", " +
  1551. // clazz.getWeaverState());
  1552. try {
  1553. boolean isChanged = false;
  1554. if (mightNeedToWeave) {
  1555. isChanged = BcelClassWeaver.weave(world, clazz, shadowMungers, typeMungers, lateTypeMungerList,
  1556. inReweavableMode);
  1557. }
  1558. checkDeclareTypeErrorOrWarning(world, classType);
  1559. if (mightNeedBridgeMethods) {
  1560. isChanged = BcelClassWeaver.calculateAnyRequiredBridgeMethods(world, clazz) || isChanged;
  1561. }
  1562. if (isChanged) {
  1563. if (dump) {
  1564. dump(classFile, clazz);
  1565. }
  1566. return clazz;
  1567. }
  1568. } catch (RuntimeException re) {
  1569. String classDebugInfo = null;
  1570. try {
  1571. classDebugInfo = clazz.toLongString();
  1572. } catch (Throwable e) {
  1573. new RuntimeException("Crashed whilst crashing with this exception: " + e, e).printStackTrace();
  1574. // recover from crash whilst producing debug string
  1575. classDebugInfo = clazz.getClassName();
  1576. }
  1577. String messageText = "trouble in: \n" + classDebugInfo;
  1578. getWorld().getMessageHandler().handleMessage(new Message(messageText, IMessage.ABORT, re, null));
  1579. } catch (Error re) {
  1580. String classDebugInfo = null;
  1581. try {
  1582. classDebugInfo = clazz.toLongString();
  1583. } catch (OutOfMemoryError oome) {
  1584. System.err.println("Ran out of memory creating debug info for an error");
  1585. re.printStackTrace(System.err);
  1586. // recover from crash whilst producing debug string
  1587. classDebugInfo = clazz.getClassName();
  1588. } catch (Throwable e) {
  1589. // recover from crash whilst producing debug string
  1590. classDebugInfo = clazz.getClassName();
  1591. }
  1592. String messageText = "trouble in: \n" + classDebugInfo;
  1593. getWorld().getMessageHandler().handleMessage(new Message(messageText, IMessage.ABORT, re, null));
  1594. }
  1595. } else {
  1596. checkDeclareTypeErrorOrWarning(world, classType);
  1597. }
  1598. // this is very odd return behavior trying to keep everyone happy
  1599. // can we remove it from the model now? we know it contains no relationship endpoints...
  1600. AsmManager model = world.getModelAsAsmManager();
  1601. if (world.isMinimalModel() && model != null && !classType.isAspect()) {
  1602. AspectJElementHierarchy hierarchy = (AspectJElementHierarchy) model.getHierarchy();
  1603. String pkgname = classType.getResolvedTypeX().getPackageName();
  1604. String tname = classType.getResolvedTypeX().getSimpleBaseName();
  1605. IProgramElement typeElement = hierarchy.findElementForType(pkgname, tname);
  1606. if (typeElement != null && hasInnerType(typeElement)) {
  1607. // Cannot remove it right now (has inner type), schedule it
  1608. // for possible deletion later if all inner types are
  1609. // removed
  1610. candidatesForRemoval.add(typeElement);
  1611. }
  1612. if (typeElement != null && !hasInnerType(typeElement)) {
  1613. IProgramElement parent = typeElement.getParent();
  1614. // parent may have children: PACKAGE DECL, IMPORT-REFERENCE, TYPE_DECL
  1615. if (parent != null) {
  1616. // if it was the only type we should probably remove
  1617. // the others too.
  1618. parent.removeChild(typeElement);
  1619. if (parent.getKind().isSourceFile()) {
  1620. removeSourceFileIfNoMoreTypeDeclarationsInside(hierarchy, typeElement, parent);
  1621. } else {
  1622. hierarchy.forget(null, typeElement);
  1623. // At this point, the child has been removed. We
  1624. // should now check if the parent is in our
  1625. // 'candidatesForRemoval' set. If it is then that
  1626. // means we were going to remove it but it had a
  1627. // child. Now we can check if it still has a child -
  1628. // if it doesn't it can also be removed!
  1629. walkUpRemovingEmptyTypesAndPossiblyEmptySourceFile(hierarchy, tname, parent);
  1630. }
  1631. }
  1632. }
  1633. }
  1634. if (dump) {
  1635. dumpUnchanged(classFile);
  1636. return clazz;
  1637. } else {
  1638. // ATAJ: the class was not weaved, but since it gets there early it
  1639. // may have new generated inner classes
  1640. // attached to it to support LTW perX aspectOf support (see
  1641. // BcelPerClauseAspectAdder)
  1642. // that aggressively defines the inner <aspect>$mayHaveAspect
  1643. // interface.
  1644. if (clazz != null && !clazz.getChildClasses(world).isEmpty()) {
  1645. return clazz;
  1646. }
  1647. return null;
  1648. }
  1649. } finally {
  1650. world.demote();
  1651. }
  1652. }
  1653. private void walkUpRemovingEmptyTypesAndPossiblyEmptySourceFile(AspectJElementHierarchy hierarchy, String tname,
  1654. IProgramElement typeThatHasChildRemoved) {
  1655. // typeThatHasChildRemoved might be a source file, type or a method/ctor
  1656. // - for a method/ctor find the type/sourcefile
  1657. while (typeThatHasChildRemoved != null
  1658. && !(typeThatHasChildRemoved.getKind().isType() || typeThatHasChildRemoved.getKind().isSourceFile())) {
  1659. // this will take us 'up' through methods that contain anonymous
  1660. // inner classes
  1661. typeThatHasChildRemoved = typeThatHasChildRemoved.getParent();
  1662. }
  1663. // now typeThatHasChildRemoved points to the type or sourcefile that has
  1664. // had something removed
  1665. if (candidatesForRemoval.contains(typeThatHasChildRemoved) && !hasInnerType(typeThatHasChildRemoved)) {
  1666. // now we can get rid of it
  1667. IProgramElement parent = typeThatHasChildRemoved.getParent();
  1668. if (parent != null) {
  1669. parent.removeChild(typeThatHasChildRemoved);
  1670. candidatesForRemoval.remove(typeThatHasChildRemoved);
  1671. if (parent.getKind().isSourceFile()) {
  1672. removeSourceFileIfNoMoreTypeDeclarationsInside(hierarchy, typeThatHasChildRemoved, parent);
  1673. // System.out.println("Removed on second pass: " +
  1674. // typeThatHasChildRemoved.getName());
  1675. } else {
  1676. // System.out.println("On later pass, parent of type " +
  1677. // typeThatHasChildRemoved.getName()
  1678. // + " was found not to be a sourcefile, recursing up...");
  1679. walkUpRemovingEmptyTypesAndPossiblyEmptySourceFile(hierarchy, tname, parent);
  1680. }
  1681. }
  1682. }
  1683. }
  1684. private void removeSourceFileIfNoMoreTypeDeclarationsInside(AspectJElementHierarchy hierarchy, IProgramElement typeElement,
  1685. IProgramElement sourceFileNode) {
  1686. IProgramElement compilationUnit = sourceFileNode;
  1687. boolean anyOtherTypeDeclarations = false;
  1688. for (IProgramElement child : compilationUnit.getChildren()) {
  1689. IProgramElement.Kind k = child.getKind();
  1690. if (k.isType()) {
  1691. anyOtherTypeDeclarations = true;
  1692. break;
  1693. }
  1694. }
  1695. // If the compilation unit node contained no
  1696. // other types, there is no need to keep it
  1697. if (!anyOtherTypeDeclarations) {
  1698. IProgramElement cuParent = compilationUnit.getParent();
  1699. if (cuParent != null) {
  1700. compilationUnit.setParent(null);
  1701. cuParent.removeChild(compilationUnit);
  1702. }
  1703. // need to update some caches and structures too?
  1704. hierarchy.forget(sourceFileNode, typeElement);
  1705. } else {
  1706. hierarchy.forget(null, typeElement);
  1707. }
  1708. }
  1709. // ---- writing
  1710. // TODO could be smarter - really only matters if inner type has been woven, but there is a chance we haven't woven it *yet*
  1711. private boolean hasInnerType(IProgramElement typeNode) {
  1712. for (IProgramElement child : typeNode.getChildren()) {
  1713. IProgramElement.Kind kind = child.getKind();
  1714. if (kind.isType()) {
  1715. return true;
  1716. }
  1717. // if (kind == IProgramElement.Kind.ASPECT) {
  1718. // return true;
  1719. // }
  1720. if (kind.isType() || kind == IProgramElement.Kind.METHOD || kind == IProgramElement.Kind.CONSTRUCTOR) {
  1721. boolean b = hasInnerType(child);
  1722. if (b) {
  1723. return b;
  1724. }
  1725. }
  1726. }
  1727. return false;
  1728. }
  1729. private void checkDeclareTypeErrorOrWarning(BcelWorld world2, BcelObjectType classType) {
  1730. List<DeclareTypeErrorOrWarning> dteows = world.getDeclareTypeEows();
  1731. for (DeclareTypeErrorOrWarning dteow : dteows) {
  1732. if (dteow.getTypePattern().matchesStatically(classType.getResolvedTypeX())) {
  1733. if (dteow.isError()) {
  1734. world.getMessageHandler().handleMessage(
  1735. MessageUtil.error(dteow.getMessage(), classType.getResolvedTypeX().getSourceLocation()));
  1736. } else {
  1737. world.getMessageHandler().handleMessage(
  1738. MessageUtil.warn(dteow.getMessage(), classType.getResolvedTypeX().getSourceLocation()));
  1739. }
  1740. }
  1741. }
  1742. }
  1743. private void dumpUnchanged(UnwovenClassFile classFile) throws IOException {
  1744. if (zipOutputStream != null) {
  1745. writeZipEntry(getEntryName(classFile.getJavaClass().getClassName()), classFile.getBytes());
  1746. } else {
  1747. classFile.writeUnchangedBytes();
  1748. }
  1749. }
  1750. private String getEntryName(String className) {
  1751. // XXX what does bcel's getClassName do for inner names
  1752. return className.replace('.', '/') + ".class";
  1753. }
  1754. private void dump(UnwovenClassFile classFile, LazyClassGen clazz) throws IOException {
  1755. if (zipOutputStream != null) {
  1756. String mainClassName = classFile.getJavaClass().getClassName();
  1757. writeZipEntry(getEntryName(mainClassName), clazz.getJavaClass(world).getBytes());
  1758. List<UnwovenClassFile.ChildClass> childClasses = clazz.getChildClasses(world);
  1759. if (!childClasses.isEmpty()) {
  1760. for (Iterator<UnwovenClassFile.ChildClass> i = childClasses.iterator(); i.hasNext();) {
  1761. UnwovenClassFile.ChildClass c = i.next();
  1762. writeZipEntry(getEntryName(mainClassName + "$" + c.name), c.bytes);
  1763. }
  1764. }
  1765. } else {
  1766. classFile.writeWovenBytes(clazz.getJavaClass(world).getBytes(), clazz.getChildClasses(world));
  1767. }
  1768. }
  1769. private void writeZipEntry(String name, byte[] bytes) throws IOException {
  1770. ZipEntry newEntry = new ZipEntry(name); // ??? get compression scheme
  1771. // right
  1772. zipOutputStream.putNextEntry(newEntry);
  1773. zipOutputStream.write(bytes);
  1774. zipOutputStream.closeEntry();
  1775. }
  1776. /**
  1777. * Perform a fast match of the specified list of shadowmungers against the specified type. A subset of those that might match is
  1778. * returned.
  1779. *
  1780. * @param list list of all shadow mungers that might match
  1781. * @param type the target type
  1782. * @return a list of shadow mungers that might match with those that cannot (according to fast match rules) removed
  1783. */
  1784. private List<ShadowMunger> fastMatch(List<ShadowMunger> list, ResolvedType type) {
  1785. if (list == null) {
  1786. return Collections.emptyList();
  1787. }
  1788. boolean isOverweaving = world.isOverWeaving();
  1789. WeaverStateInfo typeWeaverState = (isOverweaving ? type.getWeaverState() : null);
  1790. // here we do the coarsest grained fast match with no kind constraints
  1791. // this will remove all obvious non-matches and see if we need to do any
  1792. // weaving
  1793. FastMatchInfo info = new FastMatchInfo(type, null, world);
  1794. List<ShadowMunger> result = new ArrayList<ShadowMunger>();
  1795. if (world.areInfoMessagesEnabled() && world.isTimingEnabled()) {
  1796. for (ShadowMunger munger : list) {
  1797. if (typeWeaverState != null) { // will only be null if overweaving is ON and there is weaverstate
  1798. ResolvedType declaringAspect = munger.getDeclaringType();
  1799. if (typeWeaverState.isAspectAlreadyApplied(declaringAspect)) {
  1800. continue;
  1801. }
  1802. }
  1803. Pointcut pointcut = munger.getPointcut();
  1804. long starttime = System.nanoTime();
  1805. FuzzyBoolean fb = pointcut.fastMatch(info);
  1806. long endtime = System.nanoTime();
  1807. world.recordFastMatch(pointcut, endtime - starttime);
  1808. if (fb.maybeTrue()) {
  1809. result.add(munger);
  1810. }
  1811. }
  1812. } else {
  1813. for (ShadowMunger munger : list) {
  1814. if (typeWeaverState != null) { // will only be null if overweaving is ON and there is weaverstate
  1815. ResolvedType declaringAspect = munger.getConcreteAspect();// getDeclaringType();
  1816. if (typeWeaverState.isAspectAlreadyApplied(declaringAspect)) {
  1817. continue;
  1818. }
  1819. }
  1820. Pointcut pointcut = munger.getPointcut();
  1821. FuzzyBoolean fb = pointcut.fastMatch(info);
  1822. if (fb.maybeTrue()) {
  1823. result.add(munger);
  1824. }
  1825. }
  1826. }
  1827. return result;
  1828. }
  1829. public void setReweavableMode(boolean xNotReweavable) {
  1830. inReweavableMode = !xNotReweavable;
  1831. WeaverStateInfo.setReweavableModeDefaults(!xNotReweavable, false, true);
  1832. }
  1833. public boolean isReweavable() {
  1834. return inReweavableMode;
  1835. }
  1836. public World getWorld() {
  1837. return world;
  1838. }
  1839. public void tidyUp() {
  1840. if (trace.isTraceEnabled()) {
  1841. trace.enter("tidyUp", this);
  1842. }
  1843. shadowMungerList = null; // setup by prepareForWeave
  1844. typeMungerList = null; // setup by prepareForWeave
  1845. lateTypeMungerList = null; // setup by prepareForWeave
  1846. declareParentsList = null; // setup by prepareForWeave
  1847. if (trace.isTraceEnabled()) {
  1848. trace.exit("tidyUp");
  1849. }
  1850. }
  1851. public void write(CompressingDataOutputStream dos) throws IOException {
  1852. xcutSet.write(dos);
  1853. }
  1854. // only called for testing
  1855. public void setShadowMungers(List<ShadowMunger> shadowMungers) {
  1856. shadowMungerList = shadowMungers;
  1857. }
  1858. }