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

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