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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032
  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 final 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 WeaveRequestor();
  893. }
  894. });
  895. // /* BUG 40943*/
  896. // dumpResourcesToOutJar();
  897. zipOutputStream.close(); // this flushes and closes the acutal file
  898. return c;
  899. }
  900. private class WeaveRequestor implements IWeaveRequestor {
  901. public void acceptResult(IUnwovenClassFile result) {
  902. try {
  903. writeZipEntry(result.getFilename(), result.getBytes());
  904. } catch (IOException ex) {
  905. }
  906. }
  907. public void processingReweavableState() {}
  908. public void addingTypeMungers() {}
  909. public void weavingAspects() {}
  910. public void weavingClasses() {}
  911. public void weaveCompleted() {}
  912. }
  913. private Set<IProgramElement> candidatesForRemoval = null;
  914. // variation of "weave" that sources class files from an external source.
  915. public Collection<String> weave(IClassFileProvider input) throws IOException {
  916. if (trace.isTraceEnabled()) {
  917. trace.enter("weave", this, input);
  918. }
  919. ContextToken weaveToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING, "");
  920. Collection<String> wovenClassNames = new ArrayList<>();
  921. IWeaveRequestor requestor = input.getRequestor();
  922. if (world.getModel() != null && world.isMinimalModel()) {
  923. candidatesForRemoval = new HashSet<>();
  924. }
  925. if (world.getModel() != null && !isBatchWeave) {
  926. AsmManager manager = world.getModelAsAsmManager();
  927. for (Iterator<UnwovenClassFile> i = input.getClassFileIterator(); i.hasNext();) {
  928. UnwovenClassFile classFile = i.next();
  929. // remove all relationships where this file being woven is
  930. // the target of the relationship
  931. manager.removeRelationshipsTargettingThisType(classFile.getClassName());
  932. }
  933. }
  934. // Go through the types and ensure any 'damaged' during compile time are
  935. // repaired prior to weaving
  936. for (Iterator<UnwovenClassFile> i = input.getClassFileIterator(); i.hasNext();) {
  937. UnwovenClassFile classFile = i.next();
  938. if (classFile.shouldBeWoven()) {
  939. String className = classFile.getClassName();
  940. ResolvedType theType = world.resolve(className);
  941. if (theType != null) {
  942. theType.ensureConsistent();
  943. }
  944. }
  945. }
  946. // special case for AtAspectJMungerOnly - see #113587
  947. if (input.isApplyAtAspectJMungersOnly()) {
  948. ContextToken atAspectJMungersOnly = CompilationAndWeavingContext.enteringPhase(
  949. CompilationAndWeavingContext.PROCESSING_ATASPECTJTYPE_MUNGERS_ONLY, "");
  950. requestor.weavingAspects();
  951. // ContextToken aspectToken =
  952. CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_ASPECTS, "");
  953. for (Iterator<UnwovenClassFile> i = input.getClassFileIterator(); i.hasNext();) {
  954. UnwovenClassFile classFile = i.next();
  955. if (classFile.shouldBeWoven()) {
  956. String className = classFile.getClassName();
  957. ResolvedType theType = world.resolve(className);
  958. if (theType.isAnnotationStyleAspect()) {
  959. BcelObjectType classType = BcelWorld.getBcelObjectType(theType);
  960. if (classType == null) {
  961. throw new BCException("Can't find bcel delegate for " + className + " type=" + theType.getClass());
  962. }
  963. LazyClassGen clazz = classType.getLazyClassGen();
  964. BcelPerClauseAspectAdder selfMunger = new BcelPerClauseAspectAdder(theType, theType.getPerClause().getKind());
  965. selfMunger.forceMunge(clazz, true);
  966. classType.finishedWith();
  967. UnwovenClassFile[] newClasses = getClassFilesFor(clazz);
  968. for (UnwovenClassFile newClass : newClasses) {
  969. requestor.acceptResult(newClass);
  970. }
  971. wovenClassNames.add(classFile.getClassName());
  972. }
  973. }
  974. }
  975. requestor.weaveCompleted();
  976. CompilationAndWeavingContext.leavingPhase(atAspectJMungersOnly);
  977. return wovenClassNames;
  978. }
  979. requestor.processingReweavableState();
  980. ContextToken reweaveToken = CompilationAndWeavingContext.enteringPhase(
  981. CompilationAndWeavingContext.PROCESSING_REWEAVABLE_STATE, "");
  982. prepareToProcessReweavableState();
  983. // clear all state from files we'll be reweaving
  984. for (Iterator<UnwovenClassFile> i = input.getClassFileIterator(); i.hasNext();) {
  985. UnwovenClassFile classFile = i.next();
  986. if (classFile.shouldBeWoven()) {
  987. String className = classFile.getClassName();
  988. BcelObjectType classType = getClassType(className);
  989. // null return from getClassType() means the delegate is an eclipse
  990. // source type - so
  991. // there *cant* be any reweavable state... (he bravely claimed...)
  992. if (classType != null) {
  993. ContextToken tok = CompilationAndWeavingContext.enteringPhase(
  994. CompilationAndWeavingContext.PROCESSING_REWEAVABLE_STATE, className);
  995. processReweavableStateIfPresent(className, classType);
  996. CompilationAndWeavingContext.leavingPhase(tok);
  997. }
  998. }
  999. }
  1000. CompilationAndWeavingContext.leavingPhase(reweaveToken);
  1001. ContextToken typeMungingToken = CompilationAndWeavingContext.enteringPhase(
  1002. CompilationAndWeavingContext.PROCESSING_TYPE_MUNGERS, "");
  1003. requestor.addingTypeMungers();
  1004. // We process type mungers in two groups, first mungers that change the
  1005. // type
  1006. // hierarchy, then 'normal' ITD type mungers.
  1007. // Process the types in a predictable order (rather than the order
  1008. // encountered).
  1009. // For class A, the order is superclasses of A then superinterfaces of A
  1010. // (and this mechanism is applied recursively)
  1011. List<String> typesToProcess = new ArrayList<>();
  1012. for (Iterator<UnwovenClassFile> iter = input.getClassFileIterator(); iter.hasNext();) {
  1013. UnwovenClassFile clf = iter.next();
  1014. if (clf.shouldBeWoven()) {
  1015. typesToProcess.add(clf.getClassName());
  1016. }
  1017. }
  1018. while (typesToProcess.size() > 0) {
  1019. weaveParentsFor(typesToProcess, typesToProcess.get(0), null);
  1020. }
  1021. for (Iterator<UnwovenClassFile> i = input.getClassFileIterator(); i.hasNext();) {
  1022. UnwovenClassFile classFile = i.next();
  1023. if (classFile.shouldBeWoven()) {
  1024. String className = classFile.getClassName();
  1025. addNormalTypeMungers(className);
  1026. }
  1027. }
  1028. CompilationAndWeavingContext.leavingPhase(typeMungingToken);
  1029. requestor.weavingAspects();
  1030. ContextToken aspectToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_ASPECTS, "");
  1031. // first weave into aspects
  1032. for (Iterator<UnwovenClassFile> i = input.getClassFileIterator(); i.hasNext();) {
  1033. UnwovenClassFile classFile = i.next();
  1034. if (classFile.shouldBeWoven()) {
  1035. String className = classFile.getClassName();
  1036. ResolvedType theType = world.resolve(className);
  1037. if (theType.isAspect()) {
  1038. BcelObjectType classType = BcelWorld.getBcelObjectType(theType);
  1039. if (classType == null) {
  1040. // Sometimes.. if the Bcel Delegate couldn't be found then a
  1041. // problem occurred at compile time - on
  1042. // a previous compiler run. In this case I assert the
  1043. // delegate will still be an EclipseSourceType
  1044. // and we can ignore the problem here (the original compile
  1045. // error will be reported again from
  1046. // the eclipse source type) - pr113531
  1047. ReferenceTypeDelegate theDelegate = ((ReferenceType) theType).getDelegate();
  1048. if (theDelegate.getClass().getName().endsWith("EclipseSourceType")) {
  1049. continue;
  1050. }
  1051. throw new BCException("Can't find bcel delegate for " + className + " type=" + theType.getClass());
  1052. }
  1053. weaveAndNotify(classFile, classType, requestor);
  1054. wovenClassNames.add(className);
  1055. }
  1056. }
  1057. }
  1058. CompilationAndWeavingContext.leavingPhase(aspectToken);
  1059. requestor.weavingClasses();
  1060. ContextToken classToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_CLASSES, "");
  1061. // then weave into non-aspects
  1062. for (Iterator<UnwovenClassFile> i = input.getClassFileIterator(); i.hasNext();) {
  1063. UnwovenClassFile classFile = i.next();
  1064. if (classFile.shouldBeWoven()) {
  1065. String className = classFile.getClassName();
  1066. ResolvedType theType = world.resolve(className);
  1067. if (!theType.isAspect()) {
  1068. BcelObjectType classType = BcelWorld.getBcelObjectType(theType);
  1069. if (classType == null) {
  1070. // bug 119882 - see above comment for bug 113531
  1071. ReferenceTypeDelegate theDelegate = ((ReferenceType) theType).getDelegate();
  1072. // TODO urgh - put a method on the interface to check this,
  1073. // string compare is hideous
  1074. if (theDelegate.getClass().getName().endsWith("EclipseSourceType")) {
  1075. continue;
  1076. }
  1077. throw new BCException("Can't find bcel delegate for " + className + " type=" + theType.getClass());
  1078. }
  1079. weaveAndNotify(classFile, classType, requestor);
  1080. wovenClassNames.add(className);
  1081. }
  1082. }
  1083. }
  1084. CompilationAndWeavingContext.leavingPhase(classToken);
  1085. addedClasses.clear();
  1086. deletedTypenames.clear();
  1087. requestor.weaveCompleted();
  1088. CompilationAndWeavingContext.leavingPhase(weaveToken);
  1089. if (trace.isTraceEnabled()) {
  1090. trace.exit("weave", wovenClassNames);
  1091. }
  1092. if (world.getModel() != null && world.isMinimalModel()) {
  1093. candidatesForRemoval.clear();
  1094. }
  1095. return wovenClassNames;
  1096. }
  1097. public void allWeavingComplete() {
  1098. warnOnUnmatchedAdvice();
  1099. }
  1100. /**
  1101. * In 1.5 mode and with XLint:adviceDidNotMatch enabled, put out messages for any mungers that did not match anything.
  1102. */
  1103. private void warnOnUnmatchedAdvice() {
  1104. class AdviceLocation {
  1105. private final int lineNo;
  1106. private final UnresolvedType inAspect;
  1107. public AdviceLocation(BcelAdvice advice) {
  1108. this.lineNo = advice.getSourceLocation().getLine();
  1109. this.inAspect = advice.getDeclaringAspect();
  1110. }
  1111. @Override
  1112. public boolean equals(Object obj) {
  1113. if (!(obj instanceof AdviceLocation)) {
  1114. return false;
  1115. }
  1116. AdviceLocation other = (AdviceLocation) obj;
  1117. if (this.lineNo != other.lineNo) {
  1118. return false;
  1119. }
  1120. if (!this.inAspect.equals(other.inAspect)) {
  1121. return false;
  1122. }
  1123. return true;
  1124. }
  1125. @Override
  1126. public int hashCode() {
  1127. return 37 + 17 * lineNo + 17 * inAspect.hashCode();
  1128. }
  1129. }
  1130. // FIXME asc Should be factored out into Xlint code and done
  1131. // automatically for all xlint messages, ideally.
  1132. // if a piece of advice hasn't matched anywhere and we are in -1.5 mode,
  1133. // put out a warning
  1134. if (world.isInJava5Mode() && world.getLint().adviceDidNotMatch.isEnabled()) {
  1135. List<ShadowMunger> l = world.getCrosscuttingMembersSet().getShadowMungers();
  1136. Set<AdviceLocation> alreadyWarnedLocations = new HashSet<>();
  1137. for (ShadowMunger element : l) {
  1138. // This will stop us incorrectly reporting deow checkers:
  1139. if (element instanceof BcelAdvice) {
  1140. BcelAdvice ba = (BcelAdvice) element;
  1141. if (ba.getKind() == AdviceKind.CflowEntry || ba.getKind() == AdviceKind.CflowBelowEntry) {
  1142. continue;
  1143. }
  1144. if (!ba.hasMatchedSomething()) {
  1145. // Because we implement some features of AJ itself by
  1146. // creating our own kind of mungers, you sometimes
  1147. // find that ba.getSignature() is not a BcelMethod - for
  1148. // example it might be a cflow entry munger.
  1149. if (ba.getSignature() != null) {
  1150. // check we haven't already warned on this advice and line
  1151. // (cflow creates multiple mungers for the same advice)
  1152. AdviceLocation loc = new AdviceLocation(ba);
  1153. if (alreadyWarnedLocations.contains(loc)) {
  1154. continue;
  1155. } else {
  1156. alreadyWarnedLocations.add(loc);
  1157. }
  1158. if (!(ba.getSignature() instanceof BcelMethod)
  1159. || !Utility.isSuppressing(ba.getSignature(), "adviceDidNotMatch")) {
  1160. world.getLint().adviceDidNotMatch.signal(ba.getDeclaringAspect().toString(), new SourceLocation(
  1161. element.getSourceLocation().getSourceFile(), element.getSourceLocation().getLine()));
  1162. }
  1163. }
  1164. }
  1165. }
  1166. }
  1167. }
  1168. }
  1169. /**
  1170. * 'typeToWeave' is one from the 'typesForWeaving' list. This routine ensures we process supertypes (classes/interfaces) of
  1171. * 'typeToWeave' that are in the 'typesForWeaving' list before 'typeToWeave' itself. 'typesToWeave' is then removed from the
  1172. * 'typesForWeaving' list.
  1173. *
  1174. * Note: Future gotcha in here ... when supplying partial hierarchies, this algorithm may break down. If you have a hierarchy
  1175. * 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
  1176. * problems if you are supplying partial hierarchies like that !
  1177. */
  1178. private void weaveParentsFor(List<String> typesForWeaving, String typeToWeave, ResolvedType resolvedTypeToWeave) {
  1179. if (resolvedTypeToWeave == null) {
  1180. // resolve it if the caller could not pass in the resolved type
  1181. resolvedTypeToWeave = world.resolve(typeToWeave);
  1182. }
  1183. ResolvedType superclassType = resolvedTypeToWeave.getSuperclass();
  1184. String superclassTypename = (superclassType == null ? null : superclassType.getName());
  1185. // PR336654 added the 'typesForWeaving.contains(superclassTypename)' clause.
  1186. // Without it we can delete all type mungers on the parents and yet we only
  1187. // add back in the declare parents related ones, not the regular ITDs.
  1188. if (superclassType != null && !superclassType.isTypeHierarchyComplete() && superclassType.isExposedToWeaver()
  1189. && typesForWeaving.contains(superclassTypename)) {
  1190. weaveParentsFor(typesForWeaving, superclassTypename, superclassType);
  1191. }
  1192. ResolvedType[] interfaceTypes = resolvedTypeToWeave.getDeclaredInterfaces();
  1193. for (ResolvedType resolvedSuperInterface : interfaceTypes) {
  1194. if (!resolvedSuperInterface.isTypeHierarchyComplete()) {
  1195. String interfaceTypename = resolvedSuperInterface.getName();
  1196. if (resolvedSuperInterface.isExposedToWeaver()) { // typesForWeaving.contains(interfaceTypename)) {
  1197. weaveParentsFor(typesForWeaving, interfaceTypename, resolvedSuperInterface);
  1198. }
  1199. }
  1200. }
  1201. ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_DECLARE_PARENTS,
  1202. resolvedTypeToWeave.getName());
  1203. // If A was processed before B (and was declared 'class A implements B') then there is no need to complete B again, it
  1204. // will have been done whilst processing A.
  1205. if (!resolvedTypeToWeave.isTypeHierarchyComplete()) {
  1206. weaveParentTypeMungers(resolvedTypeToWeave);
  1207. }
  1208. CompilationAndWeavingContext.leavingPhase(tok);
  1209. typesForWeaving.remove(typeToWeave);
  1210. resolvedTypeToWeave.tagAsTypeHierarchyComplete();
  1211. }
  1212. public void prepareToProcessReweavableState() {
  1213. }
  1214. public void processReweavableStateIfPresent(String className, BcelObjectType classType) {
  1215. // If the class is marked reweavable, check any aspects around when it
  1216. // was built are in this world
  1217. WeaverStateInfo wsi = classType.getWeaverState();
  1218. // System.out.println(">> processReweavableStateIfPresent " + className + " wsi=" + wsi);
  1219. if (wsi != null && wsi.isReweavable()) { // Check all necessary types
  1220. // are around!
  1221. world.showMessage(IMessage.INFO, WeaverMessages.format(WeaverMessages.PROCESSING_REWEAVABLE, className, classType
  1222. .getSourceLocation().getSourceFile()), null, null);
  1223. Set<String> aspectsPreviouslyInWorld = wsi.getAspectsAffectingType();
  1224. // keep track of them just to ensure unique missing aspect error
  1225. // reporting
  1226. Set<String> alreadyConfirmedReweavableState = new HashSet<>();
  1227. for (String requiredTypeSignature : aspectsPreviouslyInWorld) {
  1228. // for (Iterator iter = aspectsPreviouslyInWorld.iterator(); iter.hasNext();) {
  1229. // String requiredTypeName = (String) iter.next();
  1230. if (!alreadyConfirmedReweavableState.contains(requiredTypeSignature)) {
  1231. ResolvedType rtx = world.resolve(UnresolvedType.forSignature(requiredTypeSignature), true);
  1232. boolean exists = !rtx.isMissing();
  1233. if (!world.isOverWeaving()) {
  1234. if (!exists) {
  1235. world.getLint().missingAspectForReweaving.signal(new String[] { rtx.getName(), className },
  1236. classType.getSourceLocation(), null);
  1237. // world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.MISSING_REWEAVABLE_TYPE,
  1238. // requiredTypeName, className), classType.getSourceLocation(), null);
  1239. } else {
  1240. // weaved in aspect that are not declared in aop.xml
  1241. // trigger an error for now
  1242. // may cause headhache for LTW and packaged lib
  1243. // without aop.xml in
  1244. // see #104218
  1245. if (!xcutSet.containsAspect(rtx)) {
  1246. world.showMessage(IMessage.ERROR, WeaverMessages.format(
  1247. WeaverMessages.REWEAVABLE_ASPECT_NOT_REGISTERED, rtx.getName(), className), null, null);
  1248. } else if (!world.getMessageHandler().isIgnoring(IMessage.INFO)) {
  1249. world.showMessage(IMessage.INFO, WeaverMessages.format(WeaverMessages.VERIFIED_REWEAVABLE_TYPE,
  1250. rtx.getName(), rtx.getSourceLocation().getSourceFile()), null, null);
  1251. }
  1252. alreadyConfirmedReweavableState.add(requiredTypeSignature);
  1253. }
  1254. }
  1255. }
  1256. }
  1257. // old:
  1258. // classType.setJavaClass(Utility.makeJavaClass(classType.getJavaClass
  1259. // ().getFileName(), wsi.getUnwovenClassFileData()));
  1260. // new: reweavable default with clever diff
  1261. if (!world.isOverWeaving()) {
  1262. byte[] ucfd = wsi.getUnwovenClassFileData();
  1263. if (ucfd.length == 0) {
  1264. // Size 0 indicates the class was previously overwoven, so you need to be overweaving now!
  1265. world.getMessageHandler().handleMessage(
  1266. MessageUtil.error(
  1267. WeaverMessages.format(WeaverMessages.MUST_KEEP_OVERWEAVING_ONCE_START,
  1268. className)));
  1269. // onType.getName(), annoX.getTypeName(), annoX.getValidTargets()),
  1270. // decA.getSourceLocation()));
  1271. } else {
  1272. byte[] bytes = wsi.getUnwovenClassFileData(classType.getJavaClass().getBytes());
  1273. JavaClass newJavaClass = Utility.makeJavaClass(classType.getJavaClass().getFileName(), bytes);
  1274. classType.setJavaClass(newJavaClass, true);
  1275. classType.getResolvedTypeX().ensureConsistent();
  1276. }
  1277. }
  1278. // } else {
  1279. // classType.resetState();
  1280. }
  1281. }
  1282. private void weaveAndNotify(UnwovenClassFile classFile, BcelObjectType classType, IWeaveRequestor requestor) throws IOException {
  1283. trace.enter("weaveAndNotify", this, new Object[] { classFile, classType, requestor });
  1284. ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_TYPE, classType
  1285. .getResolvedTypeX().getName());
  1286. LazyClassGen clazz = weaveWithoutDump(classFile, classType);
  1287. classType.finishedWith();
  1288. // clazz is null if the classfile was unchanged by weaving...
  1289. if (clazz != null) {
  1290. UnwovenClassFile[] newClasses = getClassFilesFor(clazz);
  1291. // OPTIMIZE can we avoid using the string name at all in
  1292. // UnwovenClassFile instances?
  1293. // Copy the char[] across as it means the
  1294. // WeaverAdapter.removeFromMap() can be fast!
  1295. if (newClasses[0].getClassName().equals(classFile.getClassName())) {
  1296. newClasses[0].setClassNameAsChars(classFile.getClassNameAsChars());
  1297. }
  1298. for (UnwovenClassFile newClass : newClasses) {
  1299. requestor.acceptResult(newClass);
  1300. }
  1301. } else {
  1302. requestor.acceptResult(classFile);
  1303. }
  1304. classType.weavingCompleted();
  1305. CompilationAndWeavingContext.leavingPhase(tok);
  1306. trace.exit("weaveAndNotify");
  1307. }
  1308. /**
  1309. * helper method - will return NULL if the underlying delegate is an EclipseSourceType and not a BcelObjectType
  1310. */
  1311. public BcelObjectType getClassType(String forClass) {
  1312. return BcelWorld.getBcelObjectType(world.resolve(forClass));
  1313. }
  1314. public void addParentTypeMungers(String typeName) {
  1315. weaveParentTypeMungers(world.resolve(typeName));
  1316. }
  1317. public void addNormalTypeMungers(String typeName) {
  1318. weaveNormalTypeMungers(world.resolve(typeName));
  1319. }
  1320. public UnwovenClassFile[] getClassFilesFor(LazyClassGen clazz) {
  1321. List<UnwovenClassFile.ChildClass> childClasses = clazz.getChildClasses(world);
  1322. UnwovenClassFile[] ret = new UnwovenClassFile[1 + childClasses.size()];
  1323. ret[0] = new UnwovenClassFile(clazz.getFileName(), clazz.getClassName(), clazz.getJavaClassBytesIncludingReweavable(world));
  1324. int index = 1;
  1325. for (UnwovenClassFile.ChildClass element : childClasses) {
  1326. UnwovenClassFile childClass = new UnwovenClassFile(clazz.getFileName() + "$" + element.name, element.bytes);
  1327. ret[index++] = childClass;
  1328. }
  1329. return ret;
  1330. }
  1331. /**
  1332. * Weaves new parents and annotations onto a type ("declare parents" and "declare @type")
  1333. *
  1334. * Algorithm: 1. First pass, do parents then do annotations. During this pass record: - any parent mungers that don't match but
  1335. * have a non-wild annotation type pattern - any annotation mungers that don't match 2. Multiple subsequent passes which go over
  1336. * the munger lists constructed in the first pass, repeatedly applying them until nothing changes. FIXME asc confirm that
  1337. * algorithm is optimal ??
  1338. */
  1339. public void weaveParentTypeMungers(ResolvedType onType) {
  1340. if (onType.isRawType() || onType.isParameterizedType()) {
  1341. onType = onType.getGenericType();
  1342. }
  1343. onType.clearInterTypeMungers();
  1344. List<DeclareParents> decpToRepeat = new ArrayList<>();
  1345. boolean aParentChangeOccurred = false;
  1346. boolean anAnnotationChangeOccurred = false;
  1347. // First pass - apply all decp mungers
  1348. for (DeclareParents decp : declareParentsList) {
  1349. boolean typeChanged = applyDeclareParents(decp, onType);
  1350. if (typeChanged) {
  1351. aParentChangeOccurred = true;
  1352. } else {
  1353. decpToRepeat.add(decp);
  1354. }
  1355. }
  1356. // Still first pass - apply all dec @type mungers
  1357. for (DeclareAnnotation decA : xcutSet.getDeclareAnnotationOnTypes()) {
  1358. boolean typeChanged = applyDeclareAtType(decA, onType, true);
  1359. if (typeChanged) {
  1360. anAnnotationChangeOccurred = true;
  1361. }
  1362. }
  1363. while ((aParentChangeOccurred || anAnnotationChangeOccurred) && !decpToRepeat.isEmpty()) {
  1364. anAnnotationChangeOccurred = aParentChangeOccurred = false;
  1365. List<DeclareParents> decpToRepeatNextTime = new ArrayList<>();
  1366. for (DeclareParents decp : decpToRepeat) {
  1367. boolean typeChanged = applyDeclareParents(decp, onType);
  1368. if (typeChanged) {
  1369. aParentChangeOccurred = true;
  1370. } else {
  1371. decpToRepeatNextTime.add(decp);
  1372. }
  1373. }
  1374. for (DeclareAnnotation decA : xcutSet.getDeclareAnnotationOnTypes()) {
  1375. boolean typeChanged = applyDeclareAtType(decA, onType, false);
  1376. if (typeChanged) {
  1377. anAnnotationChangeOccurred = true;
  1378. }
  1379. }
  1380. decpToRepeat = decpToRepeatNextTime;
  1381. }
  1382. }
  1383. /**
  1384. * Apply a declare @type - return true if we change the type
  1385. */
  1386. private boolean applyDeclareAtType(DeclareAnnotation decA, ResolvedType onType, boolean reportProblems) {
  1387. boolean didSomething = false;
  1388. if (decA.matches(onType)) {
  1389. AnnotationAJ theAnnotation = decA.getAnnotation();
  1390. // can be null for broken code!
  1391. if (theAnnotation == null) {
  1392. return false;
  1393. }
  1394. if (onType.hasAnnotation(theAnnotation.getType())) {
  1395. // Could put out a lint here for an already annotated type ...
  1396. // if (reportProblems) {
  1397. // world.getLint().elementAlreadyAnnotated.signal(
  1398. // new
  1399. // String[]{onType.toString(),decA.getAnnotationTypeX().toString
  1400. // ()},
  1401. // onType.getSourceLocation(),new
  1402. // ISourceLocation[]{decA.getSourceLocation()});
  1403. // }
  1404. return false;
  1405. }
  1406. AnnotationAJ annoX = decA.getAnnotation();
  1407. // check the annotation is suitable for the target
  1408. boolean problemReported = verifyTargetIsOK(decA, onType, annoX, reportProblems);
  1409. if (!problemReported) {
  1410. AsmRelationshipProvider.addDeclareAnnotationRelationship(world.getModelAsAsmManager(), decA.getSourceLocation(),
  1411. onType.getSourceLocation(), false);
  1412. // TAG: WeavingMessage
  1413. if (!getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) {
  1414. getWorld().getMessageHandler().handleMessage(
  1415. WeaveMessage.constructWeavingMessage(
  1416. WeaveMessage.WEAVEMESSAGE_ANNOTATES,
  1417. new String[] { onType.toString(), Utility.beautifyLocation(onType.getSourceLocation()),
  1418. decA.getAnnotationString(), "type", decA.getAspect().toString(),
  1419. Utility.beautifyLocation(decA.getSourceLocation()) }));
  1420. }
  1421. didSomething = true;
  1422. ResolvedTypeMunger newAnnotationTM = new AnnotationOnTypeMunger(annoX);
  1423. newAnnotationTM.setSourceLocation(decA.getSourceLocation());
  1424. onType.addInterTypeMunger(new BcelTypeMunger(newAnnotationTM, decA.getAspect().resolve(world)), false);
  1425. decA.copyAnnotationTo(onType);
  1426. }
  1427. }
  1428. return didSomething;
  1429. }
  1430. /**
  1431. * Checks for an @target() on the annotation and if found ensures it allows the annotation to be attached to the target type
  1432. * that matched.
  1433. */
  1434. private boolean verifyTargetIsOK(DeclareAnnotation decA, ResolvedType onType, AnnotationAJ annoX, boolean outputProblems) {
  1435. boolean problemReported = false;
  1436. if (annoX.specifiesTarget()) {
  1437. if ((onType.isAnnotation() && !annoX.allowedOnAnnotationType()) || (!annoX.allowedOnRegularType())) {
  1438. if (outputProblems) {
  1439. if (decA.isExactPattern()) {
  1440. world.getMessageHandler().handleMessage(
  1441. MessageUtil.error(
  1442. WeaverMessages.format(WeaverMessages.INCORRECT_TARGET_FOR_DECLARE_ANNOTATION,
  1443. onType.getName(), annoX.getTypeName(), annoX.getValidTargets()),
  1444. decA.getSourceLocation()));
  1445. } else {
  1446. if (world.getLint().invalidTargetForAnnotation.isEnabled()) {
  1447. world.getLint().invalidTargetForAnnotation.signal(new String[] { onType.getName(), annoX.getTypeName(),
  1448. annoX.getValidTargets() }, decA.getSourceLocation(),
  1449. new ISourceLocation[] { onType.getSourceLocation() });
  1450. }
  1451. }
  1452. }
  1453. problemReported = true;
  1454. }
  1455. }
  1456. return problemReported;
  1457. }
  1458. /**
  1459. * Apply a single declare parents - return true if we change the type
  1460. */
  1461. private boolean applyDeclareParents(DeclareParents p, ResolvedType onType) {
  1462. boolean didSomething = false;
  1463. List<ResolvedType> newParents = p.findMatchingNewParents(onType, true);
  1464. if (!newParents.isEmpty()) {
  1465. didSomething = true;
  1466. BcelWorld.getBcelObjectType(onType);
  1467. // System.err.println("need to do declare parents for: " + onType);
  1468. for (ResolvedType newParent : newParents) {
  1469. // We set it here so that the imminent matching for ITDs can
  1470. // succeed - we still haven't done the necessary changes to the class file
  1471. // itself (like transform super calls) - that is done in
  1472. // BcelTypeMunger.mungeNewParent()
  1473. // classType.addParent(newParent);
  1474. onType.addParent(newParent);
  1475. NewParentTypeMunger newParentMunger = new NewParentTypeMunger(newParent, p.getDeclaringType());
  1476. if (p.isMixin()) {
  1477. newParentMunger.setIsMixin(true);
  1478. }
  1479. newParentMunger.setSourceLocation(p.getSourceLocation());
  1480. onType.addInterTypeMunger(new BcelTypeMunger(newParentMunger, xcutSet.findAspectDeclaringParents(p)), false);
  1481. }
  1482. }
  1483. return didSomething;
  1484. }
  1485. public void weaveNormalTypeMungers(ResolvedType onType) {
  1486. ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_TYPE_MUNGERS,
  1487. onType.getName());
  1488. if (onType.isRawType() || onType.isParameterizedType()) {
  1489. onType = onType.getGenericType();
  1490. }
  1491. for (ConcreteTypeMunger m : typeMungerList) {
  1492. if (!m.isLateMunger() && m.matches(onType)) {
  1493. onType.addInterTypeMunger(m, false);
  1494. }
  1495. }
  1496. CompilationAndWeavingContext.leavingPhase(tok);
  1497. }
  1498. // exposed for ClassLoader dynamic weaving
  1499. public LazyClassGen weaveWithoutDump(UnwovenClassFile classFile, BcelObjectType classType) throws IOException {
  1500. return weave(classFile, classType, false);
  1501. }
  1502. // FOR TESTING
  1503. LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType) throws IOException {
  1504. LazyClassGen ret = weave(classFile, classType, true);
  1505. return ret;
  1506. }
  1507. private LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType, boolean dump) throws IOException {
  1508. try {
  1509. if (classType.isSynthetic()) { // Don't touch synthetic classes
  1510. if (dump) {
  1511. dumpUnchanged(classFile);
  1512. }
  1513. return null;
  1514. }
  1515. ReferenceType resolvedClassType = classType.getResolvedTypeX();
  1516. if (world.isXmlConfigured() && world.getXmlConfiguration().excludesType(resolvedClassType)) {
  1517. if (!world.getMessageHandler().isIgnoring(IMessage.INFO)) {
  1518. world.getMessageHandler().handleMessage(
  1519. MessageUtil.info("Type '" + resolvedClassType.getName()
  1520. + "' not woven due to exclusion via XML weaver exclude section"));
  1521. }
  1522. if (dump) {
  1523. dumpUnchanged(classFile);
  1524. }
  1525. return null;
  1526. }
  1527. List<ShadowMunger> shadowMungers = fastMatch(shadowMungerList, resolvedClassType);
  1528. List<ConcreteTypeMunger> typeMungers = classType.getResolvedTypeX().getInterTypeMungers();
  1529. resolvedClassType.checkInterTypeMungers();
  1530. // Decide if we need to do actual weaving for this class
  1531. boolean mightNeedToWeave = shadowMungers.size() > 0 || typeMungers.size() > 0 || classType.isAspect()
  1532. || world.getDeclareAnnotationOnMethods().size() > 0 || world.getDeclareAnnotationOnFields().size() > 0;
  1533. // May need bridge methods if on 1.5 and something in our hierarchy is
  1534. // affected by ITDs
  1535. boolean mightNeedBridgeMethods = world.isInJava5Mode() && !classType.isInterface()
  1536. && resolvedClassType.getInterTypeMungersIncludingSupers().size() > 0;
  1537. LazyClassGen clazz = null;
  1538. if (mightNeedToWeave || mightNeedBridgeMethods) {
  1539. clazz = classType.getLazyClassGen();
  1540. // System.err.println("got lazy gen: " + clazz + ", " +
  1541. // clazz.getWeaverState());
  1542. try {
  1543. boolean isChanged = false;
  1544. if (mightNeedToWeave) {
  1545. isChanged = BcelClassWeaver.weave(world, clazz, shadowMungers, typeMungers, lateTypeMungerList,
  1546. inReweavableMode);
  1547. }
  1548. checkDeclareTypeErrorOrWarning(world, classType);
  1549. if (mightNeedBridgeMethods) {
  1550. isChanged = BcelClassWeaver.calculateAnyRequiredBridgeMethods(world, clazz) || isChanged;
  1551. }
  1552. if (isChanged) {
  1553. if (dump) {
  1554. dump(classFile, clazz);
  1555. }
  1556. return clazz;
  1557. }
  1558. } catch (RuntimeException re) {
  1559. String classDebugInfo = null;
  1560. try {
  1561. classDebugInfo = clazz.toLongString();
  1562. } catch (Throwable e) {
  1563. new RuntimeException("Crashed whilst crashing with this exception: " + e, e).printStackTrace();
  1564. // recover from crash whilst producing debug string
  1565. classDebugInfo = clazz.getClassName();
  1566. }
  1567. String messageText = "trouble in: \n" + classDebugInfo;
  1568. getWorld().getMessageHandler().handleMessage(new Message(messageText, IMessage.ABORT, re, null));
  1569. } catch (Error re) {
  1570. String classDebugInfo = null;
  1571. try {
  1572. classDebugInfo = clazz.toLongString();
  1573. } catch (OutOfMemoryError oome) {
  1574. System.err.println("Ran out of memory creating debug info for an error");
  1575. re.printStackTrace(System.err);
  1576. // recover from crash whilst producing debug string
  1577. classDebugInfo = clazz.getClassName();
  1578. } catch (Throwable e) {
  1579. // recover from crash whilst producing debug string
  1580. classDebugInfo = clazz.getClassName();
  1581. }
  1582. String messageText = "trouble in: \n" + classDebugInfo;
  1583. getWorld().getMessageHandler().handleMessage(new Message(messageText, IMessage.ABORT, re, null));
  1584. }
  1585. } else {
  1586. checkDeclareTypeErrorOrWarning(world, classType);
  1587. }
  1588. // this is very odd return behavior trying to keep everyone happy
  1589. // can we remove it from the model now? we know it contains no relationship endpoints...
  1590. AsmManager model = world.getModelAsAsmManager();
  1591. if (world.isMinimalModel() && model != null && !classType.isAspect()) {
  1592. AspectJElementHierarchy hierarchy = (AspectJElementHierarchy) model.getHierarchy();
  1593. String pkgname = classType.getResolvedTypeX().getPackageName();
  1594. String tname = classType.getResolvedTypeX().getSimpleBaseName();
  1595. IProgramElement typeElement = hierarchy.findElementForType(pkgname, tname);
  1596. if (typeElement != null && hasInnerType(typeElement)) {
  1597. // Cannot remove it right now (has inner type), schedule it
  1598. // for possible deletion later if all inner types are
  1599. // removed
  1600. candidatesForRemoval.add(typeElement);
  1601. }
  1602. if (typeElement != null && !hasInnerType(typeElement)) {
  1603. IProgramElement parent = typeElement.getParent();
  1604. // parent may have children: PACKAGE DECL, IMPORT-REFERENCE, TYPE_DECL
  1605. if (parent != null) {
  1606. // if it was the only type we should probably remove
  1607. // the others too.
  1608. parent.removeChild(typeElement);
  1609. if (parent.getKind().isSourceFile()) {
  1610. removeSourceFileIfNoMoreTypeDeclarationsInside(hierarchy, typeElement, parent);
  1611. } else {
  1612. hierarchy.forget(null, typeElement);
  1613. // At this point, the child has been removed. We
  1614. // should now check if the parent is in our
  1615. // 'candidatesForRemoval' set. If it is then that
  1616. // means we were going to remove it but it had a
  1617. // child. Now we can check if it still has a child -
  1618. // if it doesn't it can also be removed!
  1619. walkUpRemovingEmptyTypesAndPossiblyEmptySourceFile(hierarchy, tname, parent);
  1620. }
  1621. }
  1622. }
  1623. }
  1624. if (dump) {
  1625. dumpUnchanged(classFile);
  1626. return clazz;
  1627. } else {
  1628. // ATAJ: the class was not weaved, but since it gets there early it
  1629. // may have new generated inner classes
  1630. // attached to it to support LTW perX aspectOf support (see
  1631. // BcelPerClauseAspectAdder)
  1632. // that aggressively defines the inner <aspect>$mayHaveAspect
  1633. // interface.
  1634. if (clazz != null && !clazz.getChildClasses(world).isEmpty()) {
  1635. return clazz;
  1636. }
  1637. return null;
  1638. }
  1639. } finally {
  1640. world.demote();
  1641. }
  1642. }
  1643. private void walkUpRemovingEmptyTypesAndPossiblyEmptySourceFile(AspectJElementHierarchy hierarchy, String tname,
  1644. IProgramElement typeThatHasChildRemoved) {
  1645. // typeThatHasChildRemoved might be a source file, type or a method/ctor
  1646. // - for a method/ctor find the type/sourcefile
  1647. while (typeThatHasChildRemoved != null
  1648. && !(typeThatHasChildRemoved.getKind().isType() || typeThatHasChildRemoved.getKind().isSourceFile())) {
  1649. // this will take us 'up' through methods that contain anonymous
  1650. // inner classes
  1651. typeThatHasChildRemoved = typeThatHasChildRemoved.getParent();
  1652. }
  1653. // now typeThatHasChildRemoved points to the type or sourcefile that has
  1654. // had something removed
  1655. if (candidatesForRemoval.contains(typeThatHasChildRemoved) && !hasInnerType(typeThatHasChildRemoved)) {
  1656. // now we can get rid of it
  1657. IProgramElement parent = typeThatHasChildRemoved.getParent();
  1658. if (parent != null) {
  1659. parent.removeChild(typeThatHasChildRemoved);
  1660. candidatesForRemoval.remove(typeThatHasChildRemoved);
  1661. if (parent.getKind().isSourceFile()) {
  1662. removeSourceFileIfNoMoreTypeDeclarationsInside(hierarchy, typeThatHasChildRemoved, parent);
  1663. // System.out.println("Removed on second pass: " +
  1664. // typeThatHasChildRemoved.getName());
  1665. } else {
  1666. // System.out.println("On later pass, parent of type " +
  1667. // typeThatHasChildRemoved.getName()
  1668. // + " was found not to be a sourcefile, recursing up...");
  1669. walkUpRemovingEmptyTypesAndPossiblyEmptySourceFile(hierarchy, tname, parent);
  1670. }
  1671. }
  1672. }
  1673. }
  1674. private void removeSourceFileIfNoMoreTypeDeclarationsInside(AspectJElementHierarchy hierarchy, IProgramElement typeElement,
  1675. IProgramElement sourceFileNode) {
  1676. IProgramElement compilationUnit = sourceFileNode;
  1677. boolean anyOtherTypeDeclarations = false;
  1678. for (IProgramElement child : compilationUnit.getChildren()) {
  1679. IProgramElement.Kind k = child.getKind();
  1680. if (k.isType()) {
  1681. anyOtherTypeDeclarations = true;
  1682. break;
  1683. }
  1684. }
  1685. // If the compilation unit node contained no
  1686. // other types, there is no need to keep it
  1687. if (!anyOtherTypeDeclarations) {
  1688. IProgramElement cuParent = compilationUnit.getParent();
  1689. if (cuParent != null) {
  1690. compilationUnit.setParent(null);
  1691. cuParent.removeChild(compilationUnit);
  1692. }
  1693. // need to update some caches and structures too?
  1694. hierarchy.forget(sourceFileNode, typeElement);
  1695. } else {
  1696. hierarchy.forget(null, typeElement);
  1697. }
  1698. }
  1699. // ---- writing
  1700. // TODO could be smarter - really only matters if inner type has been woven, but there is a chance we haven't woven it *yet*
  1701. private boolean hasInnerType(IProgramElement typeNode) {
  1702. for (IProgramElement child : typeNode.getChildren()) {
  1703. IProgramElement.Kind kind = child.getKind();
  1704. if (kind.isType()) {
  1705. return true;
  1706. }
  1707. // if (kind == IProgramElement.Kind.ASPECT) {
  1708. // return true;
  1709. // }
  1710. if (kind.isType() || kind == IProgramElement.Kind.METHOD || kind == IProgramElement.Kind.CONSTRUCTOR) {
  1711. boolean b = hasInnerType(child);
  1712. if (b) {
  1713. return b;
  1714. }
  1715. }
  1716. }
  1717. return false;
  1718. }
  1719. private void checkDeclareTypeErrorOrWarning(BcelWorld world2, BcelObjectType classType) {
  1720. List<DeclareTypeErrorOrWarning> dteows = world.getDeclareTypeEows();
  1721. for (DeclareTypeErrorOrWarning dteow : dteows) {
  1722. if (dteow.getTypePattern().matchesStatically(classType.getResolvedTypeX())) {
  1723. if (dteow.isError()) {
  1724. world.getMessageHandler().handleMessage(
  1725. MessageUtil.error(dteow.getMessage(), classType.getResolvedTypeX().getSourceLocation()));
  1726. } else {
  1727. world.getMessageHandler().handleMessage(
  1728. MessageUtil.warn(dteow.getMessage(), classType.getResolvedTypeX().getSourceLocation()));
  1729. }
  1730. }
  1731. }
  1732. }
  1733. private void dumpUnchanged(UnwovenClassFile classFile) throws IOException {
  1734. if (zipOutputStream != null) {
  1735. writeZipEntry(getEntryName(classFile.getJavaClass().getClassName()), classFile.getBytes());
  1736. } else {
  1737. classFile.writeUnchangedBytes();
  1738. }
  1739. }
  1740. private String getEntryName(String className) {
  1741. // XXX what does bcel's getClassName do for inner names
  1742. return className.replace('.', '/') + ".class";
  1743. }
  1744. private void dump(UnwovenClassFile classFile, LazyClassGen clazz) throws IOException {
  1745. if (zipOutputStream != null) {
  1746. String mainClassName = classFile.getJavaClass().getClassName();
  1747. writeZipEntry(getEntryName(mainClassName), clazz.getJavaClass(world).getBytes());
  1748. List<UnwovenClassFile.ChildClass> childClasses = clazz.getChildClasses(world);
  1749. if (!childClasses.isEmpty()) {
  1750. for (UnwovenClassFile.ChildClass c : childClasses) {
  1751. writeZipEntry(getEntryName(mainClassName + "$" + c.name), c.bytes);
  1752. }
  1753. }
  1754. } else {
  1755. classFile.writeWovenBytes(clazz.getJavaClass(world).getBytes(), clazz.getChildClasses(world));
  1756. }
  1757. }
  1758. private void writeZipEntry(String name, byte[] bytes) throws IOException {
  1759. ZipEntry newEntry = new ZipEntry(name); // ??? get compression scheme
  1760. // right
  1761. zipOutputStream.putNextEntry(newEntry);
  1762. zipOutputStream.write(bytes);
  1763. zipOutputStream.closeEntry();
  1764. }
  1765. /**
  1766. * Perform a fast match of the specified list of shadowmungers against the specified type. A subset of those that might match is
  1767. * returned.
  1768. *
  1769. * @param list list of all shadow mungers that might match
  1770. * @param type the target type
  1771. * @return a list of shadow mungers that might match with those that cannot (according to fast match rules) removed
  1772. */
  1773. private List<ShadowMunger> fastMatch(List<ShadowMunger> list, ResolvedType type) {
  1774. if (list == null) {
  1775. return Collections.emptyList();
  1776. }
  1777. boolean isOverweaving = world.isOverWeaving();
  1778. WeaverStateInfo typeWeaverState = (isOverweaving ? type.getWeaverState() : null);
  1779. // here we do the coarsest grained fast match with no kind constraints
  1780. // this will remove all obvious non-matches and see if we need to do any
  1781. // weaving
  1782. FastMatchInfo info = new FastMatchInfo(type, null, world);
  1783. List<ShadowMunger> result = new ArrayList<>();
  1784. if (world.areInfoMessagesEnabled() && world.isTimingEnabled()) {
  1785. for (ShadowMunger munger : list) {
  1786. if (typeWeaverState != null) { // will only be null if overweaving is ON and there is weaverstate
  1787. ResolvedType declaringAspect = munger.getDeclaringType();
  1788. if (typeWeaverState.isAspectAlreadyApplied(declaringAspect)) {
  1789. continue;
  1790. }
  1791. }
  1792. Pointcut pointcut = munger.getPointcut();
  1793. long starttime = System.nanoTime();
  1794. FuzzyBoolean fb = pointcut.fastMatch(info);
  1795. long endtime = System.nanoTime();
  1796. world.recordFastMatch(pointcut, endtime - starttime);
  1797. if (fb.maybeTrue()) {
  1798. result.add(munger);
  1799. }
  1800. }
  1801. } else {
  1802. for (ShadowMunger munger : list) {
  1803. if (typeWeaverState != null) { // will only be null if overweaving is ON and there is weaverstate
  1804. ResolvedType declaringAspect = munger.getConcreteAspect();// getDeclaringType();
  1805. if (typeWeaverState.isAspectAlreadyApplied(declaringAspect)) {
  1806. continue;
  1807. }
  1808. }
  1809. Pointcut pointcut = munger.getPointcut();
  1810. FuzzyBoolean fb = pointcut.fastMatch(info);
  1811. if (fb.maybeTrue()) {
  1812. result.add(munger);
  1813. }
  1814. }
  1815. }
  1816. return result;
  1817. }
  1818. public void setReweavableMode(boolean xNotReweavable) {
  1819. inReweavableMode = !xNotReweavable;
  1820. WeaverStateInfo.setReweavableModeDefaults(!xNotReweavable, false, true);
  1821. }
  1822. public boolean isReweavable() {
  1823. return inReweavableMode;
  1824. }
  1825. public World getWorld() {
  1826. return world;
  1827. }
  1828. public void tidyUp() {
  1829. if (trace.isTraceEnabled()) {
  1830. trace.enter("tidyUp", this);
  1831. }
  1832. shadowMungerList = null; // setup by prepareForWeave
  1833. typeMungerList = null; // setup by prepareForWeave
  1834. lateTypeMungerList = null; // setup by prepareForWeave
  1835. declareParentsList = null; // setup by prepareForWeave
  1836. if (trace.isTraceEnabled()) {
  1837. trace.exit("tidyUp");
  1838. }
  1839. }
  1840. public void write(CompressingDataOutputStream dos) throws IOException {
  1841. xcutSet.write(dos);
  1842. }
  1843. // only called for testing
  1844. public void setShadowMungers(List<ShadowMunger> shadowMungers) {
  1845. shadowMungerList = shadowMungers;
  1846. }
  1847. }