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.

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