You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

BcelWeaver.java 75KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035
  1. /* *******************************************************************
  2. * Copyright (c) 2002-2010 Contributors
  3. * All rights reserved.
  4. * This program and the accompanying materials are made available
  5. * under the terms of the Eclipse Public License v 2.0
  6. * which accompanies this distribution and is available at
  7. * https://www.eclipse.org/org/documents/epl-2.0/EPL-2.0.txt
  8. * ******************************************************************/
  9. package org.aspectj.weaver.bcel;
  10. import java.io.ByteArrayInputStream;
  11. import java.io.File;
  12. import java.io.FileFilter;
  13. import java.io.FileInputStream;
  14. import java.io.FileNotFoundException;
  15. import java.io.IOException;
  16. import java.io.InputStream;
  17. import java.io.OutputStream;
  18. import java.util.ArrayList;
  19. import java.util.Collection;
  20. import java.util.Collections;
  21. import java.util.Comparator;
  22. import java.util.Enumeration;
  23. import java.util.HashMap;
  24. import java.util.HashSet;
  25. import java.util.Iterator;
  26. import java.util.List;
  27. import java.util.Map;
  28. import java.util.Set;
  29. import java.util.jar.Attributes;
  30. import java.util.jar.Attributes.Name;
  31. import java.util.jar.JarEntry;
  32. import java.util.jar.JarFile;
  33. import java.util.jar.Manifest;
  34. import java.util.zip.ZipEntry;
  35. import java.util.zip.ZipInputStream;
  36. import java.util.zip.ZipOutputStream;
  37. import org.aspectj.apache.bcel.classfile.ClassParser;
  38. import org.aspectj.apache.bcel.classfile.JavaClass;
  39. import org.aspectj.asm.AsmManager;
  40. import org.aspectj.asm.IProgramElement;
  41. import org.aspectj.asm.internal.AspectJElementHierarchy;
  42. import org.aspectj.bridge.IMessage;
  43. import org.aspectj.bridge.ISourceLocation;
  44. import org.aspectj.bridge.Message;
  45. import org.aspectj.bridge.MessageUtil;
  46. import org.aspectj.bridge.SourceLocation;
  47. import org.aspectj.bridge.WeaveMessage;
  48. import org.aspectj.bridge.context.CompilationAndWeavingContext;
  49. import org.aspectj.bridge.context.ContextToken;
  50. import org.aspectj.util.FileUtil;
  51. import org.aspectj.util.FuzzyBoolean;
  52. import org.aspectj.weaver.Advice;
  53. import org.aspectj.weaver.AdviceKind;
  54. import org.aspectj.weaver.AnnotationAJ;
  55. import org.aspectj.weaver.AnnotationOnTypeMunger;
  56. import org.aspectj.weaver.BCException;
  57. import org.aspectj.weaver.CompressingDataOutputStream;
  58. import org.aspectj.weaver.ConcreteTypeMunger;
  59. import org.aspectj.weaver.CrosscuttingMembersSet;
  60. import org.aspectj.weaver.CustomMungerFactory;
  61. import org.aspectj.weaver.IClassFileProvider;
  62. import org.aspectj.weaver.IUnwovenClassFile;
  63. import org.aspectj.weaver.IWeaveRequestor;
  64. import org.aspectj.weaver.NewParentTypeMunger;
  65. import org.aspectj.weaver.ReferenceType;
  66. import org.aspectj.weaver.ReferenceTypeDelegate;
  67. import org.aspectj.weaver.ResolvedType;
  68. import org.aspectj.weaver.ResolvedTypeMunger;
  69. import org.aspectj.weaver.Shadow;
  70. import org.aspectj.weaver.ShadowMunger;
  71. import org.aspectj.weaver.UnresolvedType;
  72. import org.aspectj.weaver.WeaverMessages;
  73. import org.aspectj.weaver.WeaverStateInfo;
  74. import org.aspectj.weaver.World;
  75. import org.aspectj.weaver.model.AsmRelationshipProvider;
  76. import org.aspectj.weaver.patterns.AndPointcut;
  77. import org.aspectj.weaver.patterns.BindingPattern;
  78. import org.aspectj.weaver.patterns.BindingTypePattern;
  79. import org.aspectj.weaver.patterns.ConcreteCflowPointcut;
  80. import org.aspectj.weaver.patterns.DeclareAnnotation;
  81. import org.aspectj.weaver.patterns.DeclareParents;
  82. import org.aspectj.weaver.patterns.DeclareTypeErrorOrWarning;
  83. import org.aspectj.weaver.patterns.FastMatchInfo;
  84. import org.aspectj.weaver.patterns.IfPointcut;
  85. import org.aspectj.weaver.patterns.KindedPointcut;
  86. import org.aspectj.weaver.patterns.NameBindingPointcut;
  87. import org.aspectj.weaver.patterns.NotPointcut;
  88. import org.aspectj.weaver.patterns.OrPointcut;
  89. import org.aspectj.weaver.patterns.Pointcut;
  90. import org.aspectj.weaver.patterns.PointcutRewriter;
  91. import org.aspectj.weaver.patterns.WithinPointcut;
  92. import org.aspectj.weaver.tools.Trace;
  93. import org.aspectj.weaver.tools.TraceFactory;
  94. /**
  95. *
  96. * @author PARC
  97. * @author Andy Clement
  98. * @author Alexandre Vasseur
  99. */
  100. public class BcelWeaver {
  101. public static final String CLOSURE_CLASS_PREFIX = "$Ajc";
  102. public static final String SYNTHETIC_CLASS_POSTFIX = "$ajc";
  103. private static Trace trace = TraceFactory.getTraceFactory().getTrace(BcelWeaver.class);
  104. private transient final BcelWorld world;
  105. private final CrosscuttingMembersSet xcutSet;
  106. private boolean inReweavableMode = false;
  107. private transient List<UnwovenClassFile> addedClasses = new ArrayList<>();
  108. private transient List<String> deletedTypenames = new ArrayList<>();
  109. // These four are setup by prepareForWeave
  110. private transient List<ShadowMunger> shadowMungerList = null;
  111. private transient List<ConcreteTypeMunger> typeMungerList = null;
  112. private transient List<ConcreteTypeMunger> lateTypeMungerList = null;
  113. private transient List<DeclareParents> declareParentsList = null;
  114. private Manifest manifest = null;
  115. private boolean needToReweaveWorld = false;
  116. private boolean isBatchWeave = true;
  117. private ZipOutputStream zipOutputStream;
  118. private CustomMungerFactory customMungerFactory;
  119. public BcelWeaver(BcelWorld world) {
  120. super();
  121. if (trace.isTraceEnabled()) {
  122. trace.enter("<init>", this, world);
  123. }
  124. this.world = world;
  125. this.xcutSet = world.getCrosscuttingMembersSet();
  126. if (trace.isTraceEnabled()) {
  127. trace.exit("<init>");
  128. }
  129. }
  130. /**
  131. * Add the given aspect to the weaver. The type is resolved to support DOT for static inner classes as well as DOLLAR
  132. *
  133. * @param aspectName
  134. * @return aspect
  135. */
  136. public ResolvedType addLibraryAspect(String aspectName) {
  137. if (trace.isTraceEnabled()) {
  138. trace.enter("addLibraryAspect", this, aspectName);
  139. }
  140. // 1 - resolve as is
  141. UnresolvedType unresolvedT = UnresolvedType.forName(aspectName);
  142. unresolvedT.setNeedsModifiableDelegate(true);
  143. ResolvedType type = world.resolve(unresolvedT, true);
  144. if (type.isMissing()) {
  145. // fallback on inner class lookup mechanism
  146. String fixedName = aspectName;
  147. int hasDot = fixedName.lastIndexOf('.');
  148. while (hasDot > 0) {
  149. // System.out.println("BcelWeaver.addLibraryAspect " + fixedName);
  150. char[] fixedNameChars = fixedName.toCharArray();
  151. fixedNameChars[hasDot] = '$';
  152. fixedName = new String(fixedNameChars);
  153. hasDot = fixedName.lastIndexOf('.');
  154. UnresolvedType ut = UnresolvedType.forName(fixedName);
  155. ut.setNeedsModifiableDelegate(true);
  156. type = world.resolve(ut, true);
  157. if (!type.isMissing()) {
  158. break;
  159. }
  160. }
  161. }
  162. // System.out.println("type: " + type + " for " + aspectName);
  163. if (type.isAspect()) {
  164. // Bug 119657 ensure we use the unwoven aspect
  165. WeaverStateInfo wsi = type.getWeaverState();
  166. if (wsi != null && wsi.isReweavable()) {
  167. BcelObjectType classType = getClassType(type.getName());
  168. JavaClass wovenJavaClass = classType.getJavaClass();
  169. byte[] bytes = wsi.getUnwovenClassFileData(wovenJavaClass.getBytes());
  170. JavaClass unwovenJavaClass = Utility.makeJavaClass(wovenJavaClass.getFileName(), bytes);
  171. world.storeClass(unwovenJavaClass);
  172. classType.setJavaClass(unwovenJavaClass, true);
  173. // classType.setJavaClass(Utility.makeJavaClass(classType.
  174. // getJavaClass().getFileName(),
  175. // wsi.getUnwovenClassFileData(classType.getJavaClass().getBytes(
  176. // ))));
  177. }
  178. // TODO AV - happens to reach that a lot of time: for each type
  179. // flagged reweavable X for each aspect in the weaverstate
  180. // => mainly for nothing for LTW - pbly for something in incremental
  181. // build...
  182. xcutSet.addOrReplaceAspect(type);
  183. if (trace.isTraceEnabled()) {
  184. trace.exit("addLibraryAspect", type);
  185. }
  186. if (type.getSuperclass().isAspect()) {
  187. // If the supertype includes ITDs and the user has not included
  188. // that aspect in the aop.xml, they will
  189. // not get picked up, which can give unusual behaviour! See bug
  190. // 223094
  191. // This change causes us to pick up the super aspect regardless
  192. // of what was said in the aop.xml - giving
  193. // predictable behaviour. If the user also supplied it, there
  194. // will be no problem other than the second
  195. // addition overriding the first
  196. addLibraryAspect(type.getSuperclass().getName());
  197. }
  198. return type;
  199. } else {
  200. if (type.isMissing()) {
  201. // May not be found if not visible to the classloader that can see the aop.xml during LTW
  202. IMessage message = new Message("The specified aspect '"+aspectName+"' cannot be found", null, true);
  203. world.getMessageHandler().handleMessage(message);
  204. } else {
  205. IMessage message = new Message("Cannot register '"+aspectName+"' because the type found with that name is not an aspect", null, true);
  206. world.getMessageHandler().handleMessage(message);
  207. }
  208. return null;
  209. }
  210. }
  211. /**
  212. *
  213. * @param inFile directory containing classes or zip/jar class archive
  214. */
  215. public void addLibraryJarFile(File inFile) throws IOException {
  216. List<ResolvedType> addedAspects = null;
  217. if (inFile.isDirectory()) {
  218. addedAspects = addAspectsFromDirectory(inFile);
  219. } else {
  220. addedAspects = addAspectsFromJarFile(inFile);
  221. }
  222. for (ResolvedType addedAspect : addedAspects) {
  223. xcutSet.addOrReplaceAspect(addedAspect);
  224. }
  225. }
  226. private List<ResolvedType> addAspectsFromJarFile(File inFile) throws FileNotFoundException, IOException {
  227. ZipInputStream inStream = new ZipInputStream(new FileInputStream(inFile)); // ??? buffered
  228. List<ResolvedType> addedAspects = new ArrayList<>();
  229. try {
  230. while (true) {
  231. ZipEntry entry = inStream.getNextEntry();
  232. if (entry == null) {
  233. break;
  234. }
  235. if (entry.isDirectory() || !entry.getName().endsWith(".class")) {
  236. continue;
  237. }
  238. // FIXME ASC performance? of this alternative soln.
  239. int size = (int) entry.getSize();
  240. ClassParser parser = new ClassParser(new ByteArrayInputStream(FileUtil.readAsByteArray(inStream)), entry.getName());
  241. JavaClass jc = parser.parse();
  242. inStream.closeEntry();
  243. ResolvedType type = world.addSourceObjectType(jc, false).getResolvedTypeX();
  244. type.setBinaryPath(inFile.getAbsolutePath());
  245. if (type.isAspect()) {
  246. addedAspects.add(type);
  247. } else {
  248. world.demote(type);
  249. }
  250. }
  251. } finally {
  252. inStream.close();
  253. }
  254. return addedAspects;
  255. }
  256. /**
  257. * Look for .class files that represent aspects in the supplied directory - return the list of accumulated aspects.
  258. *
  259. * @param directory the directory in which to look for Aspect .class files
  260. * @return the list of discovered aspects
  261. * @throws FileNotFoundException
  262. * @throws IOException
  263. */
  264. private List<ResolvedType> addAspectsFromDirectory(File directory) throws FileNotFoundException, IOException {
  265. List<ResolvedType> addedAspects = new ArrayList<>();
  266. File[] classFiles = FileUtil.listFiles(directory, new FileFilter() {
  267. public boolean accept(File pathname) {
  268. return pathname.getName().endsWith(".class");
  269. }
  270. });
  271. for (File classFile : classFiles) {
  272. FileInputStream fis = new FileInputStream(classFile);
  273. byte[] classBytes = FileUtil.readAsByteArray(fis);
  274. ResolvedType aspectType = isAspect(classBytes, classFile.getAbsolutePath(), directory);
  275. if (aspectType != null) {
  276. addedAspects.add(aspectType);
  277. }
  278. fis.close();
  279. }
  280. return addedAspects;
  281. }
  282. /**
  283. * Determine if the supplied bytes represent an aspect, if they do then create a ResolvedType instance for the aspect and return
  284. * it, otherwise return null
  285. *
  286. * @param classbytes the classbytes that might represent an aspect
  287. * @param name the name of the class
  288. * @param directory directory which contained the class file
  289. * @return a ResolvedType if the classbytes represent an aspect, otherwise null
  290. */
  291. private ResolvedType isAspect(byte[] classbytes, String name, File dir) throws IOException {
  292. ClassParser parser = new ClassParser(new ByteArrayInputStream(classbytes), name);
  293. JavaClass jc = parser.parse();
  294. ResolvedType type = world.addSourceObjectType(jc, false).getResolvedTypeX();
  295. String typeName = type.getName().replace('.', File.separatorChar);
  296. int end = name.lastIndexOf(typeName + ".class");
  297. String binaryPath = null;
  298. // if end is -1 then something weird happened, the class file is not in
  299. // the correct place, something like
  300. // bin/A.class when the declaration for A specifies it is in a package.
  301. if (end == -1) {
  302. binaryPath = dir.getAbsolutePath();
  303. } else {
  304. binaryPath = name.substring(0, end - 1);
  305. }
  306. type.setBinaryPath(binaryPath);
  307. if (type.isAspect()) {
  308. return type;
  309. } else {
  310. // immediately demote the type we just added since it will have
  311. // have been stuffed into the permanent map (assumed to be
  312. // an aspect)
  313. world.demote(type);
  314. return null;
  315. }
  316. }
  317. // // The ANT copy task should be used to copy resources across.
  318. // private final static boolean
  319. // CopyResourcesFromInpathDirectoriesToOutput=false;
  320. /**
  321. * Add any .class files in the directory to the outdir. Anything other than .class files in the directory (or its
  322. * subdirectories) are considered resources and are also copied.
  323. *
  324. */
  325. public List<UnwovenClassFile> addDirectoryContents(File inFile, File outDir) throws IOException {
  326. List<UnwovenClassFile> addedClassFiles = new ArrayList<>();
  327. // Get a list of all files (i.e. everything that isnt a directory)
  328. File[] files = FileUtil.listFiles(inFile, new FileFilter() {
  329. public boolean accept(File f) {
  330. boolean accept = !f.isDirectory();
  331. return accept;
  332. }
  333. });
  334. // For each file, add it either as a real .class file or as a resource
  335. for (File file : files) {
  336. addedClassFiles.add(addClassFile(file, inFile, outDir));
  337. }
  338. return addedClassFiles;
  339. }
  340. /**
  341. * Adds all class files in the jar
  342. */
  343. public List<UnwovenClassFile> addJarFile(File inFile, File outDir, boolean canBeDirectory) {
  344. // System.err.println("? addJarFile(" + inFile + ", " + outDir + ")");
  345. List<UnwovenClassFile> addedClassFiles = new ArrayList<>();
  346. needToReweaveWorld = true;
  347. JarFile inJar = null;
  348. try {
  349. // Is this a directory we are looking at?
  350. if (inFile.isDirectory() && canBeDirectory) {
  351. addedClassFiles.addAll(addDirectoryContents(inFile, outDir));
  352. } else {
  353. inJar = new JarFile(inFile);
  354. try {
  355. addManifest(inJar.getManifest());
  356. Enumeration<JarEntry> entries = inJar.entries();
  357. while (entries.hasMoreElements()) {
  358. JarEntry entry = entries.nextElement();
  359. InputStream inStream = inJar.getInputStream(entry);
  360. byte[] bytes = FileUtil.readAsByteArray(inStream);
  361. String filename = entry.getName();
  362. // System.out.println("? addJarFile() filename='" + filename
  363. // + "'");
  364. UnwovenClassFile classFile = new UnwovenClassFile(new File(outDir, filename).getAbsolutePath(), bytes);
  365. if (filename.endsWith(".class")) {
  366. ReferenceType type = this.addClassFile(classFile, false);
  367. StringBuilder sb = new StringBuilder();
  368. sb.append(inFile.getAbsolutePath());
  369. sb.append("!");
  370. sb.append(entry.getName());
  371. type.setBinaryPath(sb.toString());
  372. addedClassFiles.add(classFile);
  373. }
  374. // else if (!entry.isDirectory()) {
  375. //
  376. // /* bug-44190 Copy meta-data */
  377. // addResource(filename,classFile);
  378. // }
  379. inStream.close();
  380. }
  381. } finally {
  382. inJar.close();
  383. }
  384. inJar.close();
  385. }
  386. } catch (FileNotFoundException ex) {
  387. IMessage message = new Message("Could not find input jar file " + inFile.getPath() + ", ignoring", new SourceLocation(
  388. inFile, 0), false);
  389. world.getMessageHandler().handleMessage(message);
  390. } catch (IOException ex) {
  391. IMessage message = new Message("Could not read input jar file " + inFile.getPath() + "(" + ex.getMessage() + ")",
  392. new SourceLocation(inFile, 0), true);
  393. world.getMessageHandler().handleMessage(message);
  394. } finally {
  395. if (inJar != null) {
  396. try {
  397. inJar.close();
  398. } catch (IOException ex) {
  399. IMessage message = new Message("Could not close input jar file " + inFile.getPath() + "(" + ex.getMessage()
  400. + ")", new SourceLocation(inFile, 0), true);
  401. world.getMessageHandler().handleMessage(message);
  402. }
  403. }
  404. }
  405. return addedClassFiles;
  406. }
  407. public boolean needToReweaveWorld() {
  408. return needToReweaveWorld;
  409. }
  410. /**
  411. * Should be addOrReplace
  412. */
  413. public ReferenceType addClassFile(UnwovenClassFile classFile, boolean fromInpath) {
  414. addedClasses.add(classFile);
  415. ReferenceType type = world.addSourceObjectType(classFile.getJavaClass(), false).getResolvedTypeX();
  416. if (fromInpath) {
  417. type.setBinaryPath(classFile.getFilename());
  418. }
  419. return type;
  420. }
  421. public UnwovenClassFile addClassFile(File classFile, File inPathDir, File outDir) throws IOException {
  422. FileInputStream fis = new FileInputStream(classFile);
  423. byte[] bytes = FileUtil.readAsByteArray(fis);
  424. // String relativePath = files[i].getPath();
  425. // ASSERT:
  426. // files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath()
  427. // or we are in trouble...
  428. String filename = classFile.getAbsolutePath().substring(inPathDir.getAbsolutePath().length() + 1);
  429. UnwovenClassFile ucf = new UnwovenClassFile(new File(outDir, filename).getAbsolutePath(), bytes);
  430. if (filename.endsWith(".class")) {
  431. // System.err.println(
  432. // "BCELWeaver: processing class from input directory "+classFile);
  433. StringBuilder sb = new StringBuilder();
  434. sb.append(inPathDir.getAbsolutePath());
  435. sb.append("!");
  436. sb.append(filename);
  437. ReferenceType type = this.addClassFile(ucf, false);
  438. type.setBinaryPath(sb.toString());
  439. }
  440. fis.close();
  441. return ucf;
  442. }
  443. public void deleteClassFile(String typename) {
  444. deletedTypenames.add(typename);
  445. world.deleteSourceObjectType(UnresolvedType.forName(typename));
  446. }
  447. // ---- weave preparation
  448. public void setIsBatchWeave(boolean b) {
  449. isBatchWeave = b;
  450. }
  451. public void prepareForWeave() {
  452. if (trace.isTraceEnabled()) {
  453. trace.enter("prepareForWeave", this);
  454. }
  455. needToReweaveWorld = xcutSet.hasChangedSinceLastReset();
  456. // update mungers
  457. for (UnwovenClassFile jc : addedClasses) {
  458. String name = jc.getClassName();
  459. ResolvedType type = world.resolve(name);
  460. // No overweaving guard. If you have one then when overweaving is on the
  461. // addOrReplaceAspect will not be called when the aspect delegate changes from
  462. // EclipseSourceType to BcelObjectType. This will mean the mungers
  463. // are not picked up.
  464. if (type.isAspect()) {
  465. needToReweaveWorld |= xcutSet.addOrReplaceAspect(type);
  466. }
  467. }
  468. for (String name : deletedTypenames) {
  469. if (xcutSet.deleteAspect(UnresolvedType.forName(name))) {
  470. needToReweaveWorld = true;
  471. }
  472. }
  473. shadowMungerList = xcutSet.getShadowMungers();
  474. // world.debug("shadow mungers=" + shadowMungerList);
  475. rewritePointcuts(shadowMungerList);
  476. // Sometimes an error occurs during rewriting pointcuts (for example, if
  477. // ambiguous bindings
  478. // are detected) - we ought to fail the prepare when this happens
  479. // because continuing with
  480. // inconsistent pointcuts could lead to problems
  481. typeMungerList = xcutSet.getTypeMungers();
  482. lateTypeMungerList = xcutSet.getLateTypeMungers();
  483. declareParentsList = xcutSet.getDeclareParents();
  484. addCustomMungers();
  485. // The ordering here used to be based on a string compare on toString()
  486. // for the two mungers -
  487. // that breaks for the @AJ style where advice names aren't
  488. // programmatically generated. So we
  489. // have changed the sorting to be based on source location in the file -
  490. // this is reliable, in
  491. // the case of source locations missing, we assume they are 'sorted' -
  492. // i.e. the order in
  493. // which they were added to the collection is correct, this enables the
  494. // @AJ stuff to work properly.
  495. // When @AJ processing starts filling in source locations for mungers,
  496. // this code may need
  497. // a bit of alteration...
  498. shadowMungerList.sort(new Comparator<ShadowMunger>() {
  499. public int compare(ShadowMunger sm1, ShadowMunger sm2) {
  500. if (sm1.getSourceLocation() == null) {
  501. return (sm2.getSourceLocation() == null ? 0 : 1);
  502. }
  503. if (sm2.getSourceLocation() == null) {
  504. return -1;
  505. }
  506. return (sm2.getSourceLocation().getOffset() - sm1.getSourceLocation().getOffset());
  507. }
  508. });
  509. if (inReweavableMode) {
  510. world.showMessage(IMessage.INFO, WeaverMessages.format(WeaverMessages.REWEAVABLE_MODE), null, null);
  511. }
  512. if (trace.isTraceEnabled()) {
  513. trace.exit("prepareForWeave");
  514. }
  515. }
  516. private void addCustomMungers() {
  517. if (customMungerFactory != null) {
  518. for (UnwovenClassFile jc : addedClasses) {
  519. String name = jc.getClassName();
  520. ResolvedType type = world.resolve(name);
  521. if (type.isAspect()) {
  522. Collection<ShadowMunger> shadowMungers = customMungerFactory.createCustomShadowMungers(type);
  523. if (shadowMungers != null) {
  524. shadowMungerList.addAll(shadowMungers);
  525. }
  526. Collection<ConcreteTypeMunger> typeMungers = customMungerFactory.createCustomTypeMungers(type);
  527. if (typeMungers != null) {
  528. typeMungerList.addAll(typeMungers);
  529. }
  530. }
  531. }
  532. }
  533. }
  534. public void setCustomMungerFactory(CustomMungerFactory factory) {
  535. customMungerFactory = factory;
  536. }
  537. /*
  538. * Rewrite all of the pointcuts in the world into their most efficient form for subsequent matching. Also ensure that if
  539. * pc1.equals(pc2) then pc1 == pc2 (for non-binding pcds) by making references all point to the same instance. Since pointcuts
  540. * remember their match decision on the last shadow, this makes matching faster when many pointcuts share common elements, or
  541. * even when one single pointcut has one common element (which can be a side-effect of DNF rewriting).
  542. */
  543. private void rewritePointcuts(List<ShadowMunger> shadowMungers) {
  544. PointcutRewriter rewriter = new PointcutRewriter();
  545. for (ShadowMunger munger : shadowMungers) {
  546. Pointcut p = munger.getPointcut();
  547. Pointcut newP = rewriter.rewrite(p);
  548. // validateBindings now whilst we still have around the pointcut
  549. // that resembles what the user actually wrote in their program
  550. // text.
  551. if (munger instanceof Advice) {
  552. Advice advice = (Advice) munger;
  553. if (advice.getSignature() != null) {
  554. final int numFormals;
  555. final String names[];
  556. // If the advice is being concretized in a @AJ aspect *and*
  557. // the advice was declared in
  558. // an @AJ aspect (it could have been inherited from a code
  559. // style aspect) then
  560. // evaluate the alternative set of formals. pr125699
  561. if ((advice.getConcreteAspect().isAnnotationStyleAspect() && advice.getDeclaringAspect() != null && advice
  562. .getDeclaringAspect().resolve(world).isAnnotationStyleAspect())
  563. || advice.isAnnotationStyle()) {
  564. numFormals = advice.getBaseParameterCount();
  565. int numArgs = advice.getSignature().getParameterTypes().length;
  566. if (numFormals > 0) {
  567. names = advice.getSignature().getParameterNames(world);
  568. validateBindings(newP, p, numArgs, names);
  569. }
  570. } else {
  571. numFormals = advice.getBaseParameterCount();
  572. if (numFormals > 0) {
  573. names = advice.getBaseParameterNames(world);
  574. validateBindings(newP, p, numFormals, names);
  575. }
  576. }
  577. }
  578. }
  579. newP.m_ignoreUnboundBindingForNames = p.m_ignoreUnboundBindingForNames;
  580. munger.setPointcut(newP);
  581. }
  582. // now that we have optimized individual pointcuts, optimize
  583. // across the set of pointcuts....
  584. // Use a map from key based on pc equality, to value based on
  585. // pc identity.
  586. Map<Pointcut, Pointcut> pcMap = new HashMap<>();
  587. for (ShadowMunger munger: shadowMungers) {
  588. Pointcut p = munger.getPointcut();
  589. Pointcut newP = shareEntriesFromMap(p, pcMap);
  590. newP.m_ignoreUnboundBindingForNames = p.m_ignoreUnboundBindingForNames;
  591. munger.setPointcut(newP);
  592. }
  593. }
  594. private Pointcut shareEntriesFromMap(Pointcut p, Map<Pointcut, Pointcut> pcMap) {
  595. // some things cant be shared...
  596. if (p instanceof NameBindingPointcut) {
  597. return p;
  598. }
  599. if (p instanceof IfPointcut) {
  600. return p;
  601. }
  602. if (p instanceof ConcreteCflowPointcut) {
  603. return p;
  604. }
  605. if (p instanceof AndPointcut) {
  606. AndPointcut apc = (AndPointcut) p;
  607. Pointcut left = shareEntriesFromMap(apc.getLeft(), pcMap);
  608. Pointcut right = shareEntriesFromMap(apc.getRight(), pcMap);
  609. return new AndPointcut(left, right);
  610. } else if (p instanceof OrPointcut) {
  611. OrPointcut opc = (OrPointcut) p;
  612. Pointcut left = shareEntriesFromMap(opc.getLeft(), pcMap);
  613. Pointcut right = shareEntriesFromMap(opc.getRight(), pcMap);
  614. return new OrPointcut(left, right);
  615. } else if (p instanceof NotPointcut) {
  616. NotPointcut npc = (NotPointcut) p;
  617. Pointcut not = shareEntriesFromMap(npc.getNegatedPointcut(), pcMap);
  618. return new NotPointcut(not);
  619. } else {
  620. // primitive pcd
  621. if (pcMap.containsKey(p)) { // based on equality
  622. return pcMap.get(p); // same instance (identity)
  623. } else {
  624. pcMap.put(p, p);
  625. return p;
  626. }
  627. }
  628. }
  629. // userPointcut is the pointcut that the user wrote in the program text.
  630. // dnfPointcut is the same pointcut rewritten in DNF
  631. // numFormals is the number of formal parameters in the pointcut
  632. // if numFormals > 0 then every branch of a disjunction must bind each
  633. // formal once and only once.
  634. // in addition, the left and right branches of a disjunction must hold on
  635. // join point kinds in common.
  636. private void validateBindings(Pointcut dnfPointcut, Pointcut userPointcut, int numFormals, String[] names) {
  637. if (numFormals == 0) {
  638. return; // nothing to check
  639. }
  640. if (dnfPointcut.couldMatchKinds() == Shadow.NO_SHADOW_KINDS_BITS) {
  641. return; // cant have problems if you dont match!
  642. }
  643. if (dnfPointcut instanceof OrPointcut) {
  644. OrPointcut orBasedDNFPointcut = (OrPointcut) dnfPointcut;
  645. Pointcut[] leftBindings = new Pointcut[numFormals];
  646. Pointcut[] rightBindings = new Pointcut[numFormals];
  647. validateOrBranch(orBasedDNFPointcut, userPointcut, numFormals, names, leftBindings, rightBindings);
  648. } else {
  649. Pointcut[] bindings = new Pointcut[numFormals];
  650. validateSingleBranch(dnfPointcut, userPointcut, numFormals, names, bindings);
  651. }
  652. }
  653. private void validateOrBranch(OrPointcut pc, Pointcut userPointcut, int numFormals, String[] names, Pointcut[] leftBindings,
  654. Pointcut[] rightBindings) {
  655. Pointcut left = pc.getLeft();
  656. Pointcut right = pc.getRight();
  657. if (left instanceof OrPointcut) {
  658. Pointcut[] newRightBindings = new Pointcut[numFormals];
  659. validateOrBranch((OrPointcut) left, userPointcut, numFormals, names, leftBindings, newRightBindings);
  660. } else {
  661. if (left.couldMatchKinds() != Shadow.NO_SHADOW_KINDS_BITS) {
  662. validateSingleBranch(left, userPointcut, numFormals, names, leftBindings);
  663. }
  664. }
  665. if (right instanceof OrPointcut) {
  666. Pointcut[] newLeftBindings = new Pointcut[numFormals];
  667. validateOrBranch((OrPointcut) right, userPointcut, numFormals, names, newLeftBindings, rightBindings);
  668. } else {
  669. if (right.couldMatchKinds() != Shadow.NO_SHADOW_KINDS_BITS) {
  670. validateSingleBranch(right, userPointcut, numFormals, names, rightBindings);
  671. }
  672. }
  673. int kindsInCommon = left.couldMatchKinds() & right.couldMatchKinds();
  674. if (kindsInCommon != Shadow.NO_SHADOW_KINDS_BITS && couldEverMatchSameJoinPoints(left, right)) {
  675. // we know that every branch binds every formal, so there is no
  676. // ambiguity if each branch binds it in exactly the same way...
  677. List<String> ambiguousNames = new ArrayList<>();
  678. for (int i = 0; i < numFormals; i++) {
  679. if (leftBindings[i] == null) {
  680. if (rightBindings[i] != null) {
  681. ambiguousNames.add(names[i]);
  682. }
  683. } else if (!leftBindings[i].equals(rightBindings[i])) {
  684. ambiguousNames.add(names[i]);
  685. }
  686. }
  687. if (!ambiguousNames.isEmpty()) {
  688. raiseAmbiguityInDisjunctionError(userPointcut, ambiguousNames);
  689. }
  690. }
  691. }
  692. // pc is a pointcut that does not contain any disjunctions
  693. // check that every formal is bound (negation doesn't count).
  694. // we know that numFormals > 0 or else we would not be called
  695. private void validateSingleBranch(Pointcut pc, Pointcut userPointcut, int numFormals, String[] names, Pointcut[] bindings) {
  696. boolean[] foundFormals = new boolean[numFormals];
  697. for (int i = 0; i < foundFormals.length; i++) {
  698. foundFormals[i] = false;
  699. }
  700. validateSingleBranchRecursion(pc, userPointcut, foundFormals, names, bindings);
  701. for (int i = 0; i < foundFormals.length; i++) {
  702. if (!foundFormals[i]) {
  703. boolean ignore = false;
  704. // ATAJ soften the unbound error for implicit bindings like
  705. // JoinPoint in @AJ style
  706. for (int j = 0; j < userPointcut.m_ignoreUnboundBindingForNames.length; j++) {
  707. if (names[i] != null && names[i].equals(userPointcut.m_ignoreUnboundBindingForNames[j])) {
  708. ignore = true;
  709. break;
  710. }
  711. }
  712. if (!ignore) {
  713. raiseUnboundFormalError(names[i], userPointcut);
  714. }
  715. }
  716. }
  717. }
  718. // each formal must appear exactly once
  719. private void validateSingleBranchRecursion(Pointcut pc, Pointcut userPointcut, boolean[] foundFormals, String[] names,
  720. Pointcut[] bindings) {
  721. if (pc instanceof NotPointcut) {
  722. // nots can only appear at leaves in DNF
  723. NotPointcut not = (NotPointcut) pc;
  724. if (not.getNegatedPointcut() instanceof NameBindingPointcut) {
  725. NameBindingPointcut nnbp = (NameBindingPointcut) not.getNegatedPointcut();
  726. if (!nnbp.getBindingAnnotationTypePatterns().isEmpty() && !nnbp.getBindingTypePatterns().isEmpty()) {
  727. raiseNegationBindingError(userPointcut);
  728. }
  729. }
  730. } else if (pc instanceof AndPointcut) {
  731. AndPointcut and = (AndPointcut) pc;
  732. validateSingleBranchRecursion(and.getLeft(), userPointcut, foundFormals, names, bindings);
  733. validateSingleBranchRecursion(and.getRight(), userPointcut, foundFormals, names, bindings);
  734. } else if (pc instanceof NameBindingPointcut) {
  735. List<BindingTypePattern> bindingTypePatterns = ((NameBindingPointcut) pc).getBindingTypePatterns();
  736. for (BindingTypePattern bindingTypePattern: bindingTypePatterns) {
  737. int index = bindingTypePattern.getFormalIndex();
  738. bindings[index] = pc;
  739. if (foundFormals[index]) {
  740. raiseAmbiguousBindingError(names[index], userPointcut);
  741. } else {
  742. foundFormals[index] = true;
  743. }
  744. }
  745. List<BindingPattern> bindingAnnotationTypePatterns = ((NameBindingPointcut) pc).getBindingAnnotationTypePatterns();
  746. for (BindingPattern bindingAnnotationTypePattern: bindingAnnotationTypePatterns) {
  747. int index = bindingAnnotationTypePattern.getFormalIndex();
  748. bindings[index] = pc;
  749. if (foundFormals[index]) {
  750. raiseAmbiguousBindingError(names[index], userPointcut);
  751. } else {
  752. foundFormals[index] = true;
  753. }
  754. }
  755. } else if (pc instanceof ConcreteCflowPointcut) {
  756. ConcreteCflowPointcut cfp = (ConcreteCflowPointcut) pc;
  757. int[] slots = cfp.getUsedFormalSlots();
  758. for (int slot : slots) {
  759. bindings[slot] = cfp;
  760. if (foundFormals[slot]) {
  761. raiseAmbiguousBindingError(names[slot], userPointcut);
  762. } else {
  763. foundFormals[slot] = true;
  764. }
  765. }
  766. }
  767. }
  768. // By returning false from this method, we are allowing binding of the same
  769. // variable on either side of an or.
  770. // Be conservative :- have to consider overriding, varargs, autoboxing,
  771. // the effects of itds (on within for example), interfaces, the fact that
  772. // join points can have multiple signatures and so on.
  773. private boolean couldEverMatchSameJoinPoints(Pointcut left, Pointcut right) {
  774. if (left instanceof OrPointcut) {
  775. OrPointcut leftOrPointcut = (OrPointcut) left;
  776. if (couldEverMatchSameJoinPoints(leftOrPointcut.getLeft(), right)) {
  777. return true;
  778. }
  779. if (couldEverMatchSameJoinPoints(leftOrPointcut.getRight(), right)) {
  780. return true;
  781. }
  782. return false;
  783. }
  784. if (right instanceof OrPointcut) {
  785. OrPointcut rightOrPointcut = (OrPointcut) right;
  786. if (couldEverMatchSameJoinPoints(left, rightOrPointcut.getLeft())) {
  787. return true;
  788. }
  789. if (couldEverMatchSameJoinPoints(left, rightOrPointcut.getRight())) {
  790. return true;
  791. }
  792. return false;
  793. }
  794. // look for withins
  795. WithinPointcut leftWithin = (WithinPointcut) findFirstPointcutIn(left, WithinPointcut.class);
  796. WithinPointcut rightWithin = (WithinPointcut) findFirstPointcutIn(right, WithinPointcut.class);
  797. if ((leftWithin != null) && (rightWithin != null)) {
  798. if (!leftWithin.couldEverMatchSameJoinPointsAs(rightWithin)) {
  799. return false;
  800. }
  801. }
  802. // look for kinded
  803. KindedPointcut leftKind = (KindedPointcut) findFirstPointcutIn(left, KindedPointcut.class);
  804. KindedPointcut rightKind = (KindedPointcut) findFirstPointcutIn(right, KindedPointcut.class);
  805. if ((leftKind != null) && (rightKind != null)) {
  806. if (!leftKind.couldEverMatchSameJoinPointsAs(rightKind)) {
  807. return false;
  808. }
  809. }
  810. return true;
  811. }
  812. private Pointcut findFirstPointcutIn(Pointcut toSearch, Class<?> toLookFor) {
  813. if (toSearch instanceof NotPointcut) {
  814. return null;
  815. }
  816. if (toLookFor.isInstance(toSearch)) {
  817. return toSearch;
  818. }
  819. if (toSearch instanceof AndPointcut) {
  820. AndPointcut apc = (AndPointcut) toSearch;
  821. Pointcut left = findFirstPointcutIn(apc.getLeft(), toLookFor);
  822. if (left != null) {
  823. return left;
  824. }
  825. return findFirstPointcutIn(apc.getRight(), toLookFor);
  826. }
  827. return null;
  828. }
  829. /**
  830. * @param userPointcut
  831. */
  832. private void raiseNegationBindingError(Pointcut userPointcut) {
  833. world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.NEGATION_DOESNT_ALLOW_BINDING), userPointcut
  834. .getSourceContext().makeSourceLocation(userPointcut), null);
  835. }
  836. private void raiseAmbiguousBindingError(String name, Pointcut pointcut) {
  837. world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.AMBIGUOUS_BINDING, name), pointcut
  838. .getSourceContext().makeSourceLocation(pointcut), null);
  839. }
  840. /**
  841. * @param userPointcut
  842. */
  843. private void raiseAmbiguityInDisjunctionError(Pointcut userPointcut, List<String> names) {
  844. StringBuffer formalNames = new StringBuffer(names.get(0).toString());
  845. for (int i = 1; i < names.size(); i++) {
  846. formalNames.append(", ");
  847. formalNames.append(names.get(i));
  848. }
  849. world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.AMBIGUOUS_BINDING_IN_OR, formalNames), userPointcut
  850. .getSourceContext().makeSourceLocation(userPointcut), null);
  851. }
  852. /**
  853. * @param name
  854. * @param userPointcut
  855. */
  856. private void raiseUnboundFormalError(String name, Pointcut userPointcut) {
  857. world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.UNBOUND_FORMAL, name),
  858. userPointcut.getSourceLocation(), null);
  859. }
  860. public void addManifest(Manifest newManifest) {
  861. // System.out.println("? addManifest() newManifest=" + newManifest);
  862. if (manifest == null) {
  863. manifest = newManifest;
  864. }
  865. }
  866. public Manifest getManifest(boolean shouldCreate) {
  867. if (manifest == null && shouldCreate) {
  868. String WEAVER_MANIFEST_VERSION = "1.0";
  869. Attributes.Name CREATED_BY = new Name("Created-By");
  870. String WEAVER_CREATED_BY = "AspectJ Compiler";
  871. manifest = new Manifest();
  872. Attributes attributes = manifest.getMainAttributes();
  873. attributes.put(Name.MANIFEST_VERSION, WEAVER_MANIFEST_VERSION);
  874. attributes.put(CREATED_BY, WEAVER_CREATED_BY);
  875. }
  876. return manifest;
  877. }
  878. // ---- weaving
  879. // FOR TESTING
  880. public Collection<String> weave(File file) throws IOException {
  881. OutputStream os = FileUtil.makeOutputStream(file);
  882. this.zipOutputStream = new ZipOutputStream(os);
  883. prepareForWeave();
  884. Collection<String> c = weave(new IClassFileProvider() {
  885. public boolean isApplyAtAspectJMungersOnly() {
  886. return false;
  887. }
  888. public Iterator<UnwovenClassFile> getClassFileIterator() {
  889. return addedClasses.iterator();
  890. }
  891. public IWeaveRequestor getRequestor() {
  892. return new IWeaveRequestor() {
  893. public void acceptResult(IUnwovenClassFile result) {
  894. try {
  895. writeZipEntry(result.getFilename(), result.getBytes());
  896. } catch (IOException ex) {
  897. }
  898. }
  899. public void processingReweavableState() {
  900. }
  901. public void addingTypeMungers() {
  902. }
  903. public void weavingAspects() {
  904. }
  905. public void weavingClasses() {
  906. }
  907. public void weaveCompleted() {
  908. }
  909. };
  910. }
  911. });
  912. // /* BUG 40943*/
  913. // dumpResourcesToOutJar();
  914. zipOutputStream.close(); // this flushes and closes the acutal file
  915. return c;
  916. }
  917. private Set<IProgramElement> candidatesForRemoval = null;
  918. // variation of "weave" that sources class files from an external source.
  919. public Collection<String> weave(IClassFileProvider input) throws IOException {
  920. if (trace.isTraceEnabled()) {
  921. trace.enter("weave", this, input);
  922. }
  923. ContextToken weaveToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING, "");
  924. Collection<String> wovenClassNames = new ArrayList<>();
  925. IWeaveRequestor requestor = input.getRequestor();
  926. if (world.getModel() != null && world.isMinimalModel()) {
  927. candidatesForRemoval = new HashSet<>();
  928. }
  929. if (world.getModel() != null && !isBatchWeave) {
  930. AsmManager manager = world.getModelAsAsmManager();
  931. for (Iterator<UnwovenClassFile> i = input.getClassFileIterator(); i.hasNext();) {
  932. UnwovenClassFile classFile = i.next();
  933. // remove all relationships where this file being woven is
  934. // the target of the relationship
  935. manager.removeRelationshipsTargettingThisType(classFile.getClassName());
  936. }
  937. }
  938. // Go through the types and ensure any 'damaged' during compile time are
  939. // repaired prior to weaving
  940. for (Iterator<UnwovenClassFile> i = input.getClassFileIterator(); i.hasNext();) {
  941. UnwovenClassFile classFile = i.next();
  942. if (classFile.shouldBeWoven()) {
  943. String className = classFile.getClassName();
  944. ResolvedType theType = world.resolve(className);
  945. if (theType != null) {
  946. theType.ensureConsistent();
  947. }
  948. }
  949. }
  950. // special case for AtAspectJMungerOnly - see #113587
  951. if (input.isApplyAtAspectJMungersOnly()) {
  952. ContextToken atAspectJMungersOnly = CompilationAndWeavingContext.enteringPhase(
  953. CompilationAndWeavingContext.PROCESSING_ATASPECTJTYPE_MUNGERS_ONLY, "");
  954. requestor.weavingAspects();
  955. // ContextToken aspectToken =
  956. CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_ASPECTS, "");
  957. for (Iterator<UnwovenClassFile> i = input.getClassFileIterator(); i.hasNext();) {
  958. UnwovenClassFile classFile = i.next();
  959. if (classFile.shouldBeWoven()) {
  960. String className = classFile.getClassName();
  961. ResolvedType theType = world.resolve(className);
  962. if (theType.isAnnotationStyleAspect()) {
  963. BcelObjectType classType = BcelWorld.getBcelObjectType(theType);
  964. if (classType == null) {
  965. throw new BCException("Can't find bcel delegate for " + className + " type=" + theType.getClass());
  966. }
  967. LazyClassGen clazz = classType.getLazyClassGen();
  968. BcelPerClauseAspectAdder selfMunger = new BcelPerClauseAspectAdder(theType, theType.getPerClause().getKind());
  969. selfMunger.forceMunge(clazz, true);
  970. classType.finishedWith();
  971. UnwovenClassFile[] newClasses = getClassFilesFor(clazz);
  972. for (UnwovenClassFile newClass : newClasses) {
  973. requestor.acceptResult(newClass);
  974. }
  975. wovenClassNames.add(classFile.getClassName());
  976. }
  977. }
  978. }
  979. requestor.weaveCompleted();
  980. CompilationAndWeavingContext.leavingPhase(atAspectJMungersOnly);
  981. return wovenClassNames;
  982. }
  983. requestor.processingReweavableState();
  984. ContextToken reweaveToken = CompilationAndWeavingContext.enteringPhase(
  985. CompilationAndWeavingContext.PROCESSING_REWEAVABLE_STATE, "");
  986. prepareToProcessReweavableState();
  987. // clear all state from files we'll be reweaving
  988. for (Iterator<UnwovenClassFile> i = input.getClassFileIterator(); i.hasNext();) {
  989. UnwovenClassFile classFile = i.next();
  990. if (classFile.shouldBeWoven()) {
  991. String className = classFile.getClassName();
  992. BcelObjectType classType = getClassType(className);
  993. // null return from getClassType() means the delegate is an eclipse
  994. // source type - so
  995. // there *cant* be any reweavable state... (he bravely claimed...)
  996. if (classType != null) {
  997. ContextToken tok = CompilationAndWeavingContext.enteringPhase(
  998. CompilationAndWeavingContext.PROCESSING_REWEAVABLE_STATE, className);
  999. processReweavableStateIfPresent(className, classType);
  1000. CompilationAndWeavingContext.leavingPhase(tok);
  1001. }
  1002. }
  1003. }
  1004. CompilationAndWeavingContext.leavingPhase(reweaveToken);
  1005. ContextToken typeMungingToken = CompilationAndWeavingContext.enteringPhase(
  1006. CompilationAndWeavingContext.PROCESSING_TYPE_MUNGERS, "");
  1007. requestor.addingTypeMungers();
  1008. // We process type mungers in two groups, first mungers that change the
  1009. // type
  1010. // hierarchy, then 'normal' ITD type mungers.
  1011. // Process the types in a predictable order (rather than the order
  1012. // encountered).
  1013. // For class A, the order is superclasses of A then superinterfaces of A
  1014. // (and this mechanism is applied recursively)
  1015. List<String> typesToProcess = new ArrayList<>();
  1016. for (Iterator<UnwovenClassFile> iter = input.getClassFileIterator(); iter.hasNext();) {
  1017. UnwovenClassFile clf = iter.next();
  1018. if (clf.shouldBeWoven()) {
  1019. typesToProcess.add(clf.getClassName());
  1020. }
  1021. }
  1022. while (typesToProcess.size() > 0) {
  1023. weaveParentsFor(typesToProcess, typesToProcess.get(0), null);
  1024. }
  1025. for (Iterator<UnwovenClassFile> i = input.getClassFileIterator(); i.hasNext();) {
  1026. UnwovenClassFile classFile = i.next();
  1027. if (classFile.shouldBeWoven()) {
  1028. String className = classFile.getClassName();
  1029. addNormalTypeMungers(className);
  1030. }
  1031. }
  1032. CompilationAndWeavingContext.leavingPhase(typeMungingToken);
  1033. requestor.weavingAspects();
  1034. ContextToken aspectToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_ASPECTS, "");
  1035. // first weave into aspects
  1036. for (Iterator<UnwovenClassFile> i = input.getClassFileIterator(); i.hasNext();) {
  1037. UnwovenClassFile classFile = i.next();
  1038. if (classFile.shouldBeWoven()) {
  1039. String className = classFile.getClassName();
  1040. ResolvedType theType = world.resolve(className);
  1041. if (theType.isAspect()) {
  1042. BcelObjectType classType = BcelWorld.getBcelObjectType(theType);
  1043. if (classType == null) {
  1044. // Sometimes.. if the Bcel Delegate couldn't be found then a
  1045. // problem occurred at compile time - on
  1046. // a previous compiler run. In this case I assert the
  1047. // delegate will still be an EclipseSourceType
  1048. // and we can ignore the problem here (the original compile
  1049. // error will be reported again from
  1050. // the eclipse source type) - pr113531
  1051. ReferenceTypeDelegate theDelegate = ((ReferenceType) theType).getDelegate();
  1052. if (theDelegate.getClass().getName().endsWith("EclipseSourceType")) {
  1053. continue;
  1054. }
  1055. throw new BCException("Can't find bcel delegate for " + className + " type=" + theType.getClass());
  1056. }
  1057. weaveAndNotify(classFile, classType, requestor);
  1058. wovenClassNames.add(className);
  1059. }
  1060. }
  1061. }
  1062. CompilationAndWeavingContext.leavingPhase(aspectToken);
  1063. requestor.weavingClasses();
  1064. ContextToken classToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_CLASSES, "");
  1065. // then weave into non-aspects
  1066. for (Iterator<UnwovenClassFile> i = input.getClassFileIterator(); i.hasNext();) {
  1067. UnwovenClassFile classFile = i.next();
  1068. if (classFile.shouldBeWoven()) {
  1069. String className = classFile.getClassName();
  1070. ResolvedType theType = world.resolve(className);
  1071. if (!theType.isAspect()) {
  1072. BcelObjectType classType = BcelWorld.getBcelObjectType(theType);
  1073. if (classType == null) {
  1074. // bug 119882 - see above comment for bug 113531
  1075. ReferenceTypeDelegate theDelegate = ((ReferenceType) theType).getDelegate();
  1076. // TODO urgh - put a method on the interface to check this,
  1077. // string compare is hideous
  1078. if (theDelegate.getClass().getName().endsWith("EclipseSourceType")) {
  1079. continue;
  1080. }
  1081. throw new BCException("Can't find bcel delegate for " + className + " type=" + theType.getClass());
  1082. }
  1083. weaveAndNotify(classFile, classType, requestor);
  1084. wovenClassNames.add(className);
  1085. }
  1086. }
  1087. }
  1088. CompilationAndWeavingContext.leavingPhase(classToken);
  1089. addedClasses.clear();
  1090. deletedTypenames.clear();
  1091. requestor.weaveCompleted();
  1092. CompilationAndWeavingContext.leavingPhase(weaveToken);
  1093. if (trace.isTraceEnabled()) {
  1094. trace.exit("weave", wovenClassNames);
  1095. }
  1096. if (world.getModel() != null && world.isMinimalModel()) {
  1097. candidatesForRemoval.clear();
  1098. }
  1099. return wovenClassNames;
  1100. }
  1101. public void allWeavingComplete() {
  1102. warnOnUnmatchedAdvice();
  1103. }
  1104. /**
  1105. * In 1.5 mode and with XLint:adviceDidNotMatch enabled, put out messages for any mungers that did not match anything.
  1106. */
  1107. private void warnOnUnmatchedAdvice() {
  1108. class AdviceLocation {
  1109. private final int lineNo;
  1110. private final UnresolvedType inAspect;
  1111. public AdviceLocation(BcelAdvice advice) {
  1112. this.lineNo = advice.getSourceLocation().getLine();
  1113. this.inAspect = advice.getDeclaringAspect();
  1114. }
  1115. @Override
  1116. public boolean equals(Object obj) {
  1117. if (!(obj instanceof AdviceLocation)) {
  1118. return false;
  1119. }
  1120. AdviceLocation other = (AdviceLocation) obj;
  1121. if (this.lineNo != other.lineNo) {
  1122. return false;
  1123. }
  1124. if (!this.inAspect.equals(other.inAspect)) {
  1125. return false;
  1126. }
  1127. return true;
  1128. }
  1129. @Override
  1130. public int hashCode() {
  1131. return 37 + 17 * lineNo + 17 * inAspect.hashCode();
  1132. }
  1133. }
  1134. // FIXME asc Should be factored out into Xlint code and done
  1135. // automatically for all xlint messages, ideally.
  1136. // if a piece of advice hasn't matched anywhere and we are in -1.5 mode,
  1137. // put out a warning
  1138. if (world.isInJava5Mode() && world.getLint().adviceDidNotMatch.isEnabled()) {
  1139. List<ShadowMunger> l = world.getCrosscuttingMembersSet().getShadowMungers();
  1140. Set<AdviceLocation> alreadyWarnedLocations = new HashSet<>();
  1141. for (ShadowMunger element : l) {
  1142. // This will stop us incorrectly reporting deow checkers:
  1143. if (element instanceof BcelAdvice) {
  1144. BcelAdvice ba = (BcelAdvice) element;
  1145. if (ba.getKind() == AdviceKind.CflowEntry || ba.getKind() == AdviceKind.CflowBelowEntry) {
  1146. continue;
  1147. }
  1148. if (!ba.hasMatchedSomething()) {
  1149. // Because we implement some features of AJ itself by
  1150. // creating our own kind of mungers, you sometimes
  1151. // find that ba.getSignature() is not a BcelMethod - for
  1152. // example it might be a cflow entry munger.
  1153. if (ba.getSignature() != null) {
  1154. // check we haven't already warned on this advice and line
  1155. // (cflow creates multiple mungers for the same advice)
  1156. AdviceLocation loc = new AdviceLocation(ba);
  1157. if (alreadyWarnedLocations.contains(loc)) {
  1158. continue;
  1159. } else {
  1160. alreadyWarnedLocations.add(loc);
  1161. }
  1162. if (!(ba.getSignature() instanceof BcelMethod)
  1163. || !Utility.isSuppressing(ba.getSignature(), "adviceDidNotMatch")) {
  1164. world.getLint().adviceDidNotMatch.signal(ba.getDeclaringAspect().toString(), new SourceLocation(
  1165. element.getSourceLocation().getSourceFile(), element.getSourceLocation().getLine()));
  1166. }
  1167. }
  1168. }
  1169. }
  1170. }
  1171. }
  1172. }
  1173. /**
  1174. * 'typeToWeave' is one from the 'typesForWeaving' list. This routine ensures we process supertypes (classes/interfaces) of
  1175. * 'typeToWeave' that are in the 'typesForWeaving' list before 'typeToWeave' itself. 'typesToWeave' is then removed from the
  1176. * 'typesForWeaving' list.
  1177. *
  1178. * Note: Future gotcha in here ... when supplying partial hierarchies, this algorithm may break down. If you have a hierarchy
  1179. * A>B>C and only give A and C to the weaver, it may choose to weave them in either order - but you'll probably have other
  1180. * problems if you are supplying partial hierarchies like that !
  1181. */
  1182. private void weaveParentsFor(List<String> typesForWeaving, String typeToWeave, ResolvedType resolvedTypeToWeave) {
  1183. if (resolvedTypeToWeave == null) {
  1184. // resolve it if the caller could not pass in the resolved type
  1185. resolvedTypeToWeave = world.resolve(typeToWeave);
  1186. }
  1187. ResolvedType superclassType = resolvedTypeToWeave.getSuperclass();
  1188. String superclassTypename = (superclassType == null ? null : superclassType.getName());
  1189. // PR336654 added the 'typesForWeaving.contains(superclassTypename)' clause.
  1190. // Without it we can delete all type mungers on the parents and yet we only
  1191. // add back in the declare parents related ones, not the regular ITDs.
  1192. if (superclassType != null && !superclassType.isTypeHierarchyComplete() && superclassType.isExposedToWeaver()
  1193. && typesForWeaving.contains(superclassTypename)) {
  1194. weaveParentsFor(typesForWeaving, superclassTypename, superclassType);
  1195. }
  1196. ResolvedType[] interfaceTypes = resolvedTypeToWeave.getDeclaredInterfaces();
  1197. for (ResolvedType resolvedSuperInterface : interfaceTypes) {
  1198. if (!resolvedSuperInterface.isTypeHierarchyComplete()) {
  1199. String interfaceTypename = resolvedSuperInterface.getName();
  1200. if (resolvedSuperInterface.isExposedToWeaver()) { // typesForWeaving.contains(interfaceTypename)) {
  1201. weaveParentsFor(typesForWeaving, interfaceTypename, resolvedSuperInterface);
  1202. }
  1203. }
  1204. }
  1205. ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_DECLARE_PARENTS,
  1206. resolvedTypeToWeave.getName());
  1207. // If A was processed before B (and was declared 'class A implements B') then there is no need to complete B again, it
  1208. // will have been done whilst processing A.
  1209. if (!resolvedTypeToWeave.isTypeHierarchyComplete()) {
  1210. weaveParentTypeMungers(resolvedTypeToWeave);
  1211. }
  1212. CompilationAndWeavingContext.leavingPhase(tok);
  1213. typesForWeaving.remove(typeToWeave);
  1214. resolvedTypeToWeave.tagAsTypeHierarchyComplete();
  1215. }
  1216. public void prepareToProcessReweavableState() {
  1217. }
  1218. public void processReweavableStateIfPresent(String className, BcelObjectType classType) {
  1219. // If the class is marked reweavable, check any aspects around when it
  1220. // was built are in this world
  1221. WeaverStateInfo wsi = classType.getWeaverState();
  1222. // System.out.println(">> processReweavableStateIfPresent " + className + " wsi=" + wsi);
  1223. if (wsi != null && wsi.isReweavable()) { // Check all necessary types
  1224. // are around!
  1225. world.showMessage(IMessage.INFO, WeaverMessages.format(WeaverMessages.PROCESSING_REWEAVABLE, className, classType
  1226. .getSourceLocation().getSourceFile()), null, null);
  1227. Set<String> aspectsPreviouslyInWorld = wsi.getAspectsAffectingType();
  1228. // keep track of them just to ensure unique missing aspect error
  1229. // reporting
  1230. Set<String> alreadyConfirmedReweavableState = new HashSet<>();
  1231. for (String requiredTypeSignature : aspectsPreviouslyInWorld) {
  1232. // for (Iterator iter = aspectsPreviouslyInWorld.iterator(); iter.hasNext();) {
  1233. // String requiredTypeName = (String) iter.next();
  1234. if (!alreadyConfirmedReweavableState.contains(requiredTypeSignature)) {
  1235. ResolvedType rtx = world.resolve(UnresolvedType.forSignature(requiredTypeSignature), true);
  1236. boolean exists = !rtx.isMissing();
  1237. if (!world.isOverWeaving()) {
  1238. if (!exists) {
  1239. world.getLint().missingAspectForReweaving.signal(new String[] { rtx.getName(), className },
  1240. classType.getSourceLocation(), null);
  1241. // world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.MISSING_REWEAVABLE_TYPE,
  1242. // requiredTypeName, className), classType.getSourceLocation(), null);
  1243. } else {
  1244. // weaved in aspect that are not declared in aop.xml
  1245. // trigger an error for now
  1246. // may cause headhache for LTW and packaged lib
  1247. // without aop.xml in
  1248. // see #104218
  1249. if (!xcutSet.containsAspect(rtx)) {
  1250. world.showMessage(IMessage.ERROR, WeaverMessages.format(
  1251. WeaverMessages.REWEAVABLE_ASPECT_NOT_REGISTERED, rtx.getName(), className), null, null);
  1252. } else if (!world.getMessageHandler().isIgnoring(IMessage.INFO)) {
  1253. world.showMessage(IMessage.INFO, WeaverMessages.format(WeaverMessages.VERIFIED_REWEAVABLE_TYPE,
  1254. rtx.getName(), rtx.getSourceLocation().getSourceFile()), null, null);
  1255. }
  1256. alreadyConfirmedReweavableState.add(requiredTypeSignature);
  1257. }
  1258. }
  1259. }
  1260. }
  1261. // old:
  1262. // classType.setJavaClass(Utility.makeJavaClass(classType.getJavaClass
  1263. // ().getFileName(), wsi.getUnwovenClassFileData()));
  1264. // new: reweavable default with clever diff
  1265. if (!world.isOverWeaving()) {
  1266. byte[] ucfd = wsi.getUnwovenClassFileData();
  1267. if (ucfd.length == 0) {
  1268. // Size 0 indicates the class was previously overwoven, so you need to be overweaving now!
  1269. world.getMessageHandler().handleMessage(
  1270. MessageUtil.error(
  1271. WeaverMessages.format(WeaverMessages.MUST_KEEP_OVERWEAVING_ONCE_START,
  1272. className)));
  1273. // onType.getName(), annoX.getTypeName(), annoX.getValidTargets()),
  1274. // decA.getSourceLocation()));
  1275. } else {
  1276. byte[] bytes = wsi.getUnwovenClassFileData(classType.getJavaClass().getBytes());
  1277. JavaClass newJavaClass = Utility.makeJavaClass(classType.getJavaClass().getFileName(), bytes);
  1278. classType.setJavaClass(newJavaClass, true);
  1279. classType.getResolvedTypeX().ensureConsistent();
  1280. }
  1281. }
  1282. // } else {
  1283. // classType.resetState();
  1284. }
  1285. }
  1286. private void weaveAndNotify(UnwovenClassFile classFile, BcelObjectType classType, IWeaveRequestor requestor) throws IOException {
  1287. trace.enter("weaveAndNotify", this, new Object[] { classFile, classType, requestor });
  1288. ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_TYPE, classType
  1289. .getResolvedTypeX().getName());
  1290. LazyClassGen clazz = weaveWithoutDump(classFile, classType);
  1291. classType.finishedWith();
  1292. // clazz is null if the classfile was unchanged by weaving...
  1293. if (clazz != null) {
  1294. UnwovenClassFile[] newClasses = getClassFilesFor(clazz);
  1295. // OPTIMIZE can we avoid using the string name at all in
  1296. // UnwovenClassFile instances?
  1297. // Copy the char[] across as it means the
  1298. // WeaverAdapter.removeFromMap() can be fast!
  1299. if (newClasses[0].getClassName().equals(classFile.getClassName())) {
  1300. newClasses[0].setClassNameAsChars(classFile.getClassNameAsChars());
  1301. }
  1302. for (UnwovenClassFile newClass : newClasses) {
  1303. requestor.acceptResult(newClass);
  1304. }
  1305. } else {
  1306. requestor.acceptResult(classFile);
  1307. }
  1308. classType.weavingCompleted();
  1309. CompilationAndWeavingContext.leavingPhase(tok);
  1310. trace.exit("weaveAndNotify");
  1311. }
  1312. /**
  1313. * helper method - will return NULL if the underlying delegate is an EclipseSourceType and not a BcelObjectType
  1314. */
  1315. public BcelObjectType getClassType(String forClass) {
  1316. return BcelWorld.getBcelObjectType(world.resolve(forClass));
  1317. }
  1318. public void addParentTypeMungers(String typeName) {
  1319. weaveParentTypeMungers(world.resolve(typeName));
  1320. }
  1321. public void addNormalTypeMungers(String typeName) {
  1322. weaveNormalTypeMungers(world.resolve(typeName));
  1323. }
  1324. public UnwovenClassFile[] getClassFilesFor(LazyClassGen clazz) {
  1325. List<UnwovenClassFile.ChildClass> childClasses = clazz.getChildClasses(world);
  1326. UnwovenClassFile[] ret = new UnwovenClassFile[1 + childClasses.size()];
  1327. ret[0] = new UnwovenClassFile(clazz.getFileName(), clazz.getClassName(), clazz.getJavaClassBytesIncludingReweavable(world));
  1328. int index = 1;
  1329. for (UnwovenClassFile.ChildClass element : childClasses) {
  1330. UnwovenClassFile childClass = new UnwovenClassFile(clazz.getFileName() + "$" + element.name, element.bytes);
  1331. ret[index++] = childClass;
  1332. }
  1333. return ret;
  1334. }
  1335. /**
  1336. * Weaves new parents and annotations onto a type ("declare parents" and "declare @type")
  1337. *
  1338. * Algorithm: 1. First pass, do parents then do annotations. During this pass record: - any parent mungers that don't match but
  1339. * have a non-wild annotation type pattern - any annotation mungers that don't match 2. Multiple subsequent passes which go over
  1340. * the munger lists constructed in the first pass, repeatedly applying them until nothing changes. FIXME asc confirm that
  1341. * algorithm is optimal ??
  1342. */
  1343. public void weaveParentTypeMungers(ResolvedType onType) {
  1344. if (onType.isRawType() || onType.isParameterizedType()) {
  1345. onType = onType.getGenericType();
  1346. }
  1347. onType.clearInterTypeMungers();
  1348. List<DeclareParents> decpToRepeat = new ArrayList<>();
  1349. boolean aParentChangeOccurred = false;
  1350. boolean anAnnotationChangeOccurred = false;
  1351. // First pass - apply all decp mungers
  1352. for (DeclareParents decp : declareParentsList) {
  1353. boolean typeChanged = applyDeclareParents(decp, onType);
  1354. if (typeChanged) {
  1355. aParentChangeOccurred = true;
  1356. } else {
  1357. decpToRepeat.add(decp);
  1358. }
  1359. }
  1360. // Still first pass - apply all dec @type mungers
  1361. for (DeclareAnnotation decA : xcutSet.getDeclareAnnotationOnTypes()) {
  1362. boolean typeChanged = applyDeclareAtType(decA, onType, true);
  1363. if (typeChanged) {
  1364. anAnnotationChangeOccurred = true;
  1365. }
  1366. }
  1367. while ((aParentChangeOccurred || anAnnotationChangeOccurred) && !decpToRepeat.isEmpty()) {
  1368. anAnnotationChangeOccurred = aParentChangeOccurred = false;
  1369. List<DeclareParents> decpToRepeatNextTime = new ArrayList<>();
  1370. for (DeclareParents decp : decpToRepeat) {
  1371. boolean typeChanged = applyDeclareParents(decp, onType);
  1372. if (typeChanged) {
  1373. aParentChangeOccurred = true;
  1374. } else {
  1375. decpToRepeatNextTime.add(decp);
  1376. }
  1377. }
  1378. for (DeclareAnnotation decA : xcutSet.getDeclareAnnotationOnTypes()) {
  1379. boolean typeChanged = applyDeclareAtType(decA, onType, false);
  1380. if (typeChanged) {
  1381. anAnnotationChangeOccurred = true;
  1382. }
  1383. }
  1384. decpToRepeat = decpToRepeatNextTime;
  1385. }
  1386. }
  1387. /**
  1388. * Apply a declare @type - return true if we change the type
  1389. */
  1390. private boolean applyDeclareAtType(DeclareAnnotation decA, ResolvedType onType, boolean reportProblems) {
  1391. boolean didSomething = false;
  1392. if (decA.matches(onType)) {
  1393. AnnotationAJ theAnnotation = decA.getAnnotation();
  1394. // can be null for broken code!
  1395. if (theAnnotation == null) {
  1396. return false;
  1397. }
  1398. if (onType.hasAnnotation(theAnnotation.getType())) {
  1399. // Could put out a lint here for an already annotated type ...
  1400. // if (reportProblems) {
  1401. // world.getLint().elementAlreadyAnnotated.signal(
  1402. // new
  1403. // String[]{onType.toString(),decA.getAnnotationTypeX().toString
  1404. // ()},
  1405. // onType.getSourceLocation(),new
  1406. // ISourceLocation[]{decA.getSourceLocation()});
  1407. // }
  1408. return false;
  1409. }
  1410. AnnotationAJ annoX = decA.getAnnotation();
  1411. // check the annotation is suitable for the target
  1412. boolean problemReported = verifyTargetIsOK(decA, onType, annoX, reportProblems);
  1413. if (!problemReported) {
  1414. AsmRelationshipProvider.addDeclareAnnotationRelationship(world.getModelAsAsmManager(), decA.getSourceLocation(),
  1415. onType.getSourceLocation(), false);
  1416. // TAG: WeavingMessage
  1417. if (!getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) {
  1418. getWorld().getMessageHandler().handleMessage(
  1419. WeaveMessage.constructWeavingMessage(
  1420. WeaveMessage.WEAVEMESSAGE_ANNOTATES,
  1421. new String[] { onType.toString(), Utility.beautifyLocation(onType.getSourceLocation()),
  1422. decA.getAnnotationString(), "type", decA.getAspect().toString(),
  1423. Utility.beautifyLocation(decA.getSourceLocation()) }));
  1424. }
  1425. didSomething = true;
  1426. ResolvedTypeMunger newAnnotationTM = new AnnotationOnTypeMunger(annoX);
  1427. newAnnotationTM.setSourceLocation(decA.getSourceLocation());
  1428. onType.addInterTypeMunger(new BcelTypeMunger(newAnnotationTM, decA.getAspect().resolve(world)), false);
  1429. decA.copyAnnotationTo(onType);
  1430. }
  1431. }
  1432. return didSomething;
  1433. }
  1434. /**
  1435. * Checks for an @target() on the annotation and if found ensures it allows the annotation to be attached to the target type
  1436. * that matched.
  1437. */
  1438. private boolean verifyTargetIsOK(DeclareAnnotation decA, ResolvedType onType, AnnotationAJ annoX, boolean outputProblems) {
  1439. boolean problemReported = false;
  1440. if (annoX.specifiesTarget()) {
  1441. if ((onType.isAnnotation() && !annoX.allowedOnAnnotationType()) || (!annoX.allowedOnRegularType())) {
  1442. if (outputProblems) {
  1443. if (decA.isExactPattern()) {
  1444. world.getMessageHandler().handleMessage(
  1445. MessageUtil.error(
  1446. WeaverMessages.format(WeaverMessages.INCORRECT_TARGET_FOR_DECLARE_ANNOTATION,
  1447. onType.getName(), annoX.getTypeName(), annoX.getValidTargets()),
  1448. decA.getSourceLocation()));
  1449. } else {
  1450. if (world.getLint().invalidTargetForAnnotation.isEnabled()) {
  1451. world.getLint().invalidTargetForAnnotation.signal(new String[] { onType.getName(), annoX.getTypeName(),
  1452. annoX.getValidTargets() }, decA.getSourceLocation(),
  1453. new ISourceLocation[] { onType.getSourceLocation() });
  1454. }
  1455. }
  1456. }
  1457. problemReported = true;
  1458. }
  1459. }
  1460. return problemReported;
  1461. }
  1462. /**
  1463. * Apply a single declare parents - return true if we change the type
  1464. */
  1465. private boolean applyDeclareParents(DeclareParents p, ResolvedType onType) {
  1466. boolean didSomething = false;
  1467. List<ResolvedType> newParents = p.findMatchingNewParents(onType, true);
  1468. if (!newParents.isEmpty()) {
  1469. didSomething = true;
  1470. BcelWorld.getBcelObjectType(onType);
  1471. // System.err.println("need to do declare parents for: " + onType);
  1472. for (ResolvedType newParent : newParents) {
  1473. // We set it here so that the imminent matching for ITDs can
  1474. // succeed - we still haven't done the necessary changes to the class file
  1475. // itself (like transform super calls) - that is done in
  1476. // BcelTypeMunger.mungeNewParent()
  1477. // classType.addParent(newParent);
  1478. onType.addParent(newParent);
  1479. NewParentTypeMunger newParentMunger = new NewParentTypeMunger(newParent, p.getDeclaringType());
  1480. if (p.isMixin()) {
  1481. newParentMunger.setIsMixin(true);
  1482. }
  1483. newParentMunger.setSourceLocation(p.getSourceLocation());
  1484. onType.addInterTypeMunger(new BcelTypeMunger(newParentMunger, xcutSet.findAspectDeclaringParents(p)), false);
  1485. }
  1486. }
  1487. return didSomething;
  1488. }
  1489. public void weaveNormalTypeMungers(ResolvedType onType) {
  1490. ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_TYPE_MUNGERS,
  1491. onType.getName());
  1492. if (onType.isRawType() || onType.isParameterizedType()) {
  1493. onType = onType.getGenericType();
  1494. }
  1495. for (ConcreteTypeMunger m : typeMungerList) {
  1496. if (!m.isLateMunger() && m.matches(onType)) {
  1497. onType.addInterTypeMunger(m, false);
  1498. }
  1499. }
  1500. CompilationAndWeavingContext.leavingPhase(tok);
  1501. }
  1502. // exposed for ClassLoader dynamic weaving
  1503. public LazyClassGen weaveWithoutDump(UnwovenClassFile classFile, BcelObjectType classType) throws IOException {
  1504. return weave(classFile, classType, false);
  1505. }
  1506. // FOR TESTING
  1507. LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType) throws IOException {
  1508. LazyClassGen ret = weave(classFile, classType, true);
  1509. return ret;
  1510. }
  1511. private LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType, boolean dump) throws IOException {
  1512. try {
  1513. if (classType.isSynthetic()) { // Don't touch synthetic classes
  1514. if (dump) {
  1515. dumpUnchanged(classFile);
  1516. }
  1517. return null;
  1518. }
  1519. ReferenceType resolvedClassType = classType.getResolvedTypeX();
  1520. if (world.isXmlConfigured() && world.getXmlConfiguration().excludesType(resolvedClassType)) {
  1521. if (!world.getMessageHandler().isIgnoring(IMessage.INFO)) {
  1522. world.getMessageHandler().handleMessage(
  1523. MessageUtil.info("Type '" + resolvedClassType.getName()
  1524. + "' not woven due to exclusion via XML weaver exclude section"));
  1525. }
  1526. if (dump) {
  1527. dumpUnchanged(classFile);
  1528. }
  1529. return null;
  1530. }
  1531. List<ShadowMunger> shadowMungers = fastMatch(shadowMungerList, resolvedClassType);
  1532. List<ConcreteTypeMunger> typeMungers = classType.getResolvedTypeX().getInterTypeMungers();
  1533. resolvedClassType.checkInterTypeMungers();
  1534. // Decide if we need to do actual weaving for this class
  1535. boolean mightNeedToWeave = shadowMungers.size() > 0 || typeMungers.size() > 0 || classType.isAspect()
  1536. || world.getDeclareAnnotationOnMethods().size() > 0 || world.getDeclareAnnotationOnFields().size() > 0;
  1537. // May need bridge methods if on 1.5 and something in our hierarchy is
  1538. // affected by ITDs
  1539. boolean mightNeedBridgeMethods = world.isInJava5Mode() && !classType.isInterface()
  1540. && resolvedClassType.getInterTypeMungersIncludingSupers().size() > 0;
  1541. LazyClassGen clazz = null;
  1542. if (mightNeedToWeave || mightNeedBridgeMethods) {
  1543. clazz = classType.getLazyClassGen();
  1544. // System.err.println("got lazy gen: " + clazz + ", " +
  1545. // clazz.getWeaverState());
  1546. try {
  1547. boolean isChanged = false;
  1548. if (mightNeedToWeave) {
  1549. isChanged = BcelClassWeaver.weave(world, clazz, shadowMungers, typeMungers, lateTypeMungerList,
  1550. inReweavableMode);
  1551. }
  1552. checkDeclareTypeErrorOrWarning(world, classType);
  1553. if (mightNeedBridgeMethods) {
  1554. isChanged = BcelClassWeaver.calculateAnyRequiredBridgeMethods(world, clazz) || isChanged;
  1555. }
  1556. if (isChanged) {
  1557. if (dump) {
  1558. dump(classFile, clazz);
  1559. }
  1560. return clazz;
  1561. }
  1562. } catch (RuntimeException re) {
  1563. String classDebugInfo = null;
  1564. try {
  1565. classDebugInfo = clazz.toLongString();
  1566. } catch (Throwable e) {
  1567. new RuntimeException("Crashed whilst crashing with this exception: " + e, e).printStackTrace();
  1568. // recover from crash whilst producing debug string
  1569. classDebugInfo = clazz.getClassName();
  1570. }
  1571. String messageText = "trouble in: \n" + classDebugInfo;
  1572. getWorld().getMessageHandler().handleMessage(new Message(messageText, IMessage.ABORT, re, null));
  1573. } catch (Error re) {
  1574. String classDebugInfo = null;
  1575. try {
  1576. classDebugInfo = clazz.toLongString();
  1577. } catch (OutOfMemoryError oome) {
  1578. System.err.println("Ran out of memory creating debug info for an error");
  1579. re.printStackTrace(System.err);
  1580. // recover from crash whilst producing debug string
  1581. classDebugInfo = clazz.getClassName();
  1582. } catch (Throwable e) {
  1583. // recover from crash whilst producing debug string
  1584. classDebugInfo = clazz.getClassName();
  1585. }
  1586. String messageText = "trouble in: \n" + classDebugInfo;
  1587. getWorld().getMessageHandler().handleMessage(new Message(messageText, IMessage.ABORT, re, null));
  1588. }
  1589. } else {
  1590. checkDeclareTypeErrorOrWarning(world, classType);
  1591. }
  1592. // this is very odd return behavior trying to keep everyone happy
  1593. // can we remove it from the model now? we know it contains no relationship endpoints...
  1594. AsmManager model = world.getModelAsAsmManager();
  1595. if (world.isMinimalModel() && model != null && !classType.isAspect()) {
  1596. AspectJElementHierarchy hierarchy = (AspectJElementHierarchy) model.getHierarchy();
  1597. String pkgname = classType.getResolvedTypeX().getPackageName();
  1598. String tname = classType.getResolvedTypeX().getSimpleBaseName();
  1599. IProgramElement typeElement = hierarchy.findElementForType(pkgname, tname);
  1600. if (typeElement != null && hasInnerType(typeElement)) {
  1601. // Cannot remove it right now (has inner type), schedule it
  1602. // for possible deletion later if all inner types are
  1603. // removed
  1604. candidatesForRemoval.add(typeElement);
  1605. }
  1606. if (typeElement != null && !hasInnerType(typeElement)) {
  1607. IProgramElement parent = typeElement.getParent();
  1608. // parent may have children: PACKAGE DECL, IMPORT-REFERENCE, TYPE_DECL
  1609. if (parent != null) {
  1610. // if it was the only type we should probably remove
  1611. // the others too.
  1612. parent.removeChild(typeElement);
  1613. if (parent.getKind().isSourceFile()) {
  1614. removeSourceFileIfNoMoreTypeDeclarationsInside(hierarchy, typeElement, parent);
  1615. } else {
  1616. hierarchy.forget(null, typeElement);
  1617. // At this point, the child has been removed. We
  1618. // should now check if the parent is in our
  1619. // 'candidatesForRemoval' set. If it is then that
  1620. // means we were going to remove it but it had a
  1621. // child. Now we can check if it still has a child -
  1622. // if it doesn't it can also be removed!
  1623. walkUpRemovingEmptyTypesAndPossiblyEmptySourceFile(hierarchy, tname, parent);
  1624. }
  1625. }
  1626. }
  1627. }
  1628. if (dump) {
  1629. dumpUnchanged(classFile);
  1630. return clazz;
  1631. } else {
  1632. // ATAJ: the class was not weaved, but since it gets there early it
  1633. // may have new generated inner classes
  1634. // attached to it to support LTW perX aspectOf support (see
  1635. // BcelPerClauseAspectAdder)
  1636. // that aggressively defines the inner <aspect>$mayHaveAspect
  1637. // interface.
  1638. if (clazz != null && !clazz.getChildClasses(world).isEmpty()) {
  1639. return clazz;
  1640. }
  1641. return null;
  1642. }
  1643. } finally {
  1644. world.demote();
  1645. }
  1646. }
  1647. private void walkUpRemovingEmptyTypesAndPossiblyEmptySourceFile(AspectJElementHierarchy hierarchy, String tname,
  1648. IProgramElement typeThatHasChildRemoved) {
  1649. // typeThatHasChildRemoved might be a source file, type or a method/ctor
  1650. // - for a method/ctor find the type/sourcefile
  1651. while (typeThatHasChildRemoved != null
  1652. && !(typeThatHasChildRemoved.getKind().isType() || typeThatHasChildRemoved.getKind().isSourceFile())) {
  1653. // this will take us 'up' through methods that contain anonymous
  1654. // inner classes
  1655. typeThatHasChildRemoved = typeThatHasChildRemoved.getParent();
  1656. }
  1657. // now typeThatHasChildRemoved points to the type or sourcefile that has
  1658. // had something removed
  1659. if (candidatesForRemoval.contains(typeThatHasChildRemoved) && !hasInnerType(typeThatHasChildRemoved)) {
  1660. // now we can get rid of it
  1661. IProgramElement parent = typeThatHasChildRemoved.getParent();
  1662. if (parent != null) {
  1663. parent.removeChild(typeThatHasChildRemoved);
  1664. candidatesForRemoval.remove(typeThatHasChildRemoved);
  1665. if (parent.getKind().isSourceFile()) {
  1666. removeSourceFileIfNoMoreTypeDeclarationsInside(hierarchy, typeThatHasChildRemoved, parent);
  1667. // System.out.println("Removed on second pass: " +
  1668. // typeThatHasChildRemoved.getName());
  1669. } else {
  1670. // System.out.println("On later pass, parent of type " +
  1671. // typeThatHasChildRemoved.getName()
  1672. // + " was found not to be a sourcefile, recursing up...");
  1673. walkUpRemovingEmptyTypesAndPossiblyEmptySourceFile(hierarchy, tname, parent);
  1674. }
  1675. }
  1676. }
  1677. }
  1678. private void removeSourceFileIfNoMoreTypeDeclarationsInside(AspectJElementHierarchy hierarchy, IProgramElement typeElement,
  1679. IProgramElement sourceFileNode) {
  1680. IProgramElement compilationUnit = sourceFileNode;
  1681. boolean anyOtherTypeDeclarations = false;
  1682. for (IProgramElement child : compilationUnit.getChildren()) {
  1683. IProgramElement.Kind k = child.getKind();
  1684. if (k.isType()) {
  1685. anyOtherTypeDeclarations = true;
  1686. break;
  1687. }
  1688. }
  1689. // If the compilation unit node contained no
  1690. // other types, there is no need to keep it
  1691. if (!anyOtherTypeDeclarations) {
  1692. IProgramElement cuParent = compilationUnit.getParent();
  1693. if (cuParent != null) {
  1694. compilationUnit.setParent(null);
  1695. cuParent.removeChild(compilationUnit);
  1696. }
  1697. // need to update some caches and structures too?
  1698. hierarchy.forget(sourceFileNode, typeElement);
  1699. } else {
  1700. hierarchy.forget(null, typeElement);
  1701. }
  1702. }
  1703. // ---- writing
  1704. // TODO could be smarter - really only matters if inner type has been woven, but there is a chance we haven't woven it *yet*
  1705. private boolean hasInnerType(IProgramElement typeNode) {
  1706. for (IProgramElement child : typeNode.getChildren()) {
  1707. IProgramElement.Kind kind = child.getKind();
  1708. if (kind.isType()) {
  1709. return true;
  1710. }
  1711. // if (kind == IProgramElement.Kind.ASPECT) {
  1712. // return true;
  1713. // }
  1714. if (kind.isType() || kind == IProgramElement.Kind.METHOD || kind == IProgramElement.Kind.CONSTRUCTOR) {
  1715. boolean b = hasInnerType(child);
  1716. if (b) {
  1717. return b;
  1718. }
  1719. }
  1720. }
  1721. return false;
  1722. }
  1723. private void checkDeclareTypeErrorOrWarning(BcelWorld world2, BcelObjectType classType) {
  1724. List<DeclareTypeErrorOrWarning> dteows = world.getDeclareTypeEows();
  1725. for (DeclareTypeErrorOrWarning dteow : dteows) {
  1726. if (dteow.getTypePattern().matchesStatically(classType.getResolvedTypeX())) {
  1727. if (dteow.isError()) {
  1728. world.getMessageHandler().handleMessage(
  1729. MessageUtil.error(dteow.getMessage(), classType.getResolvedTypeX().getSourceLocation()));
  1730. } else {
  1731. world.getMessageHandler().handleMessage(
  1732. MessageUtil.warn(dteow.getMessage(), classType.getResolvedTypeX().getSourceLocation()));
  1733. }
  1734. }
  1735. }
  1736. }
  1737. private void dumpUnchanged(UnwovenClassFile classFile) throws IOException {
  1738. if (zipOutputStream != null) {
  1739. writeZipEntry(getEntryName(classFile.getJavaClass().getClassName()), classFile.getBytes());
  1740. } else {
  1741. classFile.writeUnchangedBytes();
  1742. }
  1743. }
  1744. private String getEntryName(String className) {
  1745. // XXX what does bcel's getClassName do for inner names
  1746. return className.replace('.', '/') + ".class";
  1747. }
  1748. private void dump(UnwovenClassFile classFile, LazyClassGen clazz) throws IOException {
  1749. if (zipOutputStream != null) {
  1750. String mainClassName = classFile.getJavaClass().getClassName();
  1751. writeZipEntry(getEntryName(mainClassName), clazz.getJavaClass(world).getBytes());
  1752. List<UnwovenClassFile.ChildClass> childClasses = clazz.getChildClasses(world);
  1753. if (!childClasses.isEmpty()) {
  1754. for (UnwovenClassFile.ChildClass c : childClasses) {
  1755. writeZipEntry(getEntryName(mainClassName + "$" + c.name), c.bytes);
  1756. }
  1757. }
  1758. } else {
  1759. classFile.writeWovenBytes(clazz.getJavaClass(world).getBytes(), clazz.getChildClasses(world));
  1760. }
  1761. }
  1762. private void writeZipEntry(String name, byte[] bytes) throws IOException {
  1763. ZipEntry newEntry = new ZipEntry(name); // ??? get compression scheme
  1764. // right
  1765. zipOutputStream.putNextEntry(newEntry);
  1766. zipOutputStream.write(bytes);
  1767. zipOutputStream.closeEntry();
  1768. }
  1769. /**
  1770. * Perform a fast match of the specified list of shadowmungers against the specified type. A subset of those that might match is
  1771. * returned.
  1772. *
  1773. * @param list list of all shadow mungers that might match
  1774. * @param type the target type
  1775. * @return a list of shadow mungers that might match with those that cannot (according to fast match rules) removed
  1776. */
  1777. private List<ShadowMunger> fastMatch(List<ShadowMunger> list, ResolvedType type) {
  1778. if (list == null) {
  1779. return Collections.emptyList();
  1780. }
  1781. boolean isOverweaving = world.isOverWeaving();
  1782. WeaverStateInfo typeWeaverState = (isOverweaving ? type.getWeaverState() : null);
  1783. // here we do the coarsest grained fast match with no kind constraints
  1784. // this will remove all obvious non-matches and see if we need to do any
  1785. // weaving
  1786. FastMatchInfo info = new FastMatchInfo(type, null, world);
  1787. List<ShadowMunger> result = new ArrayList<>();
  1788. if (world.areInfoMessagesEnabled() && world.isTimingEnabled()) {
  1789. for (ShadowMunger munger : list) {
  1790. if (typeWeaverState != null) { // will only be null if overweaving is ON and there is weaverstate
  1791. ResolvedType declaringAspect = munger.getDeclaringType();
  1792. if (typeWeaverState.isAspectAlreadyApplied(declaringAspect)) {
  1793. continue;
  1794. }
  1795. }
  1796. Pointcut pointcut = munger.getPointcut();
  1797. long starttime = System.nanoTime();
  1798. FuzzyBoolean fb = pointcut.fastMatch(info);
  1799. long endtime = System.nanoTime();
  1800. world.recordFastMatch(pointcut, endtime - starttime);
  1801. if (fb.maybeTrue()) {
  1802. result.add(munger);
  1803. }
  1804. }
  1805. } else {
  1806. for (ShadowMunger munger : list) {
  1807. if (typeWeaverState != null) { // will only be null if overweaving is ON and there is weaverstate
  1808. ResolvedType declaringAspect = munger.getConcreteAspect();// getDeclaringType();
  1809. if (typeWeaverState.isAspectAlreadyApplied(declaringAspect)) {
  1810. continue;
  1811. }
  1812. }
  1813. Pointcut pointcut = munger.getPointcut();
  1814. FuzzyBoolean fb = pointcut.fastMatch(info);
  1815. if (fb.maybeTrue()) {
  1816. result.add(munger);
  1817. }
  1818. }
  1819. }
  1820. return result;
  1821. }
  1822. public void setReweavableMode(boolean xNotReweavable) {
  1823. inReweavableMode = !xNotReweavable;
  1824. WeaverStateInfo.setReweavableModeDefaults(!xNotReweavable, false, true);
  1825. }
  1826. public boolean isReweavable() {
  1827. return inReweavableMode;
  1828. }
  1829. public World getWorld() {
  1830. return world;
  1831. }
  1832. public void tidyUp() {
  1833. if (trace.isTraceEnabled()) {
  1834. trace.enter("tidyUp", this);
  1835. }
  1836. shadowMungerList = null; // setup by prepareForWeave
  1837. typeMungerList = null; // setup by prepareForWeave
  1838. lateTypeMungerList = null; // setup by prepareForWeave
  1839. declareParentsList = null; // setup by prepareForWeave
  1840. if (trace.isTraceEnabled()) {
  1841. trace.exit("tidyUp");
  1842. }
  1843. }
  1844. public void write(CompressingDataOutputStream dos) throws IOException {
  1845. xcutSet.write(dos);
  1846. }
  1847. // only called for testing
  1848. public void setShadowMungers(List<ShadowMunger> shadowMungers) {
  1849. shadowMungerList = shadowMungers;
  1850. }
  1851. }