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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036
  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 v 2.0
  6. * which accompanies this distribution and is available at
  7. * https://www.eclipse.org/org/documents/epl-2.0/EPL-2.0.txt
  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<>();
  108. private transient List<String> deletedTypenames = new ArrayList<>();
  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<>();
  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<>();
  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<>();
  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 (File file : files) {
  336. addedClassFiles.add(addClassFile(file, 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<>();
  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<JarEntry> 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. StringBuilder sb = new StringBuilder();
  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. StringBuilder sb = new StringBuilder();
  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 (UnwovenClassFile jc : addedClasses) {
  458. String name = jc.getClassName();
  459. ResolvedType type = world.resolve(name);
  460. // No overweaving guard. If you have one then when overweaving is on the
  461. // addOrReplaceAspect will not be called when the aspect delegate changes from
  462. // EclipseSourceType to BcelObjectType. This will mean the mungers
  463. // are not picked up.
  464. if (type.isAspect()) {
  465. needToReweaveWorld |= xcutSet.addOrReplaceAspect(type);
  466. }
  467. }
  468. for (String name : deletedTypenames) {
  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. shadowMungerList.sort(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 (UnwovenClassFile jc : addedClasses) {
  519. String name = jc.getClassName();
  520. ResolvedType type = world.resolve(name);
  521. if (type.isAspect()) {
  522. Collection<ShadowMunger> shadowMungers = customMungerFactory.createCustomShadowMungers(type);
  523. if (shadowMungers != null) {
  524. shadowMungerList.addAll(shadowMungers);
  525. }
  526. Collection<ConcreteTypeMunger> typeMungers = customMungerFactory.createCustomTypeMungers(type);
  527. if (typeMungers != null) {
  528. typeMungerList.addAll(typeMungers);
  529. }
  530. }
  531. }
  532. }
  533. }
  534. public void setCustomMungerFactory(CustomMungerFactory factory) {
  535. customMungerFactory = factory;
  536. }
  537. /*
  538. * Rewrite all of the pointcuts in the world into their most efficient form for subsequent matching. Also ensure that if
  539. * pc1.equals(pc2) then pc1 == pc2 (for non-binding pcds) by making references all point to the same instance. Since pointcuts
  540. * remember their match decision on the last shadow, this makes matching faster when many pointcuts share common elements, or
  541. * even when one single pointcut has one common element (which can be a side-effect of DNF rewriting).
  542. */
  543. private void rewritePointcuts(List<ShadowMunger> shadowMungers) {
  544. PointcutRewriter rewriter = new PointcutRewriter();
  545. for (ShadowMunger munger : shadowMungers) {
  546. Pointcut p = munger.getPointcut();
  547. Pointcut newP = rewriter.rewrite(p);
  548. // validateBindings now whilst we still have around the pointcut
  549. // that resembles what the user actually wrote in their program
  550. // text.
  551. if (munger instanceof Advice) {
  552. Advice advice = (Advice) munger;
  553. if (advice.getSignature() != null) {
  554. final int numFormals;
  555. final String names[];
  556. // If the advice is being concretized in a @AJ aspect *and*
  557. // the advice was declared in
  558. // an @AJ aspect (it could have been inherited from a code
  559. // style aspect) then
  560. // evaluate the alternative set of formals. pr125699
  561. if ((advice.getConcreteAspect().isAnnotationStyleAspect() && advice.getDeclaringAspect() != null && advice
  562. .getDeclaringAspect().resolve(world).isAnnotationStyleAspect())
  563. || advice.isAnnotationStyle()) {
  564. numFormals = advice.getBaseParameterCount();
  565. int numArgs = advice.getSignature().getParameterTypes().length;
  566. if (numFormals > 0) {
  567. names = advice.getSignature().getParameterNames(world);
  568. validateBindings(newP, p, numArgs, names);
  569. }
  570. } else {
  571. numFormals = advice.getBaseParameterCount();
  572. if (numFormals > 0) {
  573. names = advice.getBaseParameterNames(world);
  574. validateBindings(newP, p, numFormals, names);
  575. }
  576. }
  577. }
  578. }
  579. newP.m_ignoreUnboundBindingForNames = p.m_ignoreUnboundBindingForNames;
  580. munger.setPointcut(newP);
  581. }
  582. // now that we have optimized individual pointcuts, optimize
  583. // across the set of pointcuts....
  584. // Use a map from key based on pc equality, to value based on
  585. // pc identity.
  586. Map<Pointcut, Pointcut> pcMap = new HashMap<>();
  587. for (ShadowMunger munger: shadowMungers) {
  588. Pointcut p = munger.getPointcut();
  589. Pointcut newP = shareEntriesFromMap(p, pcMap);
  590. newP.m_ignoreUnboundBindingForNames = p.m_ignoreUnboundBindingForNames;
  591. munger.setPointcut(newP);
  592. }
  593. }
  594. private Pointcut shareEntriesFromMap(Pointcut p, Map<Pointcut, Pointcut> pcMap) {
  595. // some things cant be shared...
  596. if (p instanceof NameBindingPointcut) {
  597. return p;
  598. }
  599. if (p instanceof IfPointcut) {
  600. return p;
  601. }
  602. if (p instanceof ConcreteCflowPointcut) {
  603. return p;
  604. }
  605. if (p instanceof AndPointcut) {
  606. AndPointcut apc = (AndPointcut) p;
  607. Pointcut left = shareEntriesFromMap(apc.getLeft(), pcMap);
  608. Pointcut right = shareEntriesFromMap(apc.getRight(), pcMap);
  609. return new AndPointcut(left, right);
  610. } else if (p instanceof OrPointcut) {
  611. OrPointcut opc = (OrPointcut) p;
  612. Pointcut left = shareEntriesFromMap(opc.getLeft(), pcMap);
  613. Pointcut right = shareEntriesFromMap(opc.getRight(), pcMap);
  614. return new OrPointcut(left, right);
  615. } else if (p instanceof NotPointcut) {
  616. NotPointcut npc = (NotPointcut) p;
  617. Pointcut not = shareEntriesFromMap(npc.getNegatedPointcut(), pcMap);
  618. return new NotPointcut(not);
  619. } else {
  620. // primitive pcd
  621. if (pcMap.containsKey(p)) { // based on equality
  622. return pcMap.get(p); // same instance (identity)
  623. } else {
  624. pcMap.put(p, p);
  625. return p;
  626. }
  627. }
  628. }
  629. // userPointcut is the pointcut that the user wrote in the program text.
  630. // dnfPointcut is the same pointcut rewritten in DNF
  631. // numFormals is the number of formal parameters in the pointcut
  632. // if numFormals > 0 then every branch of a disjunction must bind each
  633. // formal once and only once.
  634. // in addition, the left and right branches of a disjunction must hold on
  635. // join point kinds in common.
  636. private void validateBindings(Pointcut dnfPointcut, Pointcut userPointcut, int numFormals, String[] names) {
  637. if (numFormals == 0) {
  638. return; // nothing to check
  639. }
  640. if (dnfPointcut.couldMatchKinds() == Shadow.NO_SHADOW_KINDS_BITS) {
  641. return; // cant have problems if you dont match!
  642. }
  643. if (dnfPointcut instanceof OrPointcut) {
  644. OrPointcut orBasedDNFPointcut = (OrPointcut) dnfPointcut;
  645. Pointcut[] leftBindings = new Pointcut[numFormals];
  646. Pointcut[] rightBindings = new Pointcut[numFormals];
  647. validateOrBranch(orBasedDNFPointcut, userPointcut, numFormals, names, leftBindings, rightBindings);
  648. } else {
  649. Pointcut[] bindings = new Pointcut[numFormals];
  650. validateSingleBranch(dnfPointcut, userPointcut, numFormals, names, bindings);
  651. }
  652. }
  653. private void validateOrBranch(OrPointcut pc, Pointcut userPointcut, int numFormals, String[] names, Pointcut[] leftBindings,
  654. Pointcut[] rightBindings) {
  655. Pointcut left = pc.getLeft();
  656. Pointcut right = pc.getRight();
  657. if (left instanceof OrPointcut) {
  658. Pointcut[] newRightBindings = new Pointcut[numFormals];
  659. validateOrBranch((OrPointcut) left, userPointcut, numFormals, names, leftBindings, newRightBindings);
  660. } else {
  661. if (left.couldMatchKinds() != Shadow.NO_SHADOW_KINDS_BITS) {
  662. validateSingleBranch(left, userPointcut, numFormals, names, leftBindings);
  663. }
  664. }
  665. if (right instanceof OrPointcut) {
  666. Pointcut[] newLeftBindings = new Pointcut[numFormals];
  667. validateOrBranch((OrPointcut) right, userPointcut, numFormals, names, newLeftBindings, rightBindings);
  668. } else {
  669. if (right.couldMatchKinds() != Shadow.NO_SHADOW_KINDS_BITS) {
  670. validateSingleBranch(right, userPointcut, numFormals, names, rightBindings);
  671. }
  672. }
  673. int kindsInCommon = left.couldMatchKinds() & right.couldMatchKinds();
  674. if (kindsInCommon != Shadow.NO_SHADOW_KINDS_BITS && couldEverMatchSameJoinPoints(left, right)) {
  675. // we know that every branch binds every formal, so there is no
  676. // ambiguity if each branch binds it in exactly the same way...
  677. List<String> ambiguousNames = new ArrayList<>();
  678. for (int i = 0; i < numFormals; i++) {
  679. if (leftBindings[i] == null) {
  680. if (rightBindings[i] != null) {
  681. ambiguousNames.add(names[i]);
  682. }
  683. } else if (!leftBindings[i].equals(rightBindings[i])) {
  684. ambiguousNames.add(names[i]);
  685. }
  686. }
  687. if (!ambiguousNames.isEmpty()) {
  688. raiseAmbiguityInDisjunctionError(userPointcut, ambiguousNames);
  689. }
  690. }
  691. }
  692. // pc is a pointcut that does not contain any disjunctions
  693. // check that every formal is bound (negation doesn't count).
  694. // we know that numFormals > 0 or else we would not be called
  695. private void validateSingleBranch(Pointcut pc, Pointcut userPointcut, int numFormals, String[] names, Pointcut[] bindings) {
  696. boolean[] foundFormals = new boolean[numFormals];
  697. for (int i = 0; i < foundFormals.length; i++) {
  698. foundFormals[i] = false;
  699. }
  700. validateSingleBranchRecursion(pc, userPointcut, foundFormals, names, bindings);
  701. for (int i = 0; i < foundFormals.length; i++) {
  702. if (!foundFormals[i]) {
  703. boolean ignore = false;
  704. // ATAJ soften the unbound error for implicit bindings like
  705. // JoinPoint in @AJ style
  706. for (int j = 0; j < userPointcut.m_ignoreUnboundBindingForNames.length; j++) {
  707. if (names[i] != null && names[i].equals(userPointcut.m_ignoreUnboundBindingForNames[j])) {
  708. ignore = true;
  709. break;
  710. }
  711. }
  712. if (!ignore) {
  713. raiseUnboundFormalError(names[i], userPointcut);
  714. }
  715. }
  716. }
  717. }
  718. // each formal must appear exactly once
  719. private void validateSingleBranchRecursion(Pointcut pc, Pointcut userPointcut, boolean[] foundFormals, String[] names,
  720. Pointcut[] bindings) {
  721. if (pc instanceof NotPointcut) {
  722. // nots can only appear at leaves in DNF
  723. NotPointcut not = (NotPointcut) pc;
  724. if (not.getNegatedPointcut() instanceof NameBindingPointcut) {
  725. NameBindingPointcut nnbp = (NameBindingPointcut) not.getNegatedPointcut();
  726. if (!nnbp.getBindingAnnotationTypePatterns().isEmpty() && !nnbp.getBindingTypePatterns().isEmpty()) {
  727. raiseNegationBindingError(userPointcut);
  728. }
  729. }
  730. } else if (pc instanceof AndPointcut) {
  731. AndPointcut and = (AndPointcut) pc;
  732. validateSingleBranchRecursion(and.getLeft(), userPointcut, foundFormals, names, bindings);
  733. validateSingleBranchRecursion(and.getRight(), userPointcut, foundFormals, names, bindings);
  734. } else if (pc instanceof NameBindingPointcut) {
  735. List<BindingTypePattern> bindingTypePatterns = ((NameBindingPointcut) pc).getBindingTypePatterns();
  736. for (BindingTypePattern bindingTypePattern: bindingTypePatterns) {
  737. int index = bindingTypePattern.getFormalIndex();
  738. bindings[index] = pc;
  739. if (foundFormals[index]) {
  740. raiseAmbiguousBindingError(names[index], userPointcut);
  741. } else {
  742. foundFormals[index] = true;
  743. }
  744. }
  745. List<BindingPattern> bindingAnnotationTypePatterns = ((NameBindingPointcut) pc).getBindingAnnotationTypePatterns();
  746. for (BindingPattern bindingAnnotationTypePattern: bindingAnnotationTypePatterns) {
  747. int index = bindingAnnotationTypePattern.getFormalIndex();
  748. bindings[index] = pc;
  749. if (foundFormals[index]) {
  750. raiseAmbiguousBindingError(names[index], userPointcut);
  751. } else {
  752. foundFormals[index] = true;
  753. }
  754. }
  755. } else if (pc instanceof ConcreteCflowPointcut) {
  756. ConcreteCflowPointcut cfp = (ConcreteCflowPointcut) pc;
  757. int[] slots = cfp.getUsedFormalSlots();
  758. for (int slot : slots) {
  759. bindings[slot] = cfp;
  760. if (foundFormals[slot]) {
  761. raiseAmbiguousBindingError(names[slot], userPointcut);
  762. } else {
  763. foundFormals[slot] = true;
  764. }
  765. }
  766. }
  767. }
  768. // By returning false from this method, we are allowing binding of the same
  769. // variable on either side of an or.
  770. // Be conservative :- have to consider overriding, varargs, autoboxing,
  771. // the effects of itds (on within for example), interfaces, the fact that
  772. // join points can have multiple signatures and so on.
  773. private boolean couldEverMatchSameJoinPoints(Pointcut left, Pointcut right) {
  774. if (left instanceof OrPointcut) {
  775. OrPointcut leftOrPointcut = (OrPointcut) left;
  776. if (couldEverMatchSameJoinPoints(leftOrPointcut.getLeft(), right)) {
  777. return true;
  778. }
  779. if (couldEverMatchSameJoinPoints(leftOrPointcut.getRight(), right)) {
  780. return true;
  781. }
  782. return false;
  783. }
  784. if (right instanceof OrPointcut) {
  785. OrPointcut rightOrPointcut = (OrPointcut) right;
  786. if (couldEverMatchSameJoinPoints(left, rightOrPointcut.getLeft())) {
  787. return true;
  788. }
  789. if (couldEverMatchSameJoinPoints(left, rightOrPointcut.getRight())) {
  790. return true;
  791. }
  792. return false;
  793. }
  794. // look for withins
  795. WithinPointcut leftWithin = (WithinPointcut) findFirstPointcutIn(left, WithinPointcut.class);
  796. WithinPointcut rightWithin = (WithinPointcut) findFirstPointcutIn(right, WithinPointcut.class);
  797. if ((leftWithin != null) && (rightWithin != null)) {
  798. if (!leftWithin.couldEverMatchSameJoinPointsAs(rightWithin)) {
  799. return false;
  800. }
  801. }
  802. // look for kinded
  803. KindedPointcut leftKind = (KindedPointcut) findFirstPointcutIn(left, KindedPointcut.class);
  804. KindedPointcut rightKind = (KindedPointcut) findFirstPointcutIn(right, KindedPointcut.class);
  805. if ((leftKind != null) && (rightKind != null)) {
  806. if (!leftKind.couldEverMatchSameJoinPointsAs(rightKind)) {
  807. return false;
  808. }
  809. }
  810. return true;
  811. }
  812. private Pointcut findFirstPointcutIn(Pointcut toSearch, Class<?> toLookFor) {
  813. if (toSearch instanceof NotPointcut) {
  814. return null;
  815. }
  816. if (toLookFor.isInstance(toSearch)) {
  817. return toSearch;
  818. }
  819. if (toSearch instanceof AndPointcut) {
  820. AndPointcut apc = (AndPointcut) toSearch;
  821. Pointcut left = findFirstPointcutIn(apc.getLeft(), toLookFor);
  822. if (left != null) {
  823. return left;
  824. }
  825. return findFirstPointcutIn(apc.getRight(), toLookFor);
  826. }
  827. return null;
  828. }
  829. /**
  830. * @param userPointcut
  831. */
  832. private void raiseNegationBindingError(Pointcut userPointcut) {
  833. world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.NEGATION_DOESNT_ALLOW_BINDING), userPointcut
  834. .getSourceContext().makeSourceLocation(userPointcut), null);
  835. }
  836. private void raiseAmbiguousBindingError(String name, Pointcut pointcut) {
  837. world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.AMBIGUOUS_BINDING, name), pointcut
  838. .getSourceContext().makeSourceLocation(pointcut), null);
  839. }
  840. /**
  841. * @param userPointcut
  842. */
  843. private void raiseAmbiguityInDisjunctionError(Pointcut userPointcut, List<String> names) {
  844. StringBuffer formalNames = new StringBuffer(names.get(0).toString());
  845. for (int i = 1; i < names.size(); i++) {
  846. formalNames.append(", ");
  847. formalNames.append(names.get(i));
  848. }
  849. world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.AMBIGUOUS_BINDING_IN_OR, formalNames), userPointcut
  850. .getSourceContext().makeSourceLocation(userPointcut), null);
  851. }
  852. /**
  853. * @param name
  854. * @param userPointcut
  855. */
  856. private void raiseUnboundFormalError(String name, Pointcut userPointcut) {
  857. world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.UNBOUND_FORMAL, name),
  858. userPointcut.getSourceLocation(), null);
  859. }
  860. public void addManifest(Manifest newManifest) {
  861. // System.out.println("? addManifest() newManifest=" + newManifest);
  862. if (manifest == null) {
  863. manifest = newManifest;
  864. }
  865. }
  866. public Manifest getManifest(boolean shouldCreate) {
  867. if (manifest == null && shouldCreate) {
  868. String WEAVER_MANIFEST_VERSION = "1.0";
  869. Attributes.Name CREATED_BY = new Name("Created-By");
  870. String WEAVER_CREATED_BY = "AspectJ Compiler";
  871. manifest = new Manifest();
  872. Attributes attributes = manifest.getMainAttributes();
  873. attributes.put(Name.MANIFEST_VERSION, WEAVER_MANIFEST_VERSION);
  874. attributes.put(CREATED_BY, WEAVER_CREATED_BY);
  875. }
  876. return manifest;
  877. }
  878. // ---- weaving
  879. // FOR TESTING
  880. public Collection<String> weave(File file) throws IOException {
  881. OutputStream os = FileUtil.makeOutputStream(file);
  882. this.zipOutputStream = new ZipOutputStream(os);
  883. prepareForWeave();
  884. Collection<String> c = weave(new IClassFileProvider() {
  885. public boolean isApplyAtAspectJMungersOnly() {
  886. return false;
  887. }
  888. public Iterator<UnwovenClassFile> getClassFileIterator() {
  889. return addedClasses.iterator();
  890. }
  891. public IWeaveRequestor getRequestor() {
  892. return new IWeaveRequestor() {
  893. public void acceptResult(IUnwovenClassFile result) {
  894. try {
  895. writeZipEntry(result.getFilename(), result.getBytes());
  896. } catch (IOException ex) {
  897. }
  898. }
  899. public void processingReweavableState() {
  900. }
  901. public void addingTypeMungers() {
  902. }
  903. public void weavingAspects() {
  904. }
  905. public void weavingClasses() {
  906. }
  907. public void weaveCompleted() {
  908. }
  909. };
  910. }
  911. });
  912. // /* BUG 40943*/
  913. // dumpResourcesToOutJar();
  914. zipOutputStream.close(); // this flushes and closes the acutal file
  915. return c;
  916. }
  917. private Set<IProgramElement> candidatesForRemoval = null;
  918. // variation of "weave" that sources class files from an external source.
  919. public Collection<String> weave(IClassFileProvider input) throws IOException {
  920. if (trace.isTraceEnabled()) {
  921. trace.enter("weave", this, input);
  922. }
  923. ContextToken weaveToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING, "");
  924. Collection<String> wovenClassNames = new ArrayList<>();
  925. IWeaveRequestor requestor = input.getRequestor();
  926. if (world.getModel() != null && world.isMinimalModel()) {
  927. candidatesForRemoval = new HashSet<>();
  928. }
  929. if (world.getModel() != null && !isBatchWeave) {
  930. AsmManager manager = world.getModelAsAsmManager();
  931. for (Iterator<UnwovenClassFile> i = input.getClassFileIterator(); i.hasNext();) {
  932. UnwovenClassFile classFile = i.next();
  933. // remove all relationships where this file being woven is
  934. // the target of the relationship
  935. manager.removeRelationshipsTargettingThisType(classFile.getClassName());
  936. }
  937. }
  938. // Go through the types and ensure any 'damaged' during compile time are
  939. // repaired prior to weaving
  940. for (Iterator<UnwovenClassFile> i = input.getClassFileIterator(); i.hasNext();) {
  941. UnwovenClassFile classFile = i.next();
  942. if (classFile.shouldBeWoven()) {
  943. String className = classFile.getClassName();
  944. ResolvedType theType = world.resolve(className);
  945. if (theType != null) {
  946. theType.ensureConsistent();
  947. }
  948. }
  949. }
  950. // special case for AtAspectJMungerOnly - see #113587
  951. if (input.isApplyAtAspectJMungersOnly()) {
  952. ContextToken atAspectJMungersOnly = CompilationAndWeavingContext.enteringPhase(
  953. CompilationAndWeavingContext.PROCESSING_ATASPECTJTYPE_MUNGERS_ONLY, "");
  954. requestor.weavingAspects();
  955. // ContextToken aspectToken =
  956. CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_ASPECTS, "");
  957. for (Iterator<UnwovenClassFile> i = input.getClassFileIterator(); i.hasNext();) {
  958. UnwovenClassFile classFile = i.next();
  959. if (classFile.shouldBeWoven()) {
  960. String className = classFile.getClassName();
  961. ResolvedType theType = world.resolve(className);
  962. if (theType.isAnnotationStyleAspect()) {
  963. BcelObjectType classType = BcelWorld.getBcelObjectType(theType);
  964. if (classType == null) {
  965. throw new BCException("Can't find bcel delegate for " + className + " type=" + theType.getClass());
  966. }
  967. LazyClassGen clazz = classType.getLazyClassGen();
  968. BcelPerClauseAspectAdder selfMunger = new BcelPerClauseAspectAdder(theType, theType.getPerClause().getKind());
  969. selfMunger.forceMunge(clazz, true);
  970. classType.finishedWith();
  971. UnwovenClassFile[] newClasses = getClassFilesFor(clazz);
  972. for (UnwovenClassFile newClass : newClasses) {
  973. requestor.acceptResult(newClass);
  974. }
  975. wovenClassNames.add(classFile.getClassName());
  976. }
  977. }
  978. }
  979. requestor.weaveCompleted();
  980. CompilationAndWeavingContext.leavingPhase(atAspectJMungersOnly);
  981. return wovenClassNames;
  982. }
  983. requestor.processingReweavableState();
  984. ContextToken reweaveToken = CompilationAndWeavingContext.enteringPhase(
  985. CompilationAndWeavingContext.PROCESSING_REWEAVABLE_STATE, "");
  986. prepareToProcessReweavableState();
  987. // clear all state from files we'll be reweaving
  988. for (Iterator<UnwovenClassFile> i = input.getClassFileIterator(); i.hasNext();) {
  989. UnwovenClassFile classFile = i.next();
  990. if (classFile.shouldBeWoven()) {
  991. String className = classFile.getClassName();
  992. BcelObjectType classType = getClassType(className);
  993. // null return from getClassType() means the delegate is an eclipse
  994. // source type - so
  995. // there *cant* be any reweavable state... (he bravely claimed...)
  996. if (classType != null) {
  997. ContextToken tok = CompilationAndWeavingContext.enteringPhase(
  998. CompilationAndWeavingContext.PROCESSING_REWEAVABLE_STATE, className);
  999. processReweavableStateIfPresent(className, classType);
  1000. CompilationAndWeavingContext.leavingPhase(tok);
  1001. }
  1002. }
  1003. }
  1004. CompilationAndWeavingContext.leavingPhase(reweaveToken);
  1005. ContextToken typeMungingToken = CompilationAndWeavingContext.enteringPhase(
  1006. CompilationAndWeavingContext.PROCESSING_TYPE_MUNGERS, "");
  1007. requestor.addingTypeMungers();
  1008. // We process type mungers in two groups, first mungers that change the
  1009. // type
  1010. // hierarchy, then 'normal' ITD type mungers.
  1011. // Process the types in a predictable order (rather than the order
  1012. // encountered).
  1013. // For class A, the order is superclasses of A then superinterfaces of A
  1014. // (and this mechanism is applied recursively)
  1015. List<String> typesToProcess = new ArrayList<>();
  1016. for (Iterator<UnwovenClassFile> iter = input.getClassFileIterator(); iter.hasNext();) {
  1017. UnwovenClassFile clf = iter.next();
  1018. if (clf.shouldBeWoven()) {
  1019. typesToProcess.add(clf.getClassName());
  1020. }
  1021. }
  1022. while (typesToProcess.size() > 0) {
  1023. weaveParentsFor(typesToProcess, typesToProcess.get(0), null);
  1024. }
  1025. for (Iterator<UnwovenClassFile> i = input.getClassFileIterator(); i.hasNext();) {
  1026. UnwovenClassFile classFile = i.next();
  1027. if (classFile.shouldBeWoven()) {
  1028. String className = classFile.getClassName();
  1029. addNormalTypeMungers(className);
  1030. }
  1031. }
  1032. CompilationAndWeavingContext.leavingPhase(typeMungingToken);
  1033. requestor.weavingAspects();
  1034. ContextToken aspectToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_ASPECTS, "");
  1035. // first weave into aspects
  1036. for (Iterator<UnwovenClassFile> i = input.getClassFileIterator(); i.hasNext();) {
  1037. UnwovenClassFile classFile = i.next();
  1038. if (classFile.shouldBeWoven()) {
  1039. String className = classFile.getClassName();
  1040. ResolvedType theType = world.resolve(className);
  1041. if (theType.isAspect()) {
  1042. BcelObjectType classType = BcelWorld.getBcelObjectType(theType);
  1043. if (classType == null) {
  1044. // Sometimes.. if the Bcel Delegate couldn't be found then a
  1045. // problem occurred at compile time - on
  1046. // a previous compiler run. In this case I assert the
  1047. // delegate will still be an EclipseSourceType
  1048. // and we can ignore the problem here (the original compile
  1049. // error will be reported again from
  1050. // the eclipse source type) - pr113531
  1051. ReferenceTypeDelegate theDelegate = ((ReferenceType) theType).getDelegate();
  1052. if (theDelegate.getClass().getName().endsWith("EclipseSourceType")) {
  1053. continue;
  1054. }
  1055. throw new BCException("Can't find bcel delegate for " + className + " type=" + theType.getClass());
  1056. }
  1057. weaveAndNotify(classFile, classType, requestor);
  1058. wovenClassNames.add(className);
  1059. }
  1060. }
  1061. }
  1062. CompilationAndWeavingContext.leavingPhase(aspectToken);
  1063. requestor.weavingClasses();
  1064. ContextToken classToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_CLASSES, "");
  1065. // then weave into non-aspects
  1066. for (Iterator<UnwovenClassFile> i = input.getClassFileIterator(); i.hasNext();) {
  1067. UnwovenClassFile classFile = i.next();
  1068. if (classFile.shouldBeWoven()) {
  1069. String className = classFile.getClassName();
  1070. ResolvedType theType = world.resolve(className);
  1071. if (!theType.isAspect()) {
  1072. BcelObjectType classType = BcelWorld.getBcelObjectType(theType);
  1073. if (classType == null) {
  1074. // bug 119882 - see above comment for bug 113531
  1075. ReferenceTypeDelegate theDelegate = ((ReferenceType) theType).getDelegate();
  1076. // TODO urgh - put a method on the interface to check this,
  1077. // string compare is hideous
  1078. if (theDelegate.getClass().getName().endsWith("EclipseSourceType")) {
  1079. continue;
  1080. }
  1081. throw new BCException("Can't find bcel delegate for " + className + " type=" + theType.getClass());
  1082. }
  1083. weaveAndNotify(classFile, classType, requestor);
  1084. wovenClassNames.add(className);
  1085. }
  1086. }
  1087. }
  1088. CompilationAndWeavingContext.leavingPhase(classToken);
  1089. addedClasses.clear();
  1090. deletedTypenames.clear();
  1091. requestor.weaveCompleted();
  1092. CompilationAndWeavingContext.leavingPhase(weaveToken);
  1093. if (trace.isTraceEnabled()) {
  1094. trace.exit("weave", wovenClassNames);
  1095. }
  1096. if (world.getModel() != null && world.isMinimalModel()) {
  1097. candidatesForRemoval.clear();
  1098. }
  1099. return wovenClassNames;
  1100. }
  1101. public void allWeavingComplete() {
  1102. warnOnUnmatchedAdvice();
  1103. }
  1104. /**
  1105. * In 1.5 mode and with XLint:adviceDidNotMatch enabled, put out messages for any mungers that did not match anything.
  1106. */
  1107. private void warnOnUnmatchedAdvice() {
  1108. class AdviceLocation {
  1109. private final int lineNo;
  1110. private final UnresolvedType inAspect;
  1111. public AdviceLocation(BcelAdvice advice) {
  1112. this.lineNo = advice.getSourceLocation().getLine();
  1113. this.inAspect = advice.getDeclaringAspect();
  1114. }
  1115. @Override
  1116. public boolean equals(Object obj) {
  1117. if (!(obj instanceof AdviceLocation)) {
  1118. return false;
  1119. }
  1120. AdviceLocation other = (AdviceLocation) obj;
  1121. if (this.lineNo != other.lineNo) {
  1122. return false;
  1123. }
  1124. if (!this.inAspect.equals(other.inAspect)) {
  1125. return false;
  1126. }
  1127. return true;
  1128. }
  1129. @Override
  1130. public int hashCode() {
  1131. return 37 + 17 * lineNo + 17 * inAspect.hashCode();
  1132. }
  1133. }
  1134. // FIXME asc Should be factored out into Xlint code and done
  1135. // automatically for all xlint messages, ideally.
  1136. // if a piece of advice hasn't matched anywhere and we are in -1.5 mode,
  1137. // put out a warning
  1138. if (world.isInJava5Mode() && world.getLint().adviceDidNotMatch.isEnabled()) {
  1139. List<ShadowMunger> l = world.getCrosscuttingMembersSet().getShadowMungers();
  1140. Set<AdviceLocation> alreadyWarnedLocations = new HashSet<>();
  1141. for (Object o : l) {
  1142. ShadowMunger element = (ShadowMunger) o;
  1143. // This will stop us incorrectly reporting deow checkers:
  1144. if (element instanceof BcelAdvice) {
  1145. BcelAdvice ba = (BcelAdvice) element;
  1146. if (ba.getKind() == AdviceKind.CflowEntry || ba.getKind() == AdviceKind.CflowBelowEntry) {
  1147. continue;
  1148. }
  1149. if (!ba.hasMatchedSomething()) {
  1150. // Because we implement some features of AJ itself by
  1151. // creating our own kind of mungers, you sometimes
  1152. // find that ba.getSignature() is not a BcelMethod - for
  1153. // example it might be a cflow entry munger.
  1154. if (ba.getSignature() != null) {
  1155. // check we haven't already warned on this advice and line
  1156. // (cflow creates multiple mungers for the same advice)
  1157. AdviceLocation loc = new AdviceLocation(ba);
  1158. if (alreadyWarnedLocations.contains(loc)) {
  1159. continue;
  1160. } else {
  1161. alreadyWarnedLocations.add(loc);
  1162. }
  1163. if (!(ba.getSignature() instanceof BcelMethod)
  1164. || !Utility.isSuppressing(ba.getSignature(), "adviceDidNotMatch")) {
  1165. world.getLint().adviceDidNotMatch.signal(ba.getDeclaringAspect().toString(), new SourceLocation(
  1166. element.getSourceLocation().getSourceFile(), element.getSourceLocation().getLine()));
  1167. }
  1168. }
  1169. }
  1170. }
  1171. }
  1172. }
  1173. }
  1174. /**
  1175. * 'typeToWeave' is one from the 'typesForWeaving' list. This routine ensures we process supertypes (classes/interfaces) of
  1176. * 'typeToWeave' that are in the 'typesForWeaving' list before 'typeToWeave' itself. 'typesToWeave' is then removed from the
  1177. * 'typesForWeaving' list.
  1178. *
  1179. * Note: Future gotcha in here ... when supplying partial hierarchies, this algorithm may break down. If you have a hierarchy
  1180. * 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
  1181. * problems if you are supplying partial hierarchies like that !
  1182. */
  1183. private void weaveParentsFor(List<String> typesForWeaving, String typeToWeave, ResolvedType resolvedTypeToWeave) {
  1184. if (resolvedTypeToWeave == null) {
  1185. // resolve it if the caller could not pass in the resolved type
  1186. resolvedTypeToWeave = world.resolve(typeToWeave);
  1187. }
  1188. ResolvedType superclassType = resolvedTypeToWeave.getSuperclass();
  1189. String superclassTypename = (superclassType == null ? null : superclassType.getName());
  1190. // PR336654 added the 'typesForWeaving.contains(superclassTypename)' clause.
  1191. // Without it we can delete all type mungers on the parents and yet we only
  1192. // add back in the declare parents related ones, not the regular ITDs.
  1193. if (superclassType != null && !superclassType.isTypeHierarchyComplete() && superclassType.isExposedToWeaver()
  1194. && typesForWeaving.contains(superclassTypename)) {
  1195. weaveParentsFor(typesForWeaving, superclassTypename, superclassType);
  1196. }
  1197. ResolvedType[] interfaceTypes = resolvedTypeToWeave.getDeclaredInterfaces();
  1198. for (ResolvedType resolvedSuperInterface : interfaceTypes) {
  1199. if (!resolvedSuperInterface.isTypeHierarchyComplete()) {
  1200. String interfaceTypename = resolvedSuperInterface.getName();
  1201. if (resolvedSuperInterface.isExposedToWeaver()) { // typesForWeaving.contains(interfaceTypename)) {
  1202. weaveParentsFor(typesForWeaving, interfaceTypename, resolvedSuperInterface);
  1203. }
  1204. }
  1205. }
  1206. ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_DECLARE_PARENTS,
  1207. resolvedTypeToWeave.getName());
  1208. // If A was processed before B (and was declared 'class A implements B') then there is no need to complete B again, it
  1209. // will have been done whilst processing A.
  1210. if (!resolvedTypeToWeave.isTypeHierarchyComplete()) {
  1211. weaveParentTypeMungers(resolvedTypeToWeave);
  1212. }
  1213. CompilationAndWeavingContext.leavingPhase(tok);
  1214. typesForWeaving.remove(typeToWeave);
  1215. resolvedTypeToWeave.tagAsTypeHierarchyComplete();
  1216. }
  1217. public void prepareToProcessReweavableState() {
  1218. }
  1219. public void processReweavableStateIfPresent(String className, BcelObjectType classType) {
  1220. // If the class is marked reweavable, check any aspects around when it
  1221. // was built are in this world
  1222. WeaverStateInfo wsi = classType.getWeaverState();
  1223. // System.out.println(">> processReweavableStateIfPresent " + className + " wsi=" + wsi);
  1224. if (wsi != null && wsi.isReweavable()) { // Check all necessary types
  1225. // are around!
  1226. world.showMessage(IMessage.INFO, WeaverMessages.format(WeaverMessages.PROCESSING_REWEAVABLE, className, classType
  1227. .getSourceLocation().getSourceFile()), null, null);
  1228. Set<String> aspectsPreviouslyInWorld = wsi.getAspectsAffectingType();
  1229. // keep track of them just to ensure unique missing aspect error
  1230. // reporting
  1231. Set<String> alreadyConfirmedReweavableState = new HashSet<>();
  1232. for (String requiredTypeSignature : aspectsPreviouslyInWorld) {
  1233. // for (Iterator iter = aspectsPreviouslyInWorld.iterator(); iter.hasNext();) {
  1234. // String requiredTypeName = (String) iter.next();
  1235. if (!alreadyConfirmedReweavableState.contains(requiredTypeSignature)) {
  1236. ResolvedType rtx = world.resolve(UnresolvedType.forSignature(requiredTypeSignature), true);
  1237. boolean exists = !rtx.isMissing();
  1238. if (!world.isOverWeaving()) {
  1239. if (!exists) {
  1240. world.getLint().missingAspectForReweaving.signal(new String[] { rtx.getName(), className },
  1241. classType.getSourceLocation(), null);
  1242. // world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.MISSING_REWEAVABLE_TYPE,
  1243. // requiredTypeName, className), classType.getSourceLocation(), null);
  1244. } else {
  1245. // weaved in aspect that are not declared in aop.xml
  1246. // trigger an error for now
  1247. // may cause headhache for LTW and packaged lib
  1248. // without aop.xml in
  1249. // see #104218
  1250. if (!xcutSet.containsAspect(rtx)) {
  1251. world.showMessage(IMessage.ERROR, WeaverMessages.format(
  1252. WeaverMessages.REWEAVABLE_ASPECT_NOT_REGISTERED, rtx.getName(), className), null, null);
  1253. } else if (!world.getMessageHandler().isIgnoring(IMessage.INFO)) {
  1254. world.showMessage(IMessage.INFO, WeaverMessages.format(WeaverMessages.VERIFIED_REWEAVABLE_TYPE,
  1255. rtx.getName(), rtx.getSourceLocation().getSourceFile()), null, null);
  1256. }
  1257. alreadyConfirmedReweavableState.add(requiredTypeSignature);
  1258. }
  1259. }
  1260. }
  1261. }
  1262. // old:
  1263. // classType.setJavaClass(Utility.makeJavaClass(classType.getJavaClass
  1264. // ().getFileName(), wsi.getUnwovenClassFileData()));
  1265. // new: reweavable default with clever diff
  1266. if (!world.isOverWeaving()) {
  1267. byte[] ucfd = wsi.getUnwovenClassFileData();
  1268. if (ucfd.length == 0) {
  1269. // Size 0 indicates the class was previously overwoven, so you need to be overweaving now!
  1270. world.getMessageHandler().handleMessage(
  1271. MessageUtil.error(
  1272. WeaverMessages.format(WeaverMessages.MUST_KEEP_OVERWEAVING_ONCE_START,
  1273. className)));
  1274. // onType.getName(), annoX.getTypeName(), annoX.getValidTargets()),
  1275. // decA.getSourceLocation()));
  1276. } else {
  1277. byte[] bytes = wsi.getUnwovenClassFileData(classType.getJavaClass().getBytes());
  1278. JavaClass newJavaClass = Utility.makeJavaClass(classType.getJavaClass().getFileName(), bytes);
  1279. classType.setJavaClass(newJavaClass, true);
  1280. classType.getResolvedTypeX().ensureConsistent();
  1281. }
  1282. }
  1283. // } else {
  1284. // classType.resetState();
  1285. }
  1286. }
  1287. private void weaveAndNotify(UnwovenClassFile classFile, BcelObjectType classType, IWeaveRequestor requestor) throws IOException {
  1288. trace.enter("weaveAndNotify", this, new Object[] { classFile, classType, requestor });
  1289. ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_TYPE, classType
  1290. .getResolvedTypeX().getName());
  1291. LazyClassGen clazz = weaveWithoutDump(classFile, classType);
  1292. classType.finishedWith();
  1293. // clazz is null if the classfile was unchanged by weaving...
  1294. if (clazz != null) {
  1295. UnwovenClassFile[] newClasses = getClassFilesFor(clazz);
  1296. // OPTIMIZE can we avoid using the string name at all in
  1297. // UnwovenClassFile instances?
  1298. // Copy the char[] across as it means the
  1299. // WeaverAdapter.removeFromMap() can be fast!
  1300. if (newClasses[0].getClassName().equals(classFile.getClassName())) {
  1301. newClasses[0].setClassNameAsChars(classFile.getClassNameAsChars());
  1302. }
  1303. for (UnwovenClassFile newClass : newClasses) {
  1304. requestor.acceptResult(newClass);
  1305. }
  1306. } else {
  1307. requestor.acceptResult(classFile);
  1308. }
  1309. classType.weavingCompleted();
  1310. CompilationAndWeavingContext.leavingPhase(tok);
  1311. trace.exit("weaveAndNotify");
  1312. }
  1313. /**
  1314. * helper method - will return NULL if the underlying delegate is an EclipseSourceType and not a BcelObjectType
  1315. */
  1316. public BcelObjectType getClassType(String forClass) {
  1317. return BcelWorld.getBcelObjectType(world.resolve(forClass));
  1318. }
  1319. public void addParentTypeMungers(String typeName) {
  1320. weaveParentTypeMungers(world.resolve(typeName));
  1321. }
  1322. public void addNormalTypeMungers(String typeName) {
  1323. weaveNormalTypeMungers(world.resolve(typeName));
  1324. }
  1325. public UnwovenClassFile[] getClassFilesFor(LazyClassGen clazz) {
  1326. List<UnwovenClassFile.ChildClass> childClasses = clazz.getChildClasses(world);
  1327. UnwovenClassFile[] ret = new UnwovenClassFile[1 + childClasses.size()];
  1328. ret[0] = new UnwovenClassFile(clazz.getFileName(), clazz.getClassName(), clazz.getJavaClassBytesIncludingReweavable(world));
  1329. int index = 1;
  1330. for (UnwovenClassFile.ChildClass element : childClasses) {
  1331. UnwovenClassFile childClass = new UnwovenClassFile(clazz.getFileName() + "$" + element.name, element.bytes);
  1332. ret[index++] = childClass;
  1333. }
  1334. return ret;
  1335. }
  1336. /**
  1337. * Weaves new parents and annotations onto a type ("declare parents" and "declare @type")
  1338. *
  1339. * Algorithm: 1. First pass, do parents then do annotations. During this pass record: - any parent mungers that don't match but
  1340. * have a non-wild annotation type pattern - any annotation mungers that don't match 2. Multiple subsequent passes which go over
  1341. * the munger lists constructed in the first pass, repeatedly applying them until nothing changes. FIXME asc confirm that
  1342. * algorithm is optimal ??
  1343. */
  1344. public void weaveParentTypeMungers(ResolvedType onType) {
  1345. if (onType.isRawType() || onType.isParameterizedType()) {
  1346. onType = onType.getGenericType();
  1347. }
  1348. onType.clearInterTypeMungers();
  1349. List<DeclareParents> decpToRepeat = new ArrayList<>();
  1350. boolean aParentChangeOccurred = false;
  1351. boolean anAnnotationChangeOccurred = false;
  1352. // First pass - apply all decp mungers
  1353. for (DeclareParents decp : declareParentsList) {
  1354. boolean typeChanged = applyDeclareParents(decp, onType);
  1355. if (typeChanged) {
  1356. aParentChangeOccurred = true;
  1357. } else {
  1358. decpToRepeat.add(decp);
  1359. }
  1360. }
  1361. // Still first pass - apply all dec @type mungers
  1362. for (DeclareAnnotation decA : xcutSet.getDeclareAnnotationOnTypes()) {
  1363. boolean typeChanged = applyDeclareAtType(decA, onType, true);
  1364. if (typeChanged) {
  1365. anAnnotationChangeOccurred = true;
  1366. }
  1367. }
  1368. while ((aParentChangeOccurred || anAnnotationChangeOccurred) && !decpToRepeat.isEmpty()) {
  1369. anAnnotationChangeOccurred = aParentChangeOccurred = false;
  1370. List<DeclareParents> decpToRepeatNextTime = new ArrayList<>();
  1371. for (DeclareParents decp : decpToRepeat) {
  1372. boolean typeChanged = applyDeclareParents(decp, onType);
  1373. if (typeChanged) {
  1374. aParentChangeOccurred = true;
  1375. } else {
  1376. decpToRepeatNextTime.add(decp);
  1377. }
  1378. }
  1379. for (DeclareAnnotation decA : xcutSet.getDeclareAnnotationOnTypes()) {
  1380. boolean typeChanged = applyDeclareAtType(decA, onType, false);
  1381. if (typeChanged) {
  1382. anAnnotationChangeOccurred = true;
  1383. }
  1384. }
  1385. decpToRepeat = decpToRepeatNextTime;
  1386. }
  1387. }
  1388. /**
  1389. * Apply a declare @type - return true if we change the type
  1390. */
  1391. private boolean applyDeclareAtType(DeclareAnnotation decA, ResolvedType onType, boolean reportProblems) {
  1392. boolean didSomething = false;
  1393. if (decA.matches(onType)) {
  1394. AnnotationAJ theAnnotation = decA.getAnnotation();
  1395. // can be null for broken code!
  1396. if (theAnnotation == null) {
  1397. return false;
  1398. }
  1399. if (onType.hasAnnotation(theAnnotation.getType())) {
  1400. // Could put out a lint here for an already annotated type ...
  1401. // if (reportProblems) {
  1402. // world.getLint().elementAlreadyAnnotated.signal(
  1403. // new
  1404. // String[]{onType.toString(),decA.getAnnotationTypeX().toString
  1405. // ()},
  1406. // onType.getSourceLocation(),new
  1407. // ISourceLocation[]{decA.getSourceLocation()});
  1408. // }
  1409. return false;
  1410. }
  1411. AnnotationAJ annoX = decA.getAnnotation();
  1412. // check the annotation is suitable for the target
  1413. boolean problemReported = verifyTargetIsOK(decA, onType, annoX, reportProblems);
  1414. if (!problemReported) {
  1415. AsmRelationshipProvider.addDeclareAnnotationRelationship(world.getModelAsAsmManager(), decA.getSourceLocation(),
  1416. onType.getSourceLocation(), false);
  1417. // TAG: WeavingMessage
  1418. if (!getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) {
  1419. getWorld().getMessageHandler().handleMessage(
  1420. WeaveMessage.constructWeavingMessage(
  1421. WeaveMessage.WEAVEMESSAGE_ANNOTATES,
  1422. new String[] { onType.toString(), Utility.beautifyLocation(onType.getSourceLocation()),
  1423. decA.getAnnotationString(), "type", decA.getAspect().toString(),
  1424. Utility.beautifyLocation(decA.getSourceLocation()) }));
  1425. }
  1426. didSomething = true;
  1427. ResolvedTypeMunger newAnnotationTM = new AnnotationOnTypeMunger(annoX);
  1428. newAnnotationTM.setSourceLocation(decA.getSourceLocation());
  1429. onType.addInterTypeMunger(new BcelTypeMunger(newAnnotationTM, decA.getAspect().resolve(world)), false);
  1430. decA.copyAnnotationTo(onType);
  1431. }
  1432. }
  1433. return didSomething;
  1434. }
  1435. /**
  1436. * Checks for an @target() on the annotation and if found ensures it allows the annotation to be attached to the target type
  1437. * that matched.
  1438. */
  1439. private boolean verifyTargetIsOK(DeclareAnnotation decA, ResolvedType onType, AnnotationAJ annoX, boolean outputProblems) {
  1440. boolean problemReported = false;
  1441. if (annoX.specifiesTarget()) {
  1442. if ((onType.isAnnotation() && !annoX.allowedOnAnnotationType()) || (!annoX.allowedOnRegularType())) {
  1443. if (outputProblems) {
  1444. if (decA.isExactPattern()) {
  1445. world.getMessageHandler().handleMessage(
  1446. MessageUtil.error(
  1447. WeaverMessages.format(WeaverMessages.INCORRECT_TARGET_FOR_DECLARE_ANNOTATION,
  1448. onType.getName(), annoX.getTypeName(), annoX.getValidTargets()),
  1449. decA.getSourceLocation()));
  1450. } else {
  1451. if (world.getLint().invalidTargetForAnnotation.isEnabled()) {
  1452. world.getLint().invalidTargetForAnnotation.signal(new String[] { onType.getName(), annoX.getTypeName(),
  1453. annoX.getValidTargets() }, decA.getSourceLocation(),
  1454. new ISourceLocation[] { onType.getSourceLocation() });
  1455. }
  1456. }
  1457. }
  1458. problemReported = true;
  1459. }
  1460. }
  1461. return problemReported;
  1462. }
  1463. /**
  1464. * Apply a single declare parents - return true if we change the type
  1465. */
  1466. private boolean applyDeclareParents(DeclareParents p, ResolvedType onType) {
  1467. boolean didSomething = false;
  1468. List<ResolvedType> newParents = p.findMatchingNewParents(onType, true);
  1469. if (!newParents.isEmpty()) {
  1470. didSomething = true;
  1471. BcelWorld.getBcelObjectType(onType);
  1472. // System.err.println("need to do declare parents for: " + onType);
  1473. for (ResolvedType newParent : newParents) {
  1474. // We set it here so that the imminent matching for ITDs can
  1475. // succeed - we still haven't done the necessary changes to the class file
  1476. // itself (like transform super calls) - that is done in
  1477. // BcelTypeMunger.mungeNewParent()
  1478. // classType.addParent(newParent);
  1479. onType.addParent(newParent);
  1480. NewParentTypeMunger newParentMunger = new NewParentTypeMunger(newParent, p.getDeclaringType());
  1481. if (p.isMixin()) {
  1482. newParentMunger.setIsMixin(true);
  1483. }
  1484. newParentMunger.setSourceLocation(p.getSourceLocation());
  1485. onType.addInterTypeMunger(new BcelTypeMunger(newParentMunger, xcutSet.findAspectDeclaringParents(p)), false);
  1486. }
  1487. }
  1488. return didSomething;
  1489. }
  1490. public void weaveNormalTypeMungers(ResolvedType onType) {
  1491. ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_TYPE_MUNGERS,
  1492. onType.getName());
  1493. if (onType.isRawType() || onType.isParameterizedType()) {
  1494. onType = onType.getGenericType();
  1495. }
  1496. for (ConcreteTypeMunger m : typeMungerList) {
  1497. if (!m.isLateMunger() && m.matches(onType)) {
  1498. onType.addInterTypeMunger(m, false);
  1499. }
  1500. }
  1501. CompilationAndWeavingContext.leavingPhase(tok);
  1502. }
  1503. // exposed for ClassLoader dynamic weaving
  1504. public LazyClassGen weaveWithoutDump(UnwovenClassFile classFile, BcelObjectType classType) throws IOException {
  1505. return weave(classFile, classType, false);
  1506. }
  1507. // FOR TESTING
  1508. LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType) throws IOException {
  1509. LazyClassGen ret = weave(classFile, classType, true);
  1510. return ret;
  1511. }
  1512. private LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType, boolean dump) throws IOException {
  1513. try {
  1514. if (classType.isSynthetic()) { // Don't touch synthetic classes
  1515. if (dump) {
  1516. dumpUnchanged(classFile);
  1517. }
  1518. return null;
  1519. }
  1520. ReferenceType resolvedClassType = classType.getResolvedTypeX();
  1521. if (world.isXmlConfigured() && world.getXmlConfiguration().excludesType(resolvedClassType)) {
  1522. if (!world.getMessageHandler().isIgnoring(IMessage.INFO)) {
  1523. world.getMessageHandler().handleMessage(
  1524. MessageUtil.info("Type '" + resolvedClassType.getName()
  1525. + "' not woven due to exclusion via XML weaver exclude section"));
  1526. }
  1527. if (dump) {
  1528. dumpUnchanged(classFile);
  1529. }
  1530. return null;
  1531. }
  1532. List<ShadowMunger> shadowMungers = fastMatch(shadowMungerList, resolvedClassType);
  1533. List<ConcreteTypeMunger> typeMungers = classType.getResolvedTypeX().getInterTypeMungers();
  1534. resolvedClassType.checkInterTypeMungers();
  1535. // Decide if we need to do actual weaving for this class
  1536. boolean mightNeedToWeave = shadowMungers.size() > 0 || typeMungers.size() > 0 || classType.isAspect()
  1537. || world.getDeclareAnnotationOnMethods().size() > 0 || world.getDeclareAnnotationOnFields().size() > 0;
  1538. // May need bridge methods if on 1.5 and something in our hierarchy is
  1539. // affected by ITDs
  1540. boolean mightNeedBridgeMethods = world.isInJava5Mode() && !classType.isInterface()
  1541. && resolvedClassType.getInterTypeMungersIncludingSupers().size() > 0;
  1542. LazyClassGen clazz = null;
  1543. if (mightNeedToWeave || mightNeedBridgeMethods) {
  1544. clazz = classType.getLazyClassGen();
  1545. // System.err.println("got lazy gen: " + clazz + ", " +
  1546. // clazz.getWeaverState());
  1547. try {
  1548. boolean isChanged = false;
  1549. if (mightNeedToWeave) {
  1550. isChanged = BcelClassWeaver.weave(world, clazz, shadowMungers, typeMungers, lateTypeMungerList,
  1551. inReweavableMode);
  1552. }
  1553. checkDeclareTypeErrorOrWarning(world, classType);
  1554. if (mightNeedBridgeMethods) {
  1555. isChanged = BcelClassWeaver.calculateAnyRequiredBridgeMethods(world, clazz) || isChanged;
  1556. }
  1557. if (isChanged) {
  1558. if (dump) {
  1559. dump(classFile, clazz);
  1560. }
  1561. return clazz;
  1562. }
  1563. } catch (RuntimeException re) {
  1564. String classDebugInfo = null;
  1565. try {
  1566. classDebugInfo = clazz.toLongString();
  1567. } catch (Throwable e) {
  1568. new RuntimeException("Crashed whilst crashing with this exception: " + e, e).printStackTrace();
  1569. // recover from crash whilst producing debug string
  1570. classDebugInfo = clazz.getClassName();
  1571. }
  1572. String messageText = "trouble in: \n" + classDebugInfo;
  1573. getWorld().getMessageHandler().handleMessage(new Message(messageText, IMessage.ABORT, re, null));
  1574. } catch (Error re) {
  1575. String classDebugInfo = null;
  1576. try {
  1577. classDebugInfo = clazz.toLongString();
  1578. } catch (OutOfMemoryError oome) {
  1579. System.err.println("Ran out of memory creating debug info for an error");
  1580. re.printStackTrace(System.err);
  1581. // recover from crash whilst producing debug string
  1582. classDebugInfo = clazz.getClassName();
  1583. } catch (Throwable e) {
  1584. // recover from crash whilst producing debug string
  1585. classDebugInfo = clazz.getClassName();
  1586. }
  1587. String messageText = "trouble in: \n" + classDebugInfo;
  1588. getWorld().getMessageHandler().handleMessage(new Message(messageText, IMessage.ABORT, re, null));
  1589. }
  1590. } else {
  1591. checkDeclareTypeErrorOrWarning(world, classType);
  1592. }
  1593. // this is very odd return behavior trying to keep everyone happy
  1594. // can we remove it from the model now? we know it contains no relationship endpoints...
  1595. AsmManager model = world.getModelAsAsmManager();
  1596. if (world.isMinimalModel() && model != null && !classType.isAspect()) {
  1597. AspectJElementHierarchy hierarchy = (AspectJElementHierarchy) model.getHierarchy();
  1598. String pkgname = classType.getResolvedTypeX().getPackageName();
  1599. String tname = classType.getResolvedTypeX().getSimpleBaseName();
  1600. IProgramElement typeElement = hierarchy.findElementForType(pkgname, tname);
  1601. if (typeElement != null && hasInnerType(typeElement)) {
  1602. // Cannot remove it right now (has inner type), schedule it
  1603. // for possible deletion later if all inner types are
  1604. // removed
  1605. candidatesForRemoval.add(typeElement);
  1606. }
  1607. if (typeElement != null && !hasInnerType(typeElement)) {
  1608. IProgramElement parent = typeElement.getParent();
  1609. // parent may have children: PACKAGE DECL, IMPORT-REFERENCE, TYPE_DECL
  1610. if (parent != null) {
  1611. // if it was the only type we should probably remove
  1612. // the others too.
  1613. parent.removeChild(typeElement);
  1614. if (parent.getKind().isSourceFile()) {
  1615. removeSourceFileIfNoMoreTypeDeclarationsInside(hierarchy, typeElement, parent);
  1616. } else {
  1617. hierarchy.forget(null, typeElement);
  1618. // At this point, the child has been removed. We
  1619. // should now check if the parent is in our
  1620. // 'candidatesForRemoval' set. If it is then that
  1621. // means we were going to remove it but it had a
  1622. // child. Now we can check if it still has a child -
  1623. // if it doesn't it can also be removed!
  1624. walkUpRemovingEmptyTypesAndPossiblyEmptySourceFile(hierarchy, tname, parent);
  1625. }
  1626. }
  1627. }
  1628. }
  1629. if (dump) {
  1630. dumpUnchanged(classFile);
  1631. return clazz;
  1632. } else {
  1633. // ATAJ: the class was not weaved, but since it gets there early it
  1634. // may have new generated inner classes
  1635. // attached to it to support LTW perX aspectOf support (see
  1636. // BcelPerClauseAspectAdder)
  1637. // that aggressively defines the inner <aspect>$mayHaveAspect
  1638. // interface.
  1639. if (clazz != null && !clazz.getChildClasses(world).isEmpty()) {
  1640. return clazz;
  1641. }
  1642. return null;
  1643. }
  1644. } finally {
  1645. world.demote();
  1646. }
  1647. }
  1648. private void walkUpRemovingEmptyTypesAndPossiblyEmptySourceFile(AspectJElementHierarchy hierarchy, String tname,
  1649. IProgramElement typeThatHasChildRemoved) {
  1650. // typeThatHasChildRemoved might be a source file, type or a method/ctor
  1651. // - for a method/ctor find the type/sourcefile
  1652. while (typeThatHasChildRemoved != null
  1653. && !(typeThatHasChildRemoved.getKind().isType() || typeThatHasChildRemoved.getKind().isSourceFile())) {
  1654. // this will take us 'up' through methods that contain anonymous
  1655. // inner classes
  1656. typeThatHasChildRemoved = typeThatHasChildRemoved.getParent();
  1657. }
  1658. // now typeThatHasChildRemoved points to the type or sourcefile that has
  1659. // had something removed
  1660. if (candidatesForRemoval.contains(typeThatHasChildRemoved) && !hasInnerType(typeThatHasChildRemoved)) {
  1661. // now we can get rid of it
  1662. IProgramElement parent = typeThatHasChildRemoved.getParent();
  1663. if (parent != null) {
  1664. parent.removeChild(typeThatHasChildRemoved);
  1665. candidatesForRemoval.remove(typeThatHasChildRemoved);
  1666. if (parent.getKind().isSourceFile()) {
  1667. removeSourceFileIfNoMoreTypeDeclarationsInside(hierarchy, typeThatHasChildRemoved, parent);
  1668. // System.out.println("Removed on second pass: " +
  1669. // typeThatHasChildRemoved.getName());
  1670. } else {
  1671. // System.out.println("On later pass, parent of type " +
  1672. // typeThatHasChildRemoved.getName()
  1673. // + " was found not to be a sourcefile, recursing up...");
  1674. walkUpRemovingEmptyTypesAndPossiblyEmptySourceFile(hierarchy, tname, parent);
  1675. }
  1676. }
  1677. }
  1678. }
  1679. private void removeSourceFileIfNoMoreTypeDeclarationsInside(AspectJElementHierarchy hierarchy, IProgramElement typeElement,
  1680. IProgramElement sourceFileNode) {
  1681. IProgramElement compilationUnit = sourceFileNode;
  1682. boolean anyOtherTypeDeclarations = false;
  1683. for (IProgramElement child : compilationUnit.getChildren()) {
  1684. IProgramElement.Kind k = child.getKind();
  1685. if (k.isType()) {
  1686. anyOtherTypeDeclarations = true;
  1687. break;
  1688. }
  1689. }
  1690. // If the compilation unit node contained no
  1691. // other types, there is no need to keep it
  1692. if (!anyOtherTypeDeclarations) {
  1693. IProgramElement cuParent = compilationUnit.getParent();
  1694. if (cuParent != null) {
  1695. compilationUnit.setParent(null);
  1696. cuParent.removeChild(compilationUnit);
  1697. }
  1698. // need to update some caches and structures too?
  1699. hierarchy.forget(sourceFileNode, typeElement);
  1700. } else {
  1701. hierarchy.forget(null, typeElement);
  1702. }
  1703. }
  1704. // ---- writing
  1705. // TODO could be smarter - really only matters if inner type has been woven, but there is a chance we haven't woven it *yet*
  1706. private boolean hasInnerType(IProgramElement typeNode) {
  1707. for (IProgramElement child : typeNode.getChildren()) {
  1708. IProgramElement.Kind kind = child.getKind();
  1709. if (kind.isType()) {
  1710. return true;
  1711. }
  1712. // if (kind == IProgramElement.Kind.ASPECT) {
  1713. // return true;
  1714. // }
  1715. if (kind.isType() || kind == IProgramElement.Kind.METHOD || kind == IProgramElement.Kind.CONSTRUCTOR) {
  1716. boolean b = hasInnerType(child);
  1717. if (b) {
  1718. return b;
  1719. }
  1720. }
  1721. }
  1722. return false;
  1723. }
  1724. private void checkDeclareTypeErrorOrWarning(BcelWorld world2, BcelObjectType classType) {
  1725. List<DeclareTypeErrorOrWarning> dteows = world.getDeclareTypeEows();
  1726. for (DeclareTypeErrorOrWarning dteow : dteows) {
  1727. if (dteow.getTypePattern().matchesStatically(classType.getResolvedTypeX())) {
  1728. if (dteow.isError()) {
  1729. world.getMessageHandler().handleMessage(
  1730. MessageUtil.error(dteow.getMessage(), classType.getResolvedTypeX().getSourceLocation()));
  1731. } else {
  1732. world.getMessageHandler().handleMessage(
  1733. MessageUtil.warn(dteow.getMessage(), classType.getResolvedTypeX().getSourceLocation()));
  1734. }
  1735. }
  1736. }
  1737. }
  1738. private void dumpUnchanged(UnwovenClassFile classFile) throws IOException {
  1739. if (zipOutputStream != null) {
  1740. writeZipEntry(getEntryName(classFile.getJavaClass().getClassName()), classFile.getBytes());
  1741. } else {
  1742. classFile.writeUnchangedBytes();
  1743. }
  1744. }
  1745. private String getEntryName(String className) {
  1746. // XXX what does bcel's getClassName do for inner names
  1747. return className.replace('.', '/') + ".class";
  1748. }
  1749. private void dump(UnwovenClassFile classFile, LazyClassGen clazz) throws IOException {
  1750. if (zipOutputStream != null) {
  1751. String mainClassName = classFile.getJavaClass().getClassName();
  1752. writeZipEntry(getEntryName(mainClassName), clazz.getJavaClass(world).getBytes());
  1753. List<UnwovenClassFile.ChildClass> childClasses = clazz.getChildClasses(world);
  1754. if (!childClasses.isEmpty()) {
  1755. for (UnwovenClassFile.ChildClass c : childClasses) {
  1756. writeZipEntry(getEntryName(mainClassName + "$" + c.name), c.bytes);
  1757. }
  1758. }
  1759. } else {
  1760. classFile.writeWovenBytes(clazz.getJavaClass(world).getBytes(), clazz.getChildClasses(world));
  1761. }
  1762. }
  1763. private void writeZipEntry(String name, byte[] bytes) throws IOException {
  1764. ZipEntry newEntry = new ZipEntry(name); // ??? get compression scheme
  1765. // right
  1766. zipOutputStream.putNextEntry(newEntry);
  1767. zipOutputStream.write(bytes);
  1768. zipOutputStream.closeEntry();
  1769. }
  1770. /**
  1771. * Perform a fast match of the specified list of shadowmungers against the specified type. A subset of those that might match is
  1772. * returned.
  1773. *
  1774. * @param list list of all shadow mungers that might match
  1775. * @param type the target type
  1776. * @return a list of shadow mungers that might match with those that cannot (according to fast match rules) removed
  1777. */
  1778. private List<ShadowMunger> fastMatch(List<ShadowMunger> list, ResolvedType type) {
  1779. if (list == null) {
  1780. return Collections.emptyList();
  1781. }
  1782. boolean isOverweaving = world.isOverWeaving();
  1783. WeaverStateInfo typeWeaverState = (isOverweaving ? type.getWeaverState() : null);
  1784. // here we do the coarsest grained fast match with no kind constraints
  1785. // this will remove all obvious non-matches and see if we need to do any
  1786. // weaving
  1787. FastMatchInfo info = new FastMatchInfo(type, null, world);
  1788. List<ShadowMunger> result = new ArrayList<>();
  1789. if (world.areInfoMessagesEnabled() && world.isTimingEnabled()) {
  1790. for (ShadowMunger munger : list) {
  1791. if (typeWeaverState != null) { // will only be null if overweaving is ON and there is weaverstate
  1792. ResolvedType declaringAspect = munger.getDeclaringType();
  1793. if (typeWeaverState.isAspectAlreadyApplied(declaringAspect)) {
  1794. continue;
  1795. }
  1796. }
  1797. Pointcut pointcut = munger.getPointcut();
  1798. long starttime = System.nanoTime();
  1799. FuzzyBoolean fb = pointcut.fastMatch(info);
  1800. long endtime = System.nanoTime();
  1801. world.recordFastMatch(pointcut, endtime - starttime);
  1802. if (fb.maybeTrue()) {
  1803. result.add(munger);
  1804. }
  1805. }
  1806. } else {
  1807. for (ShadowMunger munger : list) {
  1808. if (typeWeaverState != null) { // will only be null if overweaving is ON and there is weaverstate
  1809. ResolvedType declaringAspect = munger.getConcreteAspect();// getDeclaringType();
  1810. if (typeWeaverState.isAspectAlreadyApplied(declaringAspect)) {
  1811. continue;
  1812. }
  1813. }
  1814. Pointcut pointcut = munger.getPointcut();
  1815. FuzzyBoolean fb = pointcut.fastMatch(info);
  1816. if (fb.maybeTrue()) {
  1817. result.add(munger);
  1818. }
  1819. }
  1820. }
  1821. return result;
  1822. }
  1823. public void setReweavableMode(boolean xNotReweavable) {
  1824. inReweavableMode = !xNotReweavable;
  1825. WeaverStateInfo.setReweavableModeDefaults(!xNotReweavable, false, true);
  1826. }
  1827. public boolean isReweavable() {
  1828. return inReweavableMode;
  1829. }
  1830. public World getWorld() {
  1831. return world;
  1832. }
  1833. public void tidyUp() {
  1834. if (trace.isTraceEnabled()) {
  1835. trace.enter("tidyUp", this);
  1836. }
  1837. shadowMungerList = null; // setup by prepareForWeave
  1838. typeMungerList = null; // setup by prepareForWeave
  1839. lateTypeMungerList = null; // setup by prepareForWeave
  1840. declareParentsList = null; // setup by prepareForWeave
  1841. if (trace.isTraceEnabled()) {
  1842. trace.exit("tidyUp");
  1843. }
  1844. }
  1845. public void write(CompressingDataOutputStream dos) throws IOException {
  1846. xcutSet.write(dos);
  1847. }
  1848. // only called for testing
  1849. public void setShadowMungers(List<ShadowMunger> shadowMungers) {
  1850. shadowMungerList = shadowMungers;
  1851. }
  1852. }