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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736
  1. /* *******************************************************************
  2. * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
  3. * All rights reserved.
  4. * This program and the accompanying materials are made available
  5. * under the terms of the Eclipse Public License v1.0
  6. * which accompanies this distribution and is available at
  7. * http://www.eclipse.org/legal/epl-v10.html
  8. *
  9. * Contributors:
  10. * PARC initial implementation
  11. * Alexandre Vasseur support for @AJ aspects
  12. * ******************************************************************/
  13. package org.aspectj.weaver.bcel;
  14. import java.io.ByteArrayInputStream;
  15. import java.io.File;
  16. import java.io.FileFilter;
  17. import java.io.FileInputStream;
  18. import java.io.FileNotFoundException;
  19. import java.io.IOException;
  20. import java.io.InputStream;
  21. import java.io.OutputStream;
  22. import java.util.ArrayList;
  23. import java.util.Collection;
  24. import java.util.Collections;
  25. import java.util.Comparator;
  26. import java.util.Enumeration;
  27. import java.util.HashMap;
  28. import java.util.HashSet;
  29. import java.util.Iterator;
  30. import java.util.List;
  31. import java.util.Map;
  32. import java.util.Set;
  33. import java.util.jar.Attributes;
  34. import java.util.jar.JarEntry;
  35. import java.util.jar.JarFile;
  36. import java.util.jar.Manifest;
  37. import java.util.jar.Attributes.Name;
  38. import java.util.zip.ZipEntry;
  39. import java.util.zip.ZipInputStream;
  40. import java.util.zip.ZipOutputStream;
  41. import org.aspectj.apache.bcel.classfile.ClassParser;
  42. import org.aspectj.apache.bcel.classfile.JavaClass;
  43. import org.aspectj.asm.AsmManager;
  44. import org.aspectj.bridge.IMessage;
  45. import org.aspectj.bridge.IProgressListener;
  46. import org.aspectj.bridge.ISourceLocation;
  47. import org.aspectj.bridge.Message;
  48. import org.aspectj.bridge.MessageUtil;
  49. import org.aspectj.bridge.SourceLocation;
  50. import org.aspectj.bridge.WeaveMessage;
  51. import org.aspectj.bridge.context.CompilationAndWeavingContext;
  52. import org.aspectj.bridge.context.ContextToken;
  53. import org.aspectj.util.FileUtil;
  54. import org.aspectj.util.FuzzyBoolean;
  55. import org.aspectj.weaver.Advice;
  56. import org.aspectj.weaver.AnnotationOnTypeMunger;
  57. import org.aspectj.weaver.AnnotationX;
  58. import org.aspectj.weaver.AsmRelationshipProvider;
  59. import org.aspectj.weaver.BCException;
  60. import org.aspectj.weaver.ConcreteTypeMunger;
  61. import org.aspectj.weaver.CrosscuttingMembersSet;
  62. import org.aspectj.weaver.IClassFileProvider;
  63. import org.aspectj.weaver.IWeaveRequestor;
  64. import org.aspectj.weaver.IWeaver;
  65. import org.aspectj.weaver.NewParentTypeMunger;
  66. import org.aspectj.weaver.ReferenceType;
  67. import org.aspectj.weaver.ReferenceTypeDelegate;
  68. import org.aspectj.weaver.ResolvedTypeMunger;
  69. import org.aspectj.weaver.ResolvedType;
  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.WeaverMetrics;
  75. import org.aspectj.weaver.WeaverStateInfo;
  76. import org.aspectj.weaver.World;
  77. import org.aspectj.weaver.patterns.AndPointcut;
  78. import org.aspectj.weaver.patterns.BindingAnnotationTypePattern;
  79. import org.aspectj.weaver.patterns.BindingTypePattern;
  80. import org.aspectj.weaver.patterns.CflowPointcut;
  81. import org.aspectj.weaver.patterns.ConcreteCflowPointcut;
  82. import org.aspectj.weaver.patterns.DeclareAnnotation;
  83. import org.aspectj.weaver.patterns.DeclareParents;
  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. public class BcelWeaver implements IWeaver {
  96. private BcelWorld world;
  97. private CrosscuttingMembersSet xcutSet;
  98. private IProgressListener progressListener = null;
  99. private double progressMade;
  100. private double progressPerClassFile;
  101. private boolean inReweavableMode = false;
  102. private static Trace trace = TraceFactory.getTraceFactory().getTrace(BcelWeaver.class);
  103. public BcelWeaver(BcelWorld world) {
  104. super();
  105. if (trace.isTraceEnabled()) trace.enter("<init>",this,world);
  106. WeaverMetrics.reset();
  107. this.world = world;
  108. this.xcutSet = world.getCrosscuttingMembersSet();
  109. if (trace.isTraceEnabled()) trace.exit("<init>");
  110. }
  111. public BcelWeaver() {
  112. this(new BcelWorld());
  113. }
  114. // ---- fields
  115. // private Map sourceJavaClasses = new HashMap(); /* String -> UnwovenClassFile */
  116. private List addedClasses = new ArrayList(); /* List<UnovenClassFile> */
  117. private List deletedTypenames = new ArrayList(); /* List<String> */
  118. // private Map resources = new HashMap(); /* String -> UnwovenClassFile */
  119. private Manifest manifest = null;
  120. private boolean needToReweaveWorld = false;
  121. private boolean isBatchWeave = true;
  122. private List shadowMungerList = null; // setup by prepareForWeave
  123. private List typeMungerList = null; // setup by prepareForWeave
  124. private List lateTypeMungerList = null; // setup by prepareForWeave
  125. private List declareParentsList = null; // setup by prepareForWeave
  126. private ZipOutputStream zipOutputStream;
  127. // ----
  128. // only called for testing
  129. public void setShadowMungers(List l) {
  130. shadowMungerList = l;
  131. }
  132. /**
  133. * Add the given aspect to the weaver.
  134. * The type is resolved to support DOT for static inner classes as well as DOLLAR
  135. *
  136. * @param aspectName
  137. * @return aspect
  138. */
  139. public ResolvedType addLibraryAspect(String aspectName) {
  140. if (trace.isTraceEnabled()) trace.enter("addLibraryAspect",this,aspectName);
  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. classType.setJavaClass(Utility.makeJavaClass(classType.getJavaClass().getFileName(), wsi.getUnwovenClassFileData(classType.getJavaClass().getBytes())));
  170. }
  171. //TODO AV - happens to reach that a lot of time: for each type flagged reweavable X for each aspect in the weaverstate
  172. //=> mainly for nothing for LTW - pbly for something in incremental build...
  173. xcutSet.addOrReplaceAspect(type);
  174. if (trace.isTraceEnabled()) trace.exit("addLibraryAspect",type);
  175. return type;
  176. } else {
  177. // FIXME AV - better warning upon no such aspect from aop.xml
  178. RuntimeException ex = new RuntimeException("Cannot register non aspect: " + type.getName() + " , " + aspectName);
  179. if (trace.isTraceEnabled()) trace.exit("addLibraryAspect",ex);
  180. throw ex;
  181. }
  182. }
  183. /**
  184. *
  185. * @param inFile File path to class directory or zip/jar class archive
  186. * @throws IOException
  187. */
  188. public void addLibraryJarFile(File inFile) throws IOException {
  189. List addedAspects = null;
  190. if (inFile.isDirectory()) {
  191. addedAspects = addAspectsFromDirectory(inFile);
  192. } else {
  193. addedAspects = addAspectsFromJarFile(inFile);
  194. }
  195. for (Iterator i = addedAspects.iterator(); i.hasNext();) {
  196. ResolvedType aspectX = (ResolvedType) i.next();
  197. xcutSet.addOrReplaceAspect(aspectX);
  198. }
  199. }
  200. private List addAspectsFromJarFile(File inFile) throws FileNotFoundException, IOException {
  201. ZipInputStream inStream = new ZipInputStream(new FileInputStream(inFile)); //??? buffered
  202. List addedAspects = new ArrayList();
  203. while (true) {
  204. ZipEntry entry = inStream.getNextEntry();
  205. if (entry == null) break;
  206. if (entry.isDirectory() || !entry.getName().endsWith(".class")) {
  207. continue;
  208. }
  209. // FIXME ASC performance? of this alternative soln.
  210. ClassParser parser = new ClassParser(new ByteArrayInputStream(FileUtil.readAsByteArray(inStream)), entry.getName());
  211. JavaClass jc = parser.parse();
  212. inStream.closeEntry();
  213. ResolvedType type = world.addSourceObjectType(jc).getResolvedTypeX();
  214. if (type.isAspect()) {
  215. addedAspects.add(type);
  216. }
  217. }
  218. inStream.close();
  219. return addedAspects;
  220. }
  221. private List addAspectsFromDirectory(File dir) throws FileNotFoundException, IOException{
  222. List addedAspects = new ArrayList();
  223. File[] classFiles = FileUtil.listFiles(dir,new FileFilter(){
  224. public boolean accept(File pathname) {
  225. return pathname.getName().endsWith(".class");
  226. }
  227. });
  228. for (int i = 0; i < classFiles.length; i++) {
  229. FileInputStream fis = new FileInputStream(classFiles[i]);
  230. byte[] bytes = FileUtil.readAsByteArray(fis);
  231. addIfAspect(bytes,classFiles[i].getAbsolutePath(),addedAspects);
  232. }
  233. return addedAspects;
  234. }
  235. private void addIfAspect(byte[] bytes, String name, List toList) throws IOException {
  236. ClassParser parser = new ClassParser(new ByteArrayInputStream(bytes),name);
  237. JavaClass jc = parser.parse();
  238. ResolvedType type = world.addSourceObjectType(jc).getResolvedTypeX();
  239. if (type.isAspect()) {
  240. toList.add(type);
  241. }
  242. }
  243. // // The ANT copy task should be used to copy resources across.
  244. // private final static boolean CopyResourcesFromInpathDirectoriesToOutput=false;
  245. /**
  246. * Add any .class files in the directory to the outdir. Anything other than .class files in
  247. * the directory (or its subdirectories) are considered resources and are also copied.
  248. *
  249. */
  250. public List addDirectoryContents(File inFile,File outDir) throws IOException {
  251. List addedClassFiles = new ArrayList();
  252. // Get a list of all files (i.e. everything that isnt a directory)
  253. File[] files = FileUtil.listFiles(inFile,new FileFilter() {
  254. public boolean accept(File f) {
  255. boolean accept = !f.isDirectory();
  256. return accept;
  257. }
  258. });
  259. // For each file, add it either as a real .class file or as a resource
  260. for (int i = 0; i < files.length; i++) {
  261. addedClassFiles.add(addClassFile(files[i],inFile,outDir));
  262. }
  263. return addedClassFiles;
  264. }
  265. /** Adds all class files in the jar
  266. */
  267. public List addJarFile(File inFile, File outDir, boolean canBeDirectory){
  268. // System.err.println("? addJarFile(" + inFile + ", " + outDir + ")");
  269. List addedClassFiles = new ArrayList();
  270. needToReweaveWorld = true;
  271. JarFile inJar = null;
  272. try {
  273. // Is this a directory we are looking at?
  274. if (inFile.isDirectory() && canBeDirectory) {
  275. addedClassFiles.addAll(addDirectoryContents(inFile,outDir));
  276. } else {
  277. inJar = new JarFile(inFile);
  278. addManifest(inJar.getManifest());
  279. Enumeration entries = inJar.entries();
  280. while (entries.hasMoreElements()) {
  281. JarEntry entry = (JarEntry)entries.nextElement();
  282. InputStream inStream = inJar.getInputStream(entry);
  283. byte[] bytes = FileUtil.readAsByteArray(inStream);
  284. String filename = entry.getName();
  285. // System.out.println("? addJarFile() filename='" + filename + "'");
  286. UnwovenClassFile classFile = new UnwovenClassFile(new File(outDir, filename).getAbsolutePath(), bytes);
  287. if (filename.endsWith(".class")) {
  288. this.addClassFile(classFile);
  289. addedClassFiles.add(classFile);
  290. }
  291. // else if (!entry.isDirectory()) {
  292. //
  293. // /* bug-44190 Copy meta-data */
  294. // addResource(filename,classFile);
  295. // }
  296. inStream.close();
  297. }
  298. inJar.close();
  299. }
  300. } catch (FileNotFoundException ex) {
  301. IMessage message = new Message(
  302. "Could not find input jar file " + inFile.getPath() + ", ignoring",
  303. new SourceLocation(inFile,0),
  304. false);
  305. world.getMessageHandler().handleMessage(message);
  306. } catch (IOException ex) {
  307. IMessage message = new Message(
  308. "Could not read input jar file " + inFile.getPath() + "(" + ex.getMessage() + ")",
  309. new SourceLocation(inFile,0),
  310. true);
  311. world.getMessageHandler().handleMessage(message);
  312. } finally {
  313. if (inJar != null) {
  314. try {inJar.close();}
  315. catch (IOException ex) {
  316. IMessage message = new Message(
  317. "Could not close input jar file " + inFile.getPath() + "(" + ex.getMessage() + ")",
  318. new SourceLocation(inFile,0),
  319. true);
  320. world.getMessageHandler().handleMessage(message);
  321. }
  322. }
  323. }
  324. return addedClassFiles;
  325. }
  326. // public void addResource(String name, File inPath, File outDir) throws IOException {
  327. //
  328. // /* Eliminate CVS files. Relative paths use "/" */
  329. // if (!name.startsWith("CVS/") && (-1 == name.indexOf("/CVS/")) && !name.endsWith("/CVS")) {
  330. //// System.err.println("? addResource('" + name + "')");
  331. //// BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(inPath));
  332. //// byte[] bytes = new byte[(int)inPath.length()];
  333. //// inStream.read(bytes);
  334. //// inStream.close();
  335. // byte[] bytes = FileUtil.readAsByteArray(inPath);
  336. // UnwovenClassFile resourceFile = new UnwovenClassFile(new File(outDir, name).getAbsolutePath(), bytes);
  337. // addResource(name,resourceFile);
  338. // }
  339. // }
  340. public boolean needToReweaveWorld() {
  341. return needToReweaveWorld;
  342. }
  343. /** Should be addOrReplace
  344. */
  345. public void addClassFile(UnwovenClassFile classFile) {
  346. addedClasses.add(classFile);
  347. // if (null != sourceJavaClasses.put(classFile.getClassName(), classFile)) {
  348. //// throw new RuntimeException(classFile.getClassName());
  349. // }
  350. world.addSourceObjectType(classFile.getJavaClass());
  351. }
  352. public UnwovenClassFile addClassFile(File classFile, File inPathDir, File outDir) throws IOException {
  353. FileInputStream fis = new FileInputStream(classFile);
  354. byte[] bytes = FileUtil.readAsByteArray(fis);
  355. // String relativePath = files[i].getPath();
  356. // ASSERT: files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath()
  357. // or we are in trouble...
  358. String filename = classFile.getAbsolutePath().substring(
  359. inPathDir.getAbsolutePath().length()+1);
  360. UnwovenClassFile ucf = new UnwovenClassFile(new File(outDir,filename).getAbsolutePath(),bytes);
  361. if (filename.endsWith(".class")) {
  362. // System.err.println("BCELWeaver: processing class from input directory "+classFile);
  363. this.addClassFile(ucf);
  364. }
  365. fis.close();
  366. return ucf;
  367. }
  368. public void deleteClassFile(String typename) {
  369. deletedTypenames.add(typename);
  370. // sourceJavaClasses.remove(typename);
  371. world.deleteSourceObjectType(UnresolvedType.forName(typename));
  372. }
  373. // public void addResource (String name, UnwovenClassFile resourceFile) {
  374. // /* bug-44190 Change error to warning and copy first resource */
  375. // if (!resources.containsKey(name)) {
  376. // resources.put(name, resourceFile);
  377. // }
  378. // else {
  379. // world.showMessage(IMessage.WARNING, "duplicate resource: '" + name + "'",
  380. // null, null);
  381. // }
  382. // }
  383. // ---- weave preparation
  384. public void setIsBatchWeave(boolean b) {
  385. isBatchWeave=b;
  386. }
  387. public void prepareForWeave() {
  388. if (trace.isTraceEnabled()) trace.enter("prepareForWeave",this);
  389. needToReweaveWorld = xcutSet.hasChangedSinceLastReset();
  390. CflowPointcut.clearCaches();
  391. // update mungers
  392. for (Iterator i = addedClasses.iterator(); i.hasNext(); ) {
  393. UnwovenClassFile jc = (UnwovenClassFile)i.next();
  394. String name = jc.getClassName();
  395. ResolvedType type = world.resolve(name);
  396. //System.err.println("added: " + type + " aspect? " + type.isAspect());
  397. if (type.isAspect()) {
  398. needToReweaveWorld |= xcutSet.addOrReplaceAspect(type);
  399. }
  400. }
  401. for (Iterator i = deletedTypenames.iterator(); i.hasNext(); ) {
  402. String name = (String)i.next();
  403. if (xcutSet.deleteAspect(UnresolvedType.forName(name))) needToReweaveWorld = true;
  404. }
  405. shadowMungerList = xcutSet.getShadowMungers();
  406. // world.debug("shadow mungers=" + shadowMungerList);
  407. rewritePointcuts(shadowMungerList);
  408. // Sometimes an error occurs during rewriting pointcuts (for example, if ambiguous bindings
  409. // are detected) - we ought to fail the prepare when this happens because continuing with
  410. // inconsistent pointcuts could lead to problems
  411. typeMungerList = xcutSet.getTypeMungers();
  412. lateTypeMungerList = xcutSet.getLateTypeMungers();
  413. declareParentsList = xcutSet.getDeclareParents();
  414. // The ordering here used to be based on a string compare on toString() for the two mungers -
  415. // that breaks for the @AJ style where advice names aren't programmatically generated. So we
  416. // have changed the sorting to be based on source location in the file - this is reliable, in
  417. // the case of source locations missing, we assume they are 'sorted' - i.e. the order in
  418. // which they were added to the collection is correct, this enables the @AJ stuff to work properly.
  419. // When @AJ processing starts filling in source locations for mungers, this code may need
  420. // a bit of alteration...
  421. Collections.sort(
  422. shadowMungerList,
  423. new Comparator() {
  424. public int compare(Object o1, Object o2) {
  425. ShadowMunger sm1 = (ShadowMunger)o1;
  426. ShadowMunger sm2 = (ShadowMunger)o2;
  427. if (sm1.getSourceLocation()==null) return (sm2.getSourceLocation()==null?0:1);
  428. if (sm2.getSourceLocation()==null) return -1;
  429. return (sm2.getSourceLocation().getOffset()-sm1.getSourceLocation().getOffset());
  430. }
  431. });
  432. if (trace.isTraceEnabled()) trace.exit("prepareForWeave");
  433. }
  434. /*
  435. * Rewrite all of the pointcuts in the world into their most efficient
  436. * form for subsequent matching. Also ensure that if pc1.equals(pc2)
  437. * then pc1 == pc2 (for non-binding pcds) by making references all
  438. * point to the same instance.
  439. * Since pointcuts remember their match decision on the last shadow,
  440. * this makes matching faster when many pointcuts share common elements,
  441. * or even when one single pointcut has one common element (which can
  442. * be a side-effect of DNF rewriting).
  443. */
  444. private void rewritePointcuts(List/*ShadowMunger*/ shadowMungers) {
  445. PointcutRewriter rewriter = new PointcutRewriter();
  446. for (Iterator iter = shadowMungers.iterator(); iter.hasNext();) {
  447. ShadowMunger munger = (ShadowMunger) iter.next();
  448. Pointcut p = munger.getPointcut();
  449. Pointcut newP = rewriter.rewrite(p);
  450. // validateBindings now whilst we still have around the pointcut
  451. // that resembles what the user actually wrote in their program
  452. // text.
  453. if (munger instanceof Advice) {
  454. Advice advice = (Advice) munger;
  455. if (advice.getSignature() != null) {
  456. final int numFormals;
  457. final String names[];
  458. // If the advice is being concretized in a @AJ aspect *and* the advice was declared in
  459. // an @AJ aspect (it could have been inherited from a code style aspect) then
  460. // evaluate the alternative set of formals. pr125699
  461. if (advice.getConcreteAspect().isAnnotationStyleAspect()
  462. && advice.getDeclaringAspect()!=null
  463. && advice.getDeclaringAspect().resolve(world).isAnnotationStyleAspect()) {
  464. numFormals = advice.getBaseParameterCount();
  465. int numArgs = advice.getSignature().getParameterTypes().length;
  466. if (numFormals > 0) {
  467. names = advice.getSignature().getParameterNames(world);
  468. validateBindings(newP,p,numArgs,names);
  469. }
  470. } else {
  471. numFormals = advice.getBaseParameterCount();
  472. if (numFormals > 0) {
  473. names = advice.getBaseParameterNames(world);
  474. validateBindings(newP,p,numFormals,names);
  475. }
  476. }
  477. }
  478. }
  479. munger.setPointcut(newP);
  480. }
  481. // now that we have optimized individual pointcuts, optimize
  482. // across the set of pointcuts....
  483. // Use a map from key based on pc equality, to value based on
  484. // pc identity.
  485. Map/*<Pointcut,Pointcut>*/ pcMap = new HashMap();
  486. for (Iterator iter = shadowMungers.iterator(); iter.hasNext();) {
  487. ShadowMunger munger = (ShadowMunger) iter.next();
  488. Pointcut p = munger.getPointcut();
  489. munger.setPointcut(shareEntriesFromMap(p,pcMap));
  490. }
  491. }
  492. private Pointcut shareEntriesFromMap(Pointcut p,Map pcMap) {
  493. // some things cant be shared...
  494. if (p instanceof NameBindingPointcut) return p;
  495. if (p instanceof IfPointcut) return p;
  496. if (p instanceof ConcreteCflowPointcut) return p;
  497. if (p instanceof AndPointcut) {
  498. AndPointcut apc = (AndPointcut) p;
  499. Pointcut left = shareEntriesFromMap(apc.getLeft(),pcMap);
  500. Pointcut right = shareEntriesFromMap(apc.getRight(),pcMap);
  501. return new AndPointcut(left,right);
  502. } else if (p instanceof OrPointcut) {
  503. OrPointcut opc = (OrPointcut) p;
  504. Pointcut left = shareEntriesFromMap(opc.getLeft(),pcMap);
  505. Pointcut right = shareEntriesFromMap(opc.getRight(),pcMap);
  506. return new OrPointcut(left,right);
  507. } else if (p instanceof NotPointcut) {
  508. NotPointcut npc = (NotPointcut) p;
  509. Pointcut not = shareEntriesFromMap(npc.getNegatedPointcut(),pcMap);
  510. return new NotPointcut(not);
  511. } else {
  512. // primitive pcd
  513. if (pcMap.containsKey(p)) { // based on equality
  514. return (Pointcut) pcMap.get(p); // same instance (identity)
  515. } else {
  516. pcMap.put(p,p);
  517. return p;
  518. }
  519. }
  520. }
  521. // userPointcut is the pointcut that the user wrote in the program text.
  522. // dnfPointcut is the same pointcut rewritten in DNF
  523. // numFormals is the number of formal parameters in the pointcut
  524. // if numFormals > 0 then every branch of a disjunction must bind each formal once and only once.
  525. // in addition, the left and right branches of a disjunction must hold on join point kinds in
  526. // common.
  527. private void validateBindings(Pointcut dnfPointcut, Pointcut userPointcut, int numFormals, String[] names) {
  528. if (numFormals == 0) return; // nothing to check
  529. if (dnfPointcut.couldMatchKinds()==Shadow.NO_SHADOW_KINDS_BITS) return; // cant have problems if you dont match!
  530. if (dnfPointcut instanceof OrPointcut) {
  531. OrPointcut orBasedDNFPointcut = (OrPointcut) dnfPointcut;
  532. Pointcut[] leftBindings = new Pointcut[numFormals];
  533. Pointcut[] rightBindings = new Pointcut[numFormals];
  534. validateOrBranch(orBasedDNFPointcut,userPointcut,numFormals,names,leftBindings,rightBindings);
  535. } else {
  536. Pointcut[] bindings = new Pointcut[numFormals];
  537. validateSingleBranch(dnfPointcut, userPointcut, numFormals, names,bindings);
  538. }
  539. }
  540. private void validateOrBranch(OrPointcut pc, Pointcut userPointcut, int numFormals,
  541. String[] names, Pointcut[] leftBindings, Pointcut[] rightBindings) {
  542. Pointcut left = pc.getLeft();
  543. Pointcut right = pc.getRight();
  544. if (left instanceof OrPointcut) {
  545. Pointcut[] newRightBindings = new Pointcut[numFormals];
  546. validateOrBranch((OrPointcut)left,userPointcut,numFormals,names,leftBindings,newRightBindings);
  547. } else {
  548. if (left.couldMatchKinds()!=Shadow.NO_SHADOW_KINDS_BITS)
  549. validateSingleBranch(left, userPointcut, numFormals, names, leftBindings);
  550. }
  551. if (right instanceof OrPointcut) {
  552. Pointcut[] newLeftBindings = new Pointcut[numFormals];
  553. validateOrBranch((OrPointcut)right,userPointcut,numFormals,names,newLeftBindings,rightBindings);
  554. } else {
  555. if (right.couldMatchKinds()!=Shadow.NO_SHADOW_KINDS_BITS)
  556. validateSingleBranch(right, userPointcut, numFormals, names, rightBindings);
  557. }
  558. int kindsInCommon = left.couldMatchKinds() & right.couldMatchKinds();
  559. if (kindsInCommon!=Shadow.NO_SHADOW_KINDS_BITS && couldEverMatchSameJoinPoints(left,right)) {
  560. // we know that every branch binds every formal, so there is no ambiguity
  561. // if each branch binds it in exactly the same way...
  562. List ambiguousNames = new ArrayList();
  563. for (int i = 0; i < numFormals; i++) {
  564. if (leftBindings[i] == null) {
  565. if (rightBindings[i] != null) {
  566. ambiguousNames.add(names[i]);
  567. }
  568. } else if (!leftBindings[i].equals(rightBindings[i])) {
  569. ambiguousNames.add(names[i]);
  570. }
  571. }
  572. if (!ambiguousNames.isEmpty())
  573. raiseAmbiguityInDisjunctionError(userPointcut,ambiguousNames);
  574. }
  575. }
  576. // pc is a pointcut that does not contain any disjunctions
  577. // check that every formal is bound (negation doesn't count).
  578. // we know that numFormals > 0 or else we would not be called
  579. private void validateSingleBranch(Pointcut pc, Pointcut userPointcut, int numFormals, String[] names, Pointcut[] bindings) {
  580. boolean[] foundFormals = new boolean[numFormals];
  581. for (int i = 0; i < foundFormals.length; i++) {
  582. foundFormals[i] = false;
  583. }
  584. validateSingleBranchRecursion(pc, userPointcut, foundFormals, names, bindings);
  585. for (int i = 0; i < foundFormals.length; i++) {
  586. if (!foundFormals[i]) {
  587. boolean ignore = false;
  588. // ATAJ soften the unbound error for implicit bindings like JoinPoint in @AJ style
  589. for (int j = 0; j < userPointcut.m_ignoreUnboundBindingForNames.length; j++) {
  590. if (names[i] != null && names[i].equals(userPointcut.m_ignoreUnboundBindingForNames[j])) {
  591. ignore = true;
  592. break;
  593. }
  594. }
  595. if (!ignore) {
  596. raiseUnboundFormalError(names[i],userPointcut);
  597. }
  598. }
  599. }
  600. }
  601. // each formal must appear exactly once
  602. private void validateSingleBranchRecursion(Pointcut pc, Pointcut userPointcut, boolean[] foundFormals, String[] names, Pointcut[] bindings) {
  603. if (pc instanceof NotPointcut) {
  604. // nots can only appear at leaves in DNF
  605. NotPointcut not = (NotPointcut) pc;
  606. if (not.getNegatedPointcut() instanceof NameBindingPointcut) {
  607. NameBindingPointcut nnbp = (NameBindingPointcut) not.getNegatedPointcut();
  608. if (!nnbp.getBindingAnnotationTypePatterns().isEmpty() && !nnbp.getBindingTypePatterns().isEmpty())
  609. raiseNegationBindingError(userPointcut);
  610. }
  611. } else if (pc instanceof AndPointcut) {
  612. AndPointcut and = (AndPointcut) pc;
  613. validateSingleBranchRecursion(and.getLeft(), userPointcut,foundFormals,names,bindings);
  614. validateSingleBranchRecursion(and.getRight(),userPointcut,foundFormals,names,bindings);
  615. } else if (pc instanceof NameBindingPointcut) {
  616. List/*BindingTypePattern*/ btps = ((NameBindingPointcut)pc).getBindingTypePatterns();
  617. for (Iterator iter = btps.iterator(); iter.hasNext();) {
  618. BindingTypePattern btp = (BindingTypePattern) iter.next();
  619. int index = btp.getFormalIndex();
  620. bindings[index] = pc;
  621. if (foundFormals[index]) {
  622. raiseAmbiguousBindingError(names[index],userPointcut);
  623. } else {
  624. foundFormals[index] = true;
  625. }
  626. }
  627. List/*BindingAnnotationTypePattern*/ baps = ((NameBindingPointcut)pc).getBindingAnnotationTypePatterns();
  628. for (Iterator iter = baps.iterator(); iter.hasNext();) {
  629. BindingAnnotationTypePattern bap = (BindingAnnotationTypePattern) iter.next();
  630. int index = bap.getFormalIndex();
  631. bindings[index] = pc;
  632. if (foundFormals[index]) {
  633. raiseAmbiguousBindingError(names[index],userPointcut);
  634. } else {
  635. foundFormals[index] = true;
  636. }
  637. }
  638. } else if (pc instanceof ConcreteCflowPointcut) {
  639. ConcreteCflowPointcut cfp = (ConcreteCflowPointcut) pc;
  640. int[] slots = cfp.getUsedFormalSlots();
  641. for (int i = 0; i < slots.length; i++) {
  642. bindings[slots[i]] = cfp;
  643. if (foundFormals[slots[i]]) {
  644. raiseAmbiguousBindingError(names[slots[i]],userPointcut);
  645. } else {
  646. foundFormals[slots[i]] = true;
  647. }
  648. }
  649. }
  650. }
  651. // By returning false from this method, we are allowing binding of the same
  652. // variable on either side of an or.
  653. // Be conservative :- have to consider overriding, varargs, autoboxing,
  654. // the effects of itds (on within for example), interfaces, the fact that
  655. // join points can have multiple signatures and so on.
  656. private boolean couldEverMatchSameJoinPoints(Pointcut left, Pointcut right) {
  657. if (left instanceof OrPointcut) {
  658. OrPointcut leftOrPointcut = (OrPointcut)left;
  659. if (couldEverMatchSameJoinPoints(leftOrPointcut.getLeft(),right)) return true;
  660. if (couldEverMatchSameJoinPoints(leftOrPointcut.getRight(),right)) return true;
  661. return false;
  662. }
  663. if (right instanceof OrPointcut) {
  664. OrPointcut rightOrPointcut = (OrPointcut)right;
  665. if (couldEverMatchSameJoinPoints(left,rightOrPointcut.getLeft())) return true;
  666. if (couldEverMatchSameJoinPoints(left,rightOrPointcut.getRight())) return true;
  667. return false;
  668. }
  669. // look for withins
  670. WithinPointcut leftWithin = (WithinPointcut) findFirstPointcutIn(left,WithinPointcut.class);
  671. WithinPointcut rightWithin = (WithinPointcut) findFirstPointcutIn(right,WithinPointcut.class);
  672. if ((leftWithin != null) && (rightWithin != null)) {
  673. if (!leftWithin.couldEverMatchSameJoinPointsAs(rightWithin)) return false;
  674. }
  675. // look for kinded
  676. KindedPointcut leftKind = (KindedPointcut) findFirstPointcutIn(left,KindedPointcut.class);
  677. KindedPointcut rightKind = (KindedPointcut) findFirstPointcutIn(right,KindedPointcut.class);
  678. if ((leftKind != null) && (rightKind != null)) {
  679. if (!leftKind.couldEverMatchSameJoinPointsAs(rightKind)) return false;
  680. }
  681. return true;
  682. }
  683. private Pointcut findFirstPointcutIn(Pointcut toSearch, Class toLookFor) {
  684. if (toSearch instanceof NotPointcut) return null;
  685. if (toLookFor.isInstance(toSearch)) return toSearch;
  686. if (toSearch instanceof AndPointcut) {
  687. AndPointcut apc = (AndPointcut) toSearch;
  688. Pointcut left = findFirstPointcutIn(apc.getLeft(),toLookFor);
  689. if (left != null) return left;
  690. return findFirstPointcutIn(apc.getRight(),toLookFor);
  691. }
  692. return null;
  693. }
  694. /**
  695. * @param userPointcut
  696. */
  697. private void raiseNegationBindingError(Pointcut userPointcut) {
  698. world.showMessage(IMessage.ERROR,
  699. WeaverMessages.format(WeaverMessages.NEGATION_DOESNT_ALLOW_BINDING),
  700. userPointcut.getSourceContext().makeSourceLocation(userPointcut),null);
  701. }
  702. /**
  703. * @param name
  704. * @param userPointcut
  705. */
  706. private void raiseAmbiguousBindingError(String name, Pointcut userPointcut) {
  707. world.showMessage(IMessage.ERROR,
  708. WeaverMessages.format(WeaverMessages.AMBIGUOUS_BINDING,
  709. name),
  710. userPointcut.getSourceContext().makeSourceLocation(userPointcut),null);
  711. }
  712. /**
  713. * @param userPointcut
  714. */
  715. private void raiseAmbiguityInDisjunctionError(Pointcut userPointcut, List names) {
  716. StringBuffer formalNames = new StringBuffer(names.get(0).toString());
  717. for (int i = 1; i < names.size(); i++) {
  718. formalNames.append(", ");
  719. formalNames.append(names.get(i));
  720. }
  721. world.showMessage(IMessage.ERROR,
  722. WeaverMessages.format(WeaverMessages.AMBIGUOUS_BINDING_IN_OR,formalNames),
  723. userPointcut.getSourceContext().makeSourceLocation(userPointcut),null);
  724. }
  725. /**
  726. * @param name
  727. * @param userPointcut
  728. */
  729. private void raiseUnboundFormalError(String name, Pointcut userPointcut) {
  730. world.showMessage(IMessage.ERROR,
  731. WeaverMessages.format(WeaverMessages.UNBOUND_FORMAL,
  732. name),
  733. userPointcut.getSourceContext().makeSourceLocation(userPointcut),null);
  734. }
  735. // public void dumpUnwoven(File file) throws IOException {
  736. // BufferedOutputStream os = FileUtil.makeOutputStream(file);
  737. // this.zipOutputStream = new ZipOutputStream(os);
  738. // dumpUnwoven();
  739. // /* BUG 40943*/
  740. // dumpResourcesToOutJar();
  741. // zipOutputStream.close(); //this flushes and closes the acutal file
  742. // }
  743. //
  744. //
  745. // public void dumpUnwoven() throws IOException {
  746. // Collection filesToDump = new HashSet(sourceJavaClasses.values());
  747. // for (Iterator i = filesToDump.iterator(); i.hasNext(); ) {
  748. // UnwovenClassFile classFile = (UnwovenClassFile)i.next();
  749. // dumpUnchanged(classFile);
  750. // }
  751. // }
  752. // public void dumpResourcesToOutPath() throws IOException {
  753. //// System.err.println("? dumpResourcesToOutPath() resources=" + resources.keySet());
  754. // Iterator i = resources.keySet().iterator();
  755. // while (i.hasNext()) {
  756. // UnwovenClassFile res = (UnwovenClassFile)resources.get(i.next());
  757. // dumpUnchanged(res);
  758. // }
  759. // //resources = new HashMap();
  760. // }
  761. //
  762. /* BUG #40943 */
  763. // public void dumpResourcesToOutJar() throws IOException {
  764. //// System.err.println("? dumpResourcesToOutJar() resources=" + resources.keySet());
  765. // Iterator i = resources.keySet().iterator();
  766. // while (i.hasNext()) {
  767. // String name = (String)i.next();
  768. // UnwovenClassFile res = (UnwovenClassFile)resources.get(name);
  769. // writeZipEntry(name,res.getBytes());
  770. // }
  771. // resources = new HashMap();
  772. // }
  773. //
  774. // // halfway house for when the jar is managed outside of the weaver, but the resources
  775. // // to be copied are known in the weaver.
  776. // public void dumpResourcesToOutJar(ZipOutputStream zos) throws IOException {
  777. // this.zipOutputStream = zos;
  778. // dumpResourcesToOutJar();
  779. // }
  780. public void addManifest (Manifest newManifest) {
  781. // System.out.println("? addManifest() newManifest=" + newManifest);
  782. if (manifest == null) {
  783. manifest = newManifest;
  784. }
  785. }
  786. public static final String MANIFEST_NAME = "META-INF/MANIFEST.MF";
  787. private static final String WEAVER_MANIFEST_VERSION = "1.0";
  788. private static final Attributes.Name CREATED_BY = new Name("Created-By");
  789. private static final String WEAVER_CREATED_BY = "AspectJ Compiler";
  790. public Manifest getManifest (boolean shouldCreate) {
  791. if (manifest == null && shouldCreate) {
  792. manifest = new Manifest();
  793. Attributes attributes = manifest.getMainAttributes();
  794. attributes.put(Name.MANIFEST_VERSION,WEAVER_MANIFEST_VERSION);
  795. attributes.put(CREATED_BY,WEAVER_CREATED_BY);
  796. }
  797. return manifest;
  798. }
  799. // ---- weaving
  800. // Used by some test cases only...
  801. public Collection weave(File file) throws IOException {
  802. OutputStream os = FileUtil.makeOutputStream(file);
  803. this.zipOutputStream = new ZipOutputStream(os);
  804. prepareForWeave();
  805. Collection c = weave( new IClassFileProvider() {
  806. public boolean isApplyAtAspectJMungersOnly() {
  807. return false;
  808. }
  809. public Iterator getClassFileIterator() {
  810. return addedClasses.iterator();
  811. }
  812. public IWeaveRequestor getRequestor() {
  813. return new IWeaveRequestor() {
  814. public void acceptResult(UnwovenClassFile result) {
  815. try {
  816. writeZipEntry(result.filename, result.bytes);
  817. } catch(IOException ex) {}
  818. }
  819. public void processingReweavableState() {}
  820. public void addingTypeMungers() {}
  821. public void weavingAspects() {}
  822. public void weavingClasses() {}
  823. public void weaveCompleted() {}
  824. };
  825. }
  826. });
  827. // /* BUG 40943*/
  828. // dumpResourcesToOutJar();
  829. zipOutputStream.close(); //this flushes and closes the acutal file
  830. return c;
  831. }
  832. // public Collection weave() throws IOException {
  833. // prepareForWeave();
  834. // Collection filesToWeave;
  835. //
  836. // if (needToReweaveWorld) {
  837. // filesToWeave = sourceJavaClasses.values();
  838. // } else {
  839. // filesToWeave = addedClasses;
  840. // }
  841. //
  842. // Collection wovenClassNames = new ArrayList();
  843. // world.showMessage(IMessage.INFO, "might need to weave " + filesToWeave +
  844. // "(world=" + needToReweaveWorld + ")", null, null);
  845. //
  846. //
  847. // //System.err.println("typeMungers: " + typeMungerList);
  848. //
  849. // prepareToProcessReweavableState();
  850. // // clear all state from files we'll be reweaving
  851. // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) {
  852. // UnwovenClassFile classFile = (UnwovenClassFile)i.next();
  853. // String className = classFile.getClassName();
  854. // BcelObjectType classType = getClassType(className);
  855. // processReweavableStateIfPresent(className, classType);
  856. // }
  857. //
  858. //
  859. //
  860. // //XXX this isn't quite the right place for this...
  861. // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) {
  862. // UnwovenClassFile classFile = (UnwovenClassFile)i.next();
  863. // String className = classFile.getClassName();
  864. // addTypeMungers(className);
  865. // }
  866. //
  867. // // first weave into aspects
  868. // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) {
  869. // UnwovenClassFile classFile = (UnwovenClassFile)i.next();
  870. // String className = classFile.getClassName();
  871. // BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className));
  872. // if (classType.isAspect()) {
  873. // weave(classFile, classType);
  874. // wovenClassNames.add(className);
  875. // }
  876. // }
  877. //
  878. // // then weave into non-aspects
  879. // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) {
  880. // UnwovenClassFile classFile = (UnwovenClassFile)i.next();
  881. // String className = classFile.getClassName();
  882. // BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className));
  883. // if (! classType.isAspect()) {
  884. // weave(classFile, classType);
  885. // wovenClassNames.add(className);
  886. // }
  887. // }
  888. //
  889. // if (zipOutputStream != null && !needToReweaveWorld) {
  890. // Collection filesToDump = new HashSet(sourceJavaClasses.values());
  891. // filesToDump.removeAll(filesToWeave);
  892. // for (Iterator i = filesToDump.iterator(); i.hasNext(); ) {
  893. // UnwovenClassFile classFile = (UnwovenClassFile)i.next();
  894. // dumpUnchanged(classFile);
  895. // }
  896. // }
  897. //
  898. // addedClasses = new ArrayList();
  899. // deletedTypenames = new ArrayList();
  900. //
  901. // return wovenClassNames;
  902. // }
  903. // variation of "weave" that sources class files from an external source.
  904. public Collection weave(IClassFileProvider input) throws IOException {
  905. if (trace.isTraceEnabled()) trace.enter("weave",this,input);
  906. ContextToken weaveToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING, "");
  907. Collection wovenClassNames = new ArrayList();
  908. IWeaveRequestor requestor = input.getRequestor();
  909. for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) {
  910. UnwovenClassFile classFile = (UnwovenClassFile)i.next();
  911. if (AsmManager.isCreatingModel() && !isBatchWeave) {
  912. // remove all relationships where this file being woven is the target of the relationship
  913. AsmManager.getDefault().removeRelationshipsTargettingThisType(classFile.getClassName());
  914. }
  915. }
  916. // special case for AtAspectJMungerOnly - see #113587
  917. if (input.isApplyAtAspectJMungersOnly()) {
  918. ContextToken atAspectJMungersOnly = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_ATASPECTJTYPE_MUNGERS_ONLY, "");
  919. requestor.weavingAspects();
  920. ContextToken aspectToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_ASPECTS, "");
  921. for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) {
  922. UnwovenClassFile classFile = (UnwovenClassFile)i.next();
  923. String className = classFile.getClassName();
  924. ResolvedType theType = world.resolve(className);
  925. if (theType.isAnnotationStyleAspect()) {
  926. BcelObjectType classType = BcelWorld.getBcelObjectType(theType);
  927. if (classType==null) {
  928. throw new BCException("Can't find bcel delegate for "+className+" type="+theType.getClass());
  929. }
  930. LazyClassGen clazz = classType.getLazyClassGen();
  931. BcelPerClauseAspectAdder selfMunger = new BcelPerClauseAspectAdder(theType, theType.getPerClause().getKind());
  932. selfMunger.forceMunge(clazz, true);
  933. classType.finishedWith();
  934. UnwovenClassFile[] newClasses = getClassFilesFor(clazz);
  935. for (int news = 0; news < newClasses.length; news++) {
  936. requestor.acceptResult(newClasses[news]);
  937. }
  938. wovenClassNames.add(classFile.getClassName());
  939. }
  940. }
  941. requestor.weaveCompleted();
  942. CompilationAndWeavingContext.leavingPhase(atAspectJMungersOnly);
  943. return wovenClassNames;
  944. }
  945. requestor.processingReweavableState();
  946. ContextToken reweaveToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_REWEAVABLE_STATE,"");
  947. prepareToProcessReweavableState();
  948. // clear all state from files we'll be reweaving
  949. for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) {
  950. UnwovenClassFile classFile = (UnwovenClassFile)i.next();
  951. String className = classFile.getClassName();
  952. BcelObjectType classType = getClassType(className);
  953. // null return from getClassType() means the delegate is an eclipse source type - so
  954. // there *cant* be any reweavable state... (he bravely claimed...)
  955. if (classType !=null) {
  956. ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_REWEAVABLE_STATE, className);
  957. processReweavableStateIfPresent(className, classType);
  958. CompilationAndWeavingContext.leavingPhase(tok);
  959. }
  960. }
  961. CompilationAndWeavingContext.leavingPhase(reweaveToken);
  962. ContextToken typeMungingToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_TYPE_MUNGERS,"");
  963. requestor.addingTypeMungers();
  964. // We process type mungers in two groups, first mungers that change the type
  965. // hierarchy, then 'normal' ITD type mungers.
  966. // Process the types in a predictable order (rather than the order encountered).
  967. // For class A, the order is superclasses of A then superinterfaces of A
  968. // (and this mechanism is applied recursively)
  969. List typesToProcess = new ArrayList();
  970. for (Iterator iter = input.getClassFileIterator(); iter.hasNext();) {
  971. UnwovenClassFile clf = (UnwovenClassFile) iter.next();
  972. typesToProcess.add(clf.getClassName());
  973. }
  974. while (typesToProcess.size()>0) {
  975. weaveParentsFor(typesToProcess,(String)typesToProcess.get(0));
  976. }
  977. for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) {
  978. UnwovenClassFile classFile = (UnwovenClassFile)i.next();
  979. String className = classFile.getClassName();
  980. addNormalTypeMungers(className);
  981. }
  982. CompilationAndWeavingContext.leavingPhase(typeMungingToken);
  983. requestor.weavingAspects();
  984. ContextToken aspectToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_ASPECTS, "");
  985. // first weave into aspects
  986. for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) {
  987. UnwovenClassFile classFile = (UnwovenClassFile)i.next();
  988. String className = classFile.getClassName();
  989. ResolvedType theType = world.resolve(className);
  990. if (theType.isAspect()) {
  991. BcelObjectType classType = BcelWorld.getBcelObjectType(theType);
  992. if (classType==null) {
  993. // Sometimes.. if the Bcel Delegate couldn't be found then a problem occurred at compile time - on
  994. // a previous compiler run. In this case I assert the delegate will still be an EclipseSourceType
  995. // and we can ignore the problem here (the original compile error will be reported again from
  996. // the eclipse source type) - pr113531
  997. ReferenceTypeDelegate theDelegate = ((ReferenceType)theType).getDelegate();
  998. if (theDelegate.getClass().getName().endsWith("EclipseSourceType")) continue;
  999. throw new BCException("Can't find bcel delegate for "+className+" type="+theType.getClass());
  1000. }
  1001. weaveAndNotify(classFile, classType,requestor);
  1002. wovenClassNames.add(className);
  1003. }
  1004. }
  1005. CompilationAndWeavingContext.leavingPhase(aspectToken);
  1006. requestor.weavingClasses();
  1007. ContextToken classToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_CLASSES, "");
  1008. // then weave into non-aspects
  1009. for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) {
  1010. UnwovenClassFile classFile = (UnwovenClassFile)i.next();
  1011. String className = classFile.getClassName();
  1012. ResolvedType theType = world.resolve(className);
  1013. if (!theType.isAspect()) {
  1014. BcelObjectType classType = BcelWorld.getBcelObjectType(theType);
  1015. if (classType==null) {
  1016. // bug 119882 - see above comment for bug 113531
  1017. ReferenceTypeDelegate theDelegate = ((ReferenceType)theType).getDelegate();
  1018. if (theDelegate.getClass().getName().endsWith("EclipseSourceType")) continue;
  1019. throw new BCException("Can't find bcel delegate for "+className+" type="+theType.getClass());
  1020. }
  1021. weaveAndNotify(classFile, classType, requestor);
  1022. wovenClassNames.add(className);
  1023. }
  1024. }
  1025. CompilationAndWeavingContext.leavingPhase(classToken);
  1026. addedClasses = new ArrayList();
  1027. deletedTypenames = new ArrayList();
  1028. warnOnUnmatchedAdvice();
  1029. requestor.weaveCompleted();
  1030. CompilationAndWeavingContext.leavingPhase(weaveToken);
  1031. if (trace.isTraceEnabled()) trace.exit("weave",wovenClassNames);
  1032. return wovenClassNames;
  1033. }
  1034. /**
  1035. * In 1.5 mode and with XLint:adviceDidNotMatch enabled, put out messages for any
  1036. * mungers that did not match anything.
  1037. */
  1038. private void warnOnUnmatchedAdvice() {
  1039. class AdviceLocation {
  1040. private int lineNo;
  1041. private UnresolvedType inAspect;
  1042. public AdviceLocation(BcelAdvice advice) {
  1043. this.lineNo = advice.getSourceLocation().getLine();
  1044. this.inAspect = advice.getDeclaringAspect();
  1045. }
  1046. public boolean equals(Object obj) {
  1047. if (!(obj instanceof AdviceLocation)) return false;
  1048. AdviceLocation other = (AdviceLocation) obj;
  1049. if (this.lineNo != other.lineNo) return false;
  1050. if (!this.inAspect.equals(other.inAspect)) return false;
  1051. return true;
  1052. }
  1053. public int hashCode() {
  1054. return 37 + 17*lineNo + 17*inAspect.hashCode();
  1055. };
  1056. }
  1057. // FIXME asc Should be factored out into Xlint code and done automatically for all xlint messages, ideally.
  1058. // if a piece of advice hasn't matched anywhere and we are in -1.5 mode, put out a warning
  1059. if (world.isInJava5Mode() &&
  1060. world.getLint().adviceDidNotMatch.isEnabled()) {
  1061. List l = world.getCrosscuttingMembersSet().getShadowMungers();
  1062. Set alreadyWarnedLocations = new HashSet();
  1063. for (Iterator iter = l.iterator(); iter.hasNext();) {
  1064. ShadowMunger element = (ShadowMunger) iter.next();
  1065. if (element instanceof BcelAdvice) { // This will stop us incorrectly reporting deow Checkers
  1066. BcelAdvice ba = (BcelAdvice)element;
  1067. if (!ba.hasMatchedSomething()) {
  1068. // Because we implement some features of AJ itself by creating our own kind of mungers, you sometimes
  1069. // find that ba.getSignature() is not a BcelMethod - for example it might be a cflow entry munger.
  1070. if (ba.getSignature()!=null) {
  1071. // check we haven't already warned on this advice and line
  1072. // (cflow creates multiple mungers for the same advice)
  1073. AdviceLocation loc = new AdviceLocation(ba);
  1074. if (alreadyWarnedLocations.contains(loc)) {
  1075. continue;
  1076. } else {
  1077. alreadyWarnedLocations.add(loc);
  1078. }
  1079. if (!(ba.getSignature() instanceof BcelMethod)
  1080. || !Utility.isSuppressing((AnnotationX[])ba.getSignature().getAnnotations(),"adviceDidNotMatch")) {
  1081. world.getLint().adviceDidNotMatch.signal(ba.getDeclaringAspect().toString(),element.getSourceLocation());
  1082. }
  1083. }
  1084. }
  1085. }
  1086. }
  1087. }
  1088. }
  1089. /**
  1090. * 'typeToWeave' is one from the 'typesForWeaving' list. This routine ensures we process
  1091. * supertypes (classes/interfaces) of 'typeToWeave' that are in the
  1092. * 'typesForWeaving' list before 'typeToWeave' itself. 'typesToWeave' is then removed from
  1093. * the 'typesForWeaving' list.
  1094. *
  1095. * Note: Future gotcha in here ... when supplying partial hierarchies, this algorithm may
  1096. * break down. If you have a hierarchy A>B>C and only give A and C to the weaver, it
  1097. * may choose to weave them in either order - but you'll probably have other problems if
  1098. * you are supplying partial hierarchies like that !
  1099. */
  1100. private void weaveParentsFor(List typesForWeaving,String typeToWeave) {
  1101. // Look at the supertype first
  1102. ResolvedType rtx = world.resolve(typeToWeave);
  1103. ResolvedType superType = rtx.getSuperclass();
  1104. if (superType!=null && typesForWeaving.contains(superType.getName())) {
  1105. weaveParentsFor(typesForWeaving,superType.getName());
  1106. }
  1107. // Then look at the superinterface list
  1108. ResolvedType[] interfaceTypes = rtx.getDeclaredInterfaces();
  1109. for (int i = 0; i < interfaceTypes.length; i++) {
  1110. ResolvedType rtxI = interfaceTypes[i];
  1111. if (typesForWeaving.contains(rtxI.getName())) {
  1112. weaveParentsFor(typesForWeaving,rtxI.getName());
  1113. }
  1114. }
  1115. ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_DECLARE_PARENTS,rtx.getName());
  1116. weaveParentTypeMungers(rtx); // Now do this type
  1117. CompilationAndWeavingContext.leavingPhase(tok);
  1118. typesForWeaving.remove(typeToWeave); // and remove it from the list of those to process
  1119. }
  1120. public void prepareToProcessReweavableState() {
  1121. if (inReweavableMode)
  1122. world.showMessage(IMessage.INFO,
  1123. WeaverMessages.format(WeaverMessages.REWEAVABLE_MODE),
  1124. null, null);
  1125. }
  1126. public void processReweavableStateIfPresent(String className, BcelObjectType classType) {
  1127. // If the class is marked reweavable, check any aspects around when it was built are in this world
  1128. WeaverStateInfo wsi = classType.getWeaverState();
  1129. if (wsi!=null && wsi.isReweavable()) { // Check all necessary types are around!
  1130. world.showMessage(IMessage.INFO,
  1131. WeaverMessages.format(WeaverMessages.PROCESSING_REWEAVABLE,className,classType.getSourceLocation().getSourceFile()),
  1132. null,null);
  1133. Set aspectsPreviouslyInWorld = wsi.getAspectsAffectingType();
  1134. if (aspectsPreviouslyInWorld!=null) {
  1135. // keep track of them just to ensure unique missing aspect error reporting
  1136. Set alreadyConfirmedReweavableState = new HashSet();
  1137. for (Iterator iter = aspectsPreviouslyInWorld.iterator(); iter.hasNext();) {
  1138. String requiredTypeName = (String) iter.next();
  1139. if (!alreadyConfirmedReweavableState.contains(requiredTypeName)) {
  1140. ResolvedType rtx = world.resolve(UnresolvedType.forName(requiredTypeName),true);
  1141. boolean exists = !rtx.isMissing();
  1142. if (!exists) {
  1143. world.showMessage(IMessage.ERROR,
  1144. WeaverMessages.format(WeaverMessages.MISSING_REWEAVABLE_TYPE,requiredTypeName,className),
  1145. classType.getSourceLocation(), null);
  1146. } else {
  1147. // weaved in aspect that are not declared in aop.xml trigger an error for now
  1148. // may cause headhache for LTW and packaged lib without aop.xml in
  1149. // see #104218
  1150. if(!xcutSet.containsAspect(rtx)){
  1151. world.showMessage(
  1152. IMessage.ERROR,
  1153. WeaverMessages.format(
  1154. WeaverMessages.REWEAVABLE_ASPECT_NOT_REGISTERED,
  1155. requiredTypeName,
  1156. className
  1157. ),
  1158. null,
  1159. null
  1160. );
  1161. } else if (!world.getMessageHandler().isIgnoring(IMessage.INFO))
  1162. world.showMessage(IMessage.INFO,
  1163. WeaverMessages.format(WeaverMessages.VERIFIED_REWEAVABLE_TYPE,requiredTypeName,rtx.getSourceLocation().getSourceFile()),
  1164. null,null);
  1165. alreadyConfirmedReweavableState.add(requiredTypeName);
  1166. }
  1167. }
  1168. }
  1169. }
  1170. // old:
  1171. //classType.setJavaClass(Utility.makeJavaClass(classType.getJavaClass().getFileName(), wsi.getUnwovenClassFileData()));
  1172. // new: reweavable default with clever diff
  1173. classType.setJavaClass(Utility.makeJavaClass(classType.getJavaClass().getFileName(), wsi.getUnwovenClassFileData(classType.getJavaClass().getBytes())));
  1174. // } else {
  1175. // classType.resetState();
  1176. }
  1177. }
  1178. private void weaveAndNotify(UnwovenClassFile classFile, BcelObjectType classType,
  1179. IWeaveRequestor requestor) throws IOException {
  1180. ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_TYPE, classType.getResolvedTypeX().getName());
  1181. LazyClassGen clazz = weaveWithoutDump(classFile,classType);
  1182. classType.finishedWith();
  1183. //clazz is null if the classfile was unchanged by weaving...
  1184. if (clazz != null) {
  1185. UnwovenClassFile[] newClasses = getClassFilesFor(clazz);
  1186. for (int i = 0; i < newClasses.length; i++) {
  1187. requestor.acceptResult(newClasses[i]);
  1188. }
  1189. } else {
  1190. requestor.acceptResult(classFile);
  1191. }
  1192. classType.weavingCompleted();
  1193. CompilationAndWeavingContext.leavingPhase(tok);
  1194. }
  1195. /** helper method - will return NULL if the underlying delegate is an EclipseSourceType and not a BcelObjectType */
  1196. public BcelObjectType getClassType(String forClass) {
  1197. return BcelWorld.getBcelObjectType(world.resolve(forClass));
  1198. }
  1199. public void addParentTypeMungers(String typeName) {
  1200. weaveParentTypeMungers(world.resolve(typeName));
  1201. }
  1202. public void addNormalTypeMungers(String typeName) {
  1203. weaveNormalTypeMungers(world.resolve(typeName));
  1204. }
  1205. public UnwovenClassFile[] getClassFilesFor(LazyClassGen clazz) {
  1206. List childClasses = clazz.getChildClasses(world);
  1207. UnwovenClassFile[] ret = new UnwovenClassFile[1 + childClasses.size()];
  1208. ret[0] = new UnwovenClassFile(clazz.getFileName(),clazz.getJavaClassBytesIncludingReweavable(world));
  1209. int index = 1;
  1210. for (Iterator iter = childClasses.iterator(); iter.hasNext();) {
  1211. UnwovenClassFile.ChildClass element = (UnwovenClassFile.ChildClass) iter.next();
  1212. UnwovenClassFile childClass = new UnwovenClassFile(clazz.getFileName() + "$" + element.name, element.bytes);
  1213. ret[index++] = childClass;
  1214. }
  1215. return ret;
  1216. }
  1217. /**
  1218. * Weaves new parents and annotations onto a type ("declare parents" and "declare @type")
  1219. *
  1220. * Algorithm:
  1221. * 1. First pass, do parents then do annotations. During this pass record:
  1222. * - any parent mungers that don't match but have a non-wild annotation type pattern
  1223. * - any annotation mungers that don't match
  1224. * 2. Multiple subsequent passes which go over the munger lists constructed in the first
  1225. * pass, repeatedly applying them until nothing changes.
  1226. * FIXME asc confirm that algorithm is optimal ??
  1227. */
  1228. public void weaveParentTypeMungers(ResolvedType onType) {
  1229. if (onType.isRawType()) onType = onType.getGenericType();
  1230. onType.clearInterTypeMungers();
  1231. List decpToRepeat = new ArrayList();
  1232. boolean aParentChangeOccurred = false;
  1233. boolean anAnnotationChangeOccurred = false;
  1234. // First pass - apply all decp mungers
  1235. for (Iterator i = declareParentsList.iterator(); i.hasNext(); ) {
  1236. DeclareParents decp = (DeclareParents)i.next();
  1237. boolean typeChanged = applyDeclareParents(decp,onType);
  1238. if (typeChanged) {
  1239. aParentChangeOccurred = true;
  1240. } else { // Perhaps it would have matched if a 'dec @type' had modified the type
  1241. if (!decp.getChild().isStarAnnotation()) decpToRepeat.add(decp);
  1242. }
  1243. }
  1244. // Still first pass - apply all dec @type mungers
  1245. for (Iterator i = xcutSet.getDeclareAnnotationOnTypes().iterator();i.hasNext();) {
  1246. DeclareAnnotation decA = (DeclareAnnotation)i.next();
  1247. boolean typeChanged = applyDeclareAtType(decA,onType,true);
  1248. if (typeChanged) {
  1249. anAnnotationChangeOccurred = true;
  1250. }
  1251. }
  1252. while ((aParentChangeOccurred || anAnnotationChangeOccurred) && !decpToRepeat.isEmpty()) {
  1253. anAnnotationChangeOccurred = aParentChangeOccurred = false;
  1254. List decpToRepeatNextTime = new ArrayList();
  1255. for (Iterator iter = decpToRepeat.iterator(); iter.hasNext();) {
  1256. DeclareParents decp = (DeclareParents) iter.next();
  1257. boolean typeChanged = applyDeclareParents(decp,onType);
  1258. if (typeChanged) {
  1259. aParentChangeOccurred = true;
  1260. } else {
  1261. decpToRepeatNextTime.add(decp);
  1262. }
  1263. }
  1264. for (Iterator iter = xcutSet.getDeclareAnnotationOnTypes().iterator(); iter.hasNext();) {
  1265. DeclareAnnotation decA = (DeclareAnnotation) iter.next();
  1266. boolean typeChanged = applyDeclareAtType(decA,onType,false);
  1267. if (typeChanged) {
  1268. anAnnotationChangeOccurred = true;
  1269. }
  1270. }
  1271. decpToRepeat = decpToRepeatNextTime;
  1272. }
  1273. }
  1274. /**
  1275. * Apply a declare @type - return true if we change the type
  1276. */
  1277. private boolean applyDeclareAtType(DeclareAnnotation decA, ResolvedType onType,boolean reportProblems) {
  1278. boolean didSomething = false;
  1279. if (decA.matches(onType)) {
  1280. if (onType.hasAnnotation(decA.getAnnotationX().getSignature())) {
  1281. // Could put out a lint here for an already annotated type ...
  1282. // if (reportProblems) {
  1283. // world.getLint().elementAlreadyAnnotated.signal(
  1284. // new String[]{onType.toString(),decA.getAnnotationTypeX().toString()},
  1285. // onType.getSourceLocation(),new ISourceLocation[]{decA.getSourceLocation()});
  1286. // }
  1287. return false;
  1288. }
  1289. AnnotationX annoX = decA.getAnnotationX();
  1290. // check the annotation is suitable for the target
  1291. boolean problemReported = verifyTargetIsOK(decA, onType, annoX,reportProblems);
  1292. if (!problemReported) {
  1293. AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decA.getSourceLocation(),onType.getSourceLocation());
  1294. // TAG: WeavingMessage
  1295. if (!getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)){
  1296. getWorld().getMessageHandler().handleMessage(
  1297. WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ANNOTATES,
  1298. new String[]{
  1299. onType.toString(),
  1300. Utility.beautifyLocation(onType.getSourceLocation()),
  1301. decA.getAnnotationString(),
  1302. "type",
  1303. decA.getAspect().toString(),
  1304. Utility.beautifyLocation(decA.getSourceLocation())
  1305. }));
  1306. }
  1307. didSomething = true;
  1308. ResolvedTypeMunger newAnnotationTM = new AnnotationOnTypeMunger(annoX);
  1309. newAnnotationTM.setSourceLocation(decA.getSourceLocation());
  1310. onType.addInterTypeMunger(new BcelTypeMunger(newAnnotationTM,decA.getAspect().resolve(world)));
  1311. decA.copyAnnotationTo(onType);
  1312. }
  1313. }
  1314. return didSomething;
  1315. }
  1316. /**
  1317. * Checks for an @target() on the annotation and if found ensures it allows the annotation
  1318. * to be attached to the target type that matched.
  1319. */
  1320. private boolean verifyTargetIsOK(DeclareAnnotation decA, ResolvedType onType, AnnotationX annoX,boolean outputProblems) {
  1321. boolean problemReported = false;
  1322. if (annoX.specifiesTarget()) {
  1323. if ( (onType.isAnnotation() && !annoX.allowedOnAnnotationType()) ||
  1324. (!annoX.allowedOnRegularType())) {
  1325. if (outputProblems) {
  1326. if (decA.isExactPattern()) {
  1327. world.getMessageHandler().handleMessage(MessageUtil.error(
  1328. WeaverMessages.format(WeaverMessages.INCORRECT_TARGET_FOR_DECLARE_ANNOTATION,
  1329. onType.getName(),annoX.stringify(),annoX.getValidTargets()),decA.getSourceLocation()));
  1330. } else {
  1331. if (world.getLint().invalidTargetForAnnotation.isEnabled()) {
  1332. world.getLint().invalidTargetForAnnotation.signal(
  1333. new String[]{onType.getName(),annoX.stringify(),annoX.getValidTargets()},decA.getSourceLocation(),new ISourceLocation[]{onType.getSourceLocation()});
  1334. }
  1335. }
  1336. }
  1337. problemReported = true;
  1338. }
  1339. }
  1340. return problemReported;
  1341. }
  1342. /**
  1343. * Apply a single declare parents - return true if we change the type
  1344. */
  1345. private boolean applyDeclareParents(DeclareParents p, ResolvedType onType) {
  1346. boolean didSomething = false;
  1347. List newParents = p.findMatchingNewParents(onType,true);
  1348. if (!newParents.isEmpty()) {
  1349. didSomething=true;
  1350. BcelObjectType classType = BcelWorld.getBcelObjectType(onType);
  1351. //System.err.println("need to do declare parents for: " + onType);
  1352. for (Iterator j = newParents.iterator(); j.hasNext(); ) {
  1353. ResolvedType newParent = (ResolvedType)j.next();
  1354. // We set it here so that the imminent matching for ITDs can succeed - we
  1355. // still haven't done the necessary changes to the class file itself
  1356. // (like transform super calls) - that is done in BcelTypeMunger.mungeNewParent()
  1357. classType.addParent(newParent);
  1358. ResolvedTypeMunger newParentMunger = new NewParentTypeMunger(newParent);
  1359. newParentMunger.setSourceLocation(p.getSourceLocation());
  1360. onType.addInterTypeMunger(new BcelTypeMunger(newParentMunger, xcutSet.findAspectDeclaringParents(p)));
  1361. }
  1362. }
  1363. return didSomething;
  1364. }
  1365. public void weaveNormalTypeMungers(ResolvedType onType) {
  1366. ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_TYPE_MUNGERS, onType.getName());
  1367. if (onType.isRawType() || onType.isParameterizedType()) onType = onType.getGenericType();
  1368. for (Iterator i = typeMungerList.iterator(); i.hasNext(); ) {
  1369. ConcreteTypeMunger m = (ConcreteTypeMunger)i.next();
  1370. if (!m.isLateMunger() && m.matches(onType)) {
  1371. onType.addInterTypeMunger(m);
  1372. }
  1373. }
  1374. CompilationAndWeavingContext.leavingPhase(tok);
  1375. }
  1376. // exposed for ClassLoader dynamic weaving
  1377. public LazyClassGen weaveWithoutDump(UnwovenClassFile classFile, BcelObjectType classType) throws IOException {
  1378. return weave(classFile, classType, false);
  1379. }
  1380. // non-private for testing
  1381. LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType) throws IOException {
  1382. LazyClassGen ret = weave(classFile, classType, true);
  1383. if (progressListener != null) {
  1384. progressMade += progressPerClassFile;
  1385. progressListener.setProgress(progressMade);
  1386. progressListener.setText("woven: " + classFile.getFilename());
  1387. }
  1388. return ret;
  1389. }
  1390. private LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType, boolean dump) throws IOException {
  1391. if (classType.isSynthetic()) { // Don't touch synthetic classes
  1392. if (dump) dumpUnchanged(classFile);
  1393. return null;
  1394. }
  1395. List shadowMungers = fastMatch(shadowMungerList, classType.getResolvedTypeX());
  1396. List typeMungers = classType.getResolvedTypeX().getInterTypeMungers();
  1397. classType.getResolvedTypeX().checkInterTypeMungers();
  1398. // Decide if we need to do actual weaving for this class
  1399. boolean mightNeedToWeave =
  1400. shadowMungers.size() > 0 ||
  1401. typeMungers.size() > 0 ||
  1402. classType.isAspect() ||
  1403. world.getDeclareAnnotationOnMethods().size()>0 ||
  1404. world.getDeclareAnnotationOnFields().size()>0;
  1405. // May need bridge methods if on 1.5 and something in our hierarchy is affected by ITDs
  1406. boolean mightNeedBridgeMethods =
  1407. world.isInJava5Mode() &&
  1408. !classType.isInterface() &&
  1409. classType.getResolvedTypeX().getInterTypeMungersIncludingSupers().size()>0;
  1410. LazyClassGen clazz = null;
  1411. if (mightNeedToWeave || mightNeedBridgeMethods) {
  1412. clazz = classType.getLazyClassGen();
  1413. //System.err.println("got lazy gen: " + clazz + ", " + clazz.getWeaverState());
  1414. try {
  1415. boolean isChanged = false;
  1416. if (mightNeedToWeave)
  1417. isChanged = BcelClassWeaver.weave(world, clazz, shadowMungers, typeMungers, lateTypeMungerList);
  1418. if (mightNeedBridgeMethods)
  1419. isChanged = BcelClassWeaver.calculateAnyRequiredBridgeMethods(world,clazz) || isChanged;
  1420. if (isChanged) {
  1421. if (dump) dump(classFile, clazz);
  1422. return clazz;
  1423. }
  1424. } catch (RuntimeException re) {
  1425. String classDebugInfo = null;
  1426. try {
  1427. classDebugInfo = clazz.toLongString();
  1428. } catch (Exception e) {
  1429. // recover from crash whilst producing debug string
  1430. classDebugInfo = clazz.getClassName();
  1431. }
  1432. String messageText = "trouble in: \n" + classDebugInfo;
  1433. getWorld().getMessageHandler().handleMessage(
  1434. new Message(messageText,IMessage.ABORT,re,null)
  1435. );
  1436. } catch (Error re) {
  1437. String classDebugInfo = null;
  1438. try {
  1439. classDebugInfo = clazz.toLongString();
  1440. } catch (Exception e) {
  1441. // recover from crash whilst producing debug string
  1442. classDebugInfo = clazz.getClassName();
  1443. }
  1444. String messageText = "trouble in: \n" + classDebugInfo;
  1445. getWorld().getMessageHandler().handleMessage(
  1446. new Message(messageText,IMessage.ABORT,re,null)
  1447. );
  1448. }
  1449. }
  1450. // this is very odd return behavior trying to keep everyone happy
  1451. if (dump) {
  1452. dumpUnchanged(classFile);
  1453. return clazz;
  1454. } else {
  1455. // ATAJ: the class was not weaved, but since it gets there early it may have new generated inner classes
  1456. // attached to it to support LTW perX aspectOf support (see BcelPerClauseAspectAdder)
  1457. // that aggressively defines the inner <aspect>$mayHaveAspect interface.
  1458. if (clazz != null && !clazz.getChildClasses(world).isEmpty()) {
  1459. return clazz;
  1460. }
  1461. return null;
  1462. }
  1463. }
  1464. // ---- writing
  1465. private void dumpUnchanged(UnwovenClassFile classFile) throws IOException {
  1466. if (zipOutputStream != null) {
  1467. writeZipEntry(getEntryName(classFile.getJavaClass().getClassName()), classFile.getBytes());
  1468. } else {
  1469. classFile.writeUnchangedBytes();
  1470. }
  1471. }
  1472. private String getEntryName(String className) {
  1473. //XXX what does bcel's getClassName do for inner names
  1474. return className.replace('.', '/') + ".class";
  1475. }
  1476. private void dump(UnwovenClassFile classFile, LazyClassGen clazz) throws IOException {
  1477. if (zipOutputStream != null) {
  1478. String mainClassName = classFile.getJavaClass().getClassName();
  1479. writeZipEntry(getEntryName(mainClassName),
  1480. clazz.getJavaClass(world).getBytes());
  1481. if (!clazz.getChildClasses(world).isEmpty()) {
  1482. for (Iterator i = clazz.getChildClasses(world).iterator(); i.hasNext();) {
  1483. UnwovenClassFile.ChildClass c = (UnwovenClassFile.ChildClass) i.next();
  1484. writeZipEntry(getEntryName(mainClassName + "$" + c.name), c.bytes);
  1485. }
  1486. }
  1487. } else {
  1488. classFile.writeWovenBytes(
  1489. clazz.getJavaClass(world).getBytes(),
  1490. clazz.getChildClasses(world)
  1491. );
  1492. }
  1493. }
  1494. private void writeZipEntry(String name, byte[] bytes) throws IOException {
  1495. ZipEntry newEntry = new ZipEntry(name); //??? get compression scheme right
  1496. zipOutputStream.putNextEntry(newEntry);
  1497. zipOutputStream.write(bytes);
  1498. zipOutputStream.closeEntry();
  1499. }
  1500. private List fastMatch(List list, ResolvedType type) {
  1501. if (list == null) return Collections.EMPTY_LIST;
  1502. // here we do the coarsest grained fast match with no kind constraints
  1503. // this will remove all obvious non-matches and see if we need to do any weaving
  1504. FastMatchInfo info = new FastMatchInfo(type, null);
  1505. List result = new ArrayList();
  1506. Iterator iter = list.iterator();
  1507. while (iter.hasNext()) {
  1508. ShadowMunger munger = (ShadowMunger)iter.next();
  1509. FuzzyBoolean fb = munger.getPointcut().fastMatch(info);
  1510. WeaverMetrics.recordFastMatchTypeResult(fb); // Could pass: munger.getPointcut().toString(),info
  1511. if (fb.maybeTrue()) {
  1512. result.add(munger);
  1513. }
  1514. }
  1515. return result;
  1516. }
  1517. public void setProgressListener(IProgressListener listener, double previousProgress, double progressPerClassFile) {
  1518. progressListener = listener;
  1519. this.progressMade = previousProgress;
  1520. this.progressPerClassFile = progressPerClassFile;
  1521. }
  1522. public void setReweavableMode(boolean xNotReweavable) {
  1523. if (trace.isTraceEnabled()) trace.enter("setReweavableMode",this,xNotReweavable);
  1524. inReweavableMode = !xNotReweavable;
  1525. WeaverStateInfo.setReweavableModeDefaults(!xNotReweavable,false,true);
  1526. BcelClassWeaver.setReweavableMode(!xNotReweavable);
  1527. if (trace.isTraceEnabled()) trace.exit("setReweavableMode");
  1528. }
  1529. public boolean isReweavable() {
  1530. return inReweavableMode;
  1531. }
  1532. public World getWorld() {
  1533. return world;
  1534. }
  1535. public void tidyUp() {
  1536. if (trace.isTraceEnabled()) trace.enter("tidyUp",this);
  1537. shadowMungerList = null; // setup by prepareForWeave
  1538. typeMungerList = null; // setup by prepareForWeave
  1539. lateTypeMungerList = null; // setup by prepareForWeave
  1540. declareParentsList = null; // setup by prepareForWeave
  1541. if (trace.isTraceEnabled()) trace.exit("tidyUp");
  1542. }
  1543. }