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

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