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

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