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.

World.java 68KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039
  1. /* *******************************************************************
  2. * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
  3. * 2005,2020 Contributors
  4. * All rights reserved.
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Public License v1.0
  7. * which accompanies this distribution and is available at
  8. * http://www.eclipse.org/legal/epl-v10.html
  9. * ******************************************************************/
  10. package org.aspectj.weaver;
  11. import java.lang.ref.Reference;
  12. import java.lang.ref.ReferenceQueue;
  13. import java.lang.ref.SoftReference;
  14. import java.lang.ref.WeakReference;
  15. import java.util.ArrayList;
  16. import java.util.Collections;
  17. import java.util.HashMap;
  18. import java.util.HashSet;
  19. import java.util.List;
  20. import java.util.Map;
  21. import java.util.Properties;
  22. import java.util.Set;
  23. import java.util.WeakHashMap;
  24. import org.aspectj.bridge.IMessage;
  25. import org.aspectj.bridge.IMessage.Kind;
  26. import org.aspectj.bridge.IMessageHandler;
  27. import org.aspectj.bridge.ISourceLocation;
  28. import org.aspectj.bridge.Message;
  29. import org.aspectj.bridge.MessageUtil;
  30. import org.aspectj.bridge.context.PinpointingMessageHandler;
  31. import org.aspectj.util.IStructureModel;
  32. import org.aspectj.weaver.ResolvedType.Primitive;
  33. import org.aspectj.weaver.UnresolvedType.TypeKind;
  34. import org.aspectj.weaver.patterns.Declare;
  35. import org.aspectj.weaver.patterns.DeclareAnnotation;
  36. import org.aspectj.weaver.patterns.DeclareParents;
  37. import org.aspectj.weaver.patterns.DeclarePrecedence;
  38. import org.aspectj.weaver.patterns.DeclareSoft;
  39. import org.aspectj.weaver.patterns.DeclareTypeErrorOrWarning;
  40. import org.aspectj.weaver.patterns.Pointcut;
  41. import org.aspectj.weaver.patterns.TypePattern;
  42. import org.aspectj.weaver.tools.PointcutDesignatorHandler;
  43. import org.aspectj.weaver.tools.Trace;
  44. import org.aspectj.weaver.tools.TraceFactory;
  45. /**
  46. * A World is a collection of known types and crosscutting members.
  47. *
  48. * @author PARC
  49. * @author Adrian Colyer
  50. * @author Andy Clement
  51. * @author Abraham Nevado
  52. * @author Joseph MacFarlane
  53. */
  54. public abstract class World implements Dump.INode {
  55. /** handler for any messages produced during resolution etc. */
  56. private IMessageHandler messageHandler = IMessageHandler.SYSTEM_ERR;
  57. /** handler for cross-reference information produced during the weaving process */
  58. private ICrossReferenceHandler xrefHandler = null;
  59. /** Currently 'active' scope in which to lookup (resolve) typevariable references */
  60. private TypeVariableDeclaringElement typeVariableLookupScope;
  61. /** The heart of the world, a map from type signatures to resolved types */
  62. protected TypeMap typeMap = new TypeMap(this);
  63. /** New pointcut designators this world supports */
  64. private Set<PointcutDesignatorHandler> pointcutDesignators;
  65. // see pr145963
  66. /** Should we create the hierarchy for binary classes and aspects */
  67. public static boolean createInjarHierarchy = true;
  68. /** Calculator for working out aspect precedence */
  69. private final AspectPrecedenceCalculator precedenceCalculator;
  70. /** All of the type and shadow mungers known to us */
  71. private final CrosscuttingMembersSet crosscuttingMembersSet = new CrosscuttingMembersSet(this);
  72. /** The structure model for the compilation */
  73. private IStructureModel model = null;
  74. /** for processing Xlint messages */
  75. private Lint lint = new Lint(this);
  76. /** XnoInline option setting passed down to weaver */
  77. private boolean XnoInline;
  78. /** XlazyTjp option setting passed down to weaver */
  79. private boolean XlazyTjp;
  80. /** XhasMember option setting passed down to weaver */
  81. private boolean XhasMember = false;
  82. /** Xpinpoint controls whether we put out developer info showing the source of messages */
  83. private boolean Xpinpoint = false;
  84. /** When behaving in a Java 5 way autoboxing is considered */
  85. private boolean behaveInJava5Way = false;
  86. /** Should timing information be reported (as info messages)? */
  87. private boolean timing = false;
  88. private boolean timingPeriodically = true;
  89. /** Determines if this world could be used for multiple compiles */
  90. private boolean incrementalCompileCouldFollow = false;
  91. /** The level of the aspectjrt.jar the code we generate needs to run on */
  92. public static final RuntimeVersion RUNTIME_LEVEL_DEFAULT = RuntimeVersion.V1_5;
  93. private RuntimeVersion targetAspectjRuntimeLevel = RUNTIME_LEVEL_DEFAULT;
  94. /** Flags for the new joinpoints that are 'optional': -Xjoinpoints:arrayconstruction -Xjoinpoints:synchronization */
  95. private boolean optionalJoinpoint_ArrayConstruction = false;
  96. private boolean optionalJoinpoint_Synchronization = false;
  97. private boolean addSerialVerUID = false;
  98. private Properties extraConfiguration = null;
  99. private boolean checkedAdvancedConfiguration = false;
  100. private boolean synchronizationPointcutsInUse = false;
  101. // Xset'table options
  102. private boolean runMinimalMemory = false;
  103. private boolean transientTjpFields = false;
  104. private boolean runMinimalMemorySet = false;
  105. private boolean shouldPipelineCompilation = true;
  106. private boolean shouldGenerateStackMaps = false;
  107. protected boolean bcelRepositoryCaching = xsetBCEL_REPOSITORY_CACHING_DEFAULT.equalsIgnoreCase("true");
  108. private boolean fastMethodPacking = false;
  109. private int itdVersion = 2; // defaults to 2nd generation itds
  110. // Minimal Model controls whether model entities that are not involved in relationships are deleted post-build
  111. private boolean minimalModel = true;
  112. private boolean useFinal = true;
  113. private boolean targettingRuntime1_6_10 = false;
  114. private boolean completeBinaryTypes = false;
  115. private boolean overWeaving = false;
  116. private static boolean systemPropertyOverWeaving = false;
  117. public boolean forDEBUG_structuralChangesCode = false;
  118. public boolean forDEBUG_bridgingCode = false;
  119. public boolean optimizedMatching = true;
  120. public boolean generateNewLvts = true;
  121. protected long timersPerJoinpoint = 25000;
  122. protected long timersPerType = 250;
  123. public int infoMessagesEnabled = 0; // 0=uninitialized, 1=no, 2=yes
  124. private static Trace trace = TraceFactory.getTraceFactory().getTrace(World.class);
  125. private boolean errorThreshold;
  126. private boolean warningThreshold;
  127. /**
  128. * A list of RuntimeExceptions containing full stack information for every type we couldn't find.
  129. */
  130. private List<RuntimeException> dumpState_cantFindTypeExceptions = null;
  131. static {
  132. try {
  133. String value = System.getProperty("aspectj.overweaving", "false");
  134. if (value.equalsIgnoreCase("true")) {
  135. System.out.println("ASPECTJ: aspectj.overweaving=true: overweaving switched ON");
  136. systemPropertyOverWeaving = true;
  137. }
  138. } catch (Throwable t) {
  139. System.err.println("ASPECTJ: Unable to read system properties");
  140. t.printStackTrace();
  141. }
  142. }
  143. public final Primitive BYTE = new Primitive("B", 1, 0);
  144. public final Primitive CHAR = new Primitive("C", 1, 1);
  145. public final Primitive DOUBLE = new Primitive("D", 2, 2);
  146. public final Primitive FLOAT = new Primitive("F", 1, 3);
  147. public final Primitive INT = new Primitive("I", 1, 4);
  148. public final Primitive LONG = new Primitive("J", 2, 5);
  149. public final Primitive SHORT = new Primitive("S", 1, 6);
  150. public final Primitive BOOLEAN = new Primitive("Z", 1, 7);
  151. public final Primitive VOID = new Primitive("V", 0, 8);
  152. /**
  153. * Insert the primitives
  154. */
  155. protected World() {
  156. super();
  157. // Dump.registerNode(this.getClass(), this);
  158. typeMap.put("B", BYTE);
  159. typeMap.put("S", SHORT);
  160. typeMap.put("I", INT);
  161. typeMap.put("J", LONG);
  162. typeMap.put("F", FLOAT);
  163. typeMap.put("D", DOUBLE);
  164. typeMap.put("C", CHAR);
  165. typeMap.put("Z", BOOLEAN);
  166. typeMap.put("V", VOID);
  167. precedenceCalculator = new AspectPrecedenceCalculator(this);
  168. }
  169. /**
  170. * Dump processing when a fatal error occurs
  171. */
  172. @Override
  173. public void accept(Dump.IVisitor visitor) {
  174. // visitor.visitObject("Extra configuration:");
  175. // visitor.visitList(extraConfiguration.);
  176. visitor.visitObject("Shadow mungers:");
  177. visitor.visitList(crosscuttingMembersSet.getShadowMungers());
  178. visitor.visitObject("Type mungers:");
  179. visitor.visitList(crosscuttingMembersSet.getTypeMungers());
  180. visitor.visitObject("Late Type mungers:");
  181. visitor.visitList(crosscuttingMembersSet.getLateTypeMungers());
  182. if (dumpState_cantFindTypeExceptions != null) {
  183. visitor.visitObject("Cant find type problems:");
  184. visitor.visitList(dumpState_cantFindTypeExceptions);
  185. dumpState_cantFindTypeExceptions = null;
  186. }
  187. }
  188. // ==========================================================================
  189. // T Y P E R E S O L U T I O N
  190. // ==========================================================================
  191. /**
  192. * Resolve a type that we require to be present in the world
  193. */
  194. public ResolvedType resolve(UnresolvedType ty) {
  195. return resolve(ty, false);
  196. }
  197. /**
  198. * Attempt to resolve a type - the source location gives you some context in which resolution is taking place. In the case of an
  199. * error where we can't find the type - we can then at least report why (source location) we were trying to resolve it.
  200. */
  201. public ResolvedType resolve(UnresolvedType ty, ISourceLocation isl) {
  202. ResolvedType ret = resolve(ty, true);
  203. if (ResolvedType.isMissing(ty)) {
  204. // IMessage msg = null;
  205. getLint().cantFindType.signal(WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE, ty.getName()), isl);
  206. // if (isl!=null) {
  207. // msg = MessageUtil.error(WeaverMessages.format(WeaverMessages.
  208. // CANT_FIND_TYPE,ty.getName()),isl);
  209. // } else {
  210. // msg = MessageUtil.error(WeaverMessages.format(WeaverMessages.
  211. // CANT_FIND_TYPE,ty.getName()));
  212. // }
  213. // messageHandler.handleMessage(msg);
  214. }
  215. return ret;
  216. }
  217. /**
  218. * Convenience method for resolving an array of unresolved types in one hit. Useful for e.g. resolving type parameters in
  219. * signatures.
  220. */
  221. public ResolvedType[] resolve(UnresolvedType[] types) {
  222. if (types == null) {
  223. return ResolvedType.NONE;
  224. }
  225. ResolvedType[] ret = new ResolvedType[types.length];
  226. for (int i = 0; i < types.length; i++) {
  227. ret[i] = resolve(types[i]);
  228. }
  229. return ret;
  230. }
  231. /**
  232. * Resolve a type. This the hub of type resolution. The resolved type is added to the type map by signature.
  233. */
  234. public ResolvedType resolve(UnresolvedType ty, boolean allowMissing) {
  235. // special resolution processing for already resolved types.
  236. if (ty instanceof ResolvedType) {
  237. ResolvedType rty = (ResolvedType) ty;
  238. rty = resolve(rty);
  239. // A TypeVariableReferenceType may look like it is resolved (it extends ResolvedType) but the internal
  240. // type variable may not yet have been resolved
  241. if (!rty.isTypeVariableReference() || ((TypeVariableReferenceType) rty).isTypeVariableResolved()) {
  242. return rty;
  243. }
  244. }
  245. // dispatch back to the type variable reference to resolve its
  246. // constituent parts don't do this for other unresolved types otherwise
  247. // you'll end up in a
  248. // loop
  249. if (ty.isTypeVariableReference()) {
  250. return ty.resolve(this);
  251. }
  252. // if we've already got a resolved type for the signature, just return
  253. // it
  254. // after updating the world
  255. String signature = ty.getSignature();
  256. ResolvedType ret = typeMap.get(signature);
  257. if (ret != null) {
  258. ret.world = this; // Set the world for the RTX
  259. return ret;
  260. } else if (signature.equals("?") || signature.equals("*")) {
  261. // might be a problem here, not sure '?' should make it to here as a
  262. // signature, the
  263. // proper signature for wildcard '?' is '*'
  264. // fault in generic wildcard, can't be done earlier because of init
  265. // issues
  266. // TODO ought to be shared single instance representing this
  267. ResolvedType something = getWildcard();
  268. typeMap.put("?", something);
  269. return something;
  270. }
  271. // no existing resolved type, create one
  272. synchronized (buildingTypeLock) {
  273. if (ty.isArray()) {
  274. ResolvedType componentType = resolve(ty.getComponentType(), allowMissing);
  275. ret = new ArrayReferenceType(signature, "[" + componentType.getErasureSignature(), this, componentType);
  276. } else {
  277. ret = resolveToReferenceType(ty, allowMissing);
  278. if (!allowMissing && ret.isMissing()) {
  279. ret = handleRequiredMissingTypeDuringResolution(ty);
  280. }
  281. if (completeBinaryTypes) {
  282. completeBinaryType(ret);
  283. }
  284. }
  285. }
  286. // Pulling in the type may have already put the right entry in the map
  287. ResolvedType result = typeMap.get(signature);
  288. if (result == null && !ret.isMissing()) {
  289. ret = ensureRawTypeIfNecessary(ret);
  290. typeMap.put(signature, ret);
  291. return ret;
  292. }
  293. if (result == null) {
  294. return ret;
  295. } else {
  296. return result;
  297. }
  298. }
  299. private Object buildingTypeLock = new Object();
  300. // Only need one representation of '?' in a world - can be shared
  301. private BoundedReferenceType wildcard;
  302. private BoundedReferenceType getWildcard() {
  303. if (wildcard == null) {
  304. wildcard = new BoundedReferenceType(this);
  305. }
  306. return wildcard;
  307. }
  308. /**
  309. * Called when a type is resolved - enables its type hierarchy to be finished off before we proceed
  310. */
  311. protected void completeBinaryType(ResolvedType ret) {
  312. }
  313. /**
  314. * Return true if the classloader relating to this world is definetly the one that will define the specified class. Return false
  315. * otherwise or we don't know for certain.
  316. */
  317. public boolean isLocallyDefined(String classname) {
  318. return false;
  319. }
  320. /**
  321. * We tried to resolve a type and couldn't find it...
  322. */
  323. private ResolvedType handleRequiredMissingTypeDuringResolution(UnresolvedType ty) {
  324. // defer the message until someone asks a question of the type that we
  325. // can't answer
  326. // just from the signature.
  327. // MessageUtil.error(messageHandler,
  328. // WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE,ty.getName()));
  329. if (dumpState_cantFindTypeExceptions == null) {
  330. dumpState_cantFindTypeExceptions = new ArrayList<RuntimeException>();
  331. }
  332. if (dumpState_cantFindTypeExceptions.size() < 100) { // limit growth
  333. dumpState_cantFindTypeExceptions.add(new RuntimeException("Can't find type " + ty.getName()));
  334. }
  335. return new MissingResolvedTypeWithKnownSignature(ty.getSignature(), this);
  336. }
  337. /**
  338. * Some TypeFactory operations create resolved types directly, but these won't be in the typeMap - this resolution process puts
  339. * them there. Resolved types are also told their world which is needed for the special autoboxing resolved types.
  340. */
  341. public ResolvedType resolve(ResolvedType ty) {
  342. if (ty.isTypeVariableReference()) {
  343. return ty; // until type variables have proper sigs...
  344. }
  345. ResolvedType resolved = typeMap.get(ty.getSignature());
  346. if (resolved == null) {
  347. resolved = ensureRawTypeIfNecessary(ty);
  348. typeMap.put(ty.getSignature(), resolved);
  349. resolved = ty;
  350. }
  351. resolved.world = this;
  352. return resolved;
  353. }
  354. /**
  355. * When the world is operating in 1.5 mode, the TypeMap should only contain RAW types and never directly generic types. The RAW
  356. * type will contain a reference to the generic type.
  357. *
  358. * @param type a possibly generic type for which the raw needs creating as it is not currently in the world
  359. * @return a type suitable for putting into the world
  360. */
  361. private ResolvedType ensureRawTypeIfNecessary(ResolvedType type) {
  362. if (!isInJava5Mode() || type.isRawType()) {
  363. return type;
  364. }
  365. // Key requirement here is if it is generic, create a RAW entry to be put in the map that points to it
  366. if (type instanceof ReferenceType && ((ReferenceType) type).getDelegate() != null && type.isGenericType()) {
  367. ReferenceType rawType = new ReferenceType(type.getSignature(), this);
  368. rawType.typeKind = UnresolvedType.TypeKind.RAW;
  369. ReferenceTypeDelegate delegate = ((ReferenceType) type).getDelegate();
  370. rawType.setDelegate(delegate);
  371. rawType.setGenericType((ReferenceType) type);
  372. return rawType;
  373. }
  374. // probably parameterized...
  375. return type;
  376. }
  377. /**
  378. * Convenience method for finding a type by name and resolving it in one step.
  379. */
  380. public ResolvedType resolve(String name) {
  381. // trace.enter("resolve", this, new Object[] {name});
  382. ResolvedType ret = resolve(UnresolvedType.forName(name));
  383. // trace.exit("resolve", ret);
  384. return ret;
  385. }
  386. public ReferenceType resolveToReferenceType(String name) {
  387. return (ReferenceType) resolve(name);
  388. }
  389. public ResolvedType resolve(String name, boolean allowMissing) {
  390. return resolve(UnresolvedType.forName(name), allowMissing);
  391. }
  392. /**
  393. * Resolve to a ReferenceType - simple, raw, parameterized, or generic. Raw, parameterized, and generic versions of a type share
  394. * a delegate.
  395. */
  396. private final ResolvedType resolveToReferenceType(UnresolvedType ty, boolean allowMissing) {
  397. if (ty.isParameterizedType()) {
  398. // ======= parameterized types ================
  399. ResolvedType rt = resolveGenericTypeFor(ty, allowMissing);
  400. if (rt.isMissing()) {
  401. return rt;
  402. }
  403. ReferenceType genericType = (ReferenceType) rt;
  404. ReferenceType parameterizedType = TypeFactory.createParameterizedType(genericType, ty.typeParameters, this);
  405. return parameterizedType;
  406. } else if (ty.isGenericType()) {
  407. // ======= generic types ======================
  408. ResolvedType rt = resolveGenericTypeFor(ty, false);
  409. if (rt.isMissing()) {
  410. return rt;
  411. }
  412. ReferenceType genericType = (ReferenceType) rt;
  413. if (rt.isMissing()) {
  414. return rt;
  415. }
  416. return genericType;
  417. } else if (ty.isGenericWildcard()) {
  418. // ======= generic wildcard types =============
  419. return resolveGenericWildcardFor((WildcardedUnresolvedType) ty);
  420. } else {
  421. // ======= simple and raw types ===============
  422. String erasedSignature = ty.getErasureSignature();
  423. ReferenceType simpleOrRawType = new ReferenceType(erasedSignature, this);
  424. if (ty.needsModifiableDelegate()) {
  425. simpleOrRawType.setNeedsModifiableDelegate(true);
  426. }
  427. ReferenceTypeDelegate delegate = resolveDelegate(simpleOrRawType);
  428. if (delegate == null) {
  429. return new MissingResolvedTypeWithKnownSignature(ty.getSignature(), erasedSignature, this);
  430. }
  431. if (delegate.isGeneric() && behaveInJava5Way) {
  432. // ======== raw type ===========
  433. simpleOrRawType.typeKind = TypeKind.RAW;
  434. if (simpleOrRawType.hasNewInterfaces()) { // debug 375777
  435. throw new IllegalStateException(
  436. "Simple type promoted forced to raw, but it had new interfaces/superclass. Type is "
  437. + simpleOrRawType.getName());
  438. }
  439. ReferenceType genericType = makeGenericTypeFrom(delegate, simpleOrRawType);
  440. simpleOrRawType.setDelegate(delegate);
  441. genericType.setDelegate(delegate);
  442. simpleOrRawType.setGenericType(genericType);
  443. return simpleOrRawType;
  444. } else {
  445. // ======== simple type =========
  446. simpleOrRawType.setDelegate(delegate);
  447. return simpleOrRawType;
  448. }
  449. }
  450. }
  451. /**
  452. * Attempt to resolve a type that should be a generic type.
  453. */
  454. public ResolvedType resolveGenericTypeFor(UnresolvedType anUnresolvedType, boolean allowMissing) {
  455. // Look up the raw type by signature
  456. String rawSignature = anUnresolvedType.getRawType().getSignature();
  457. ResolvedType rawType = typeMap.get(rawSignature);
  458. if (rawType == null) {
  459. rawType = resolve(UnresolvedType.forSignature(rawSignature), allowMissing);
  460. typeMap.put(rawSignature, rawType);
  461. }
  462. if (rawType.isMissing()) {
  463. return rawType;
  464. }
  465. // Does the raw type know its generic form? (It will if we created the
  466. // raw type from a source type, it won't if its been created just
  467. // through
  468. // being referenced, e.g. java.util.List
  469. ResolvedType genericType = rawType.getGenericType();
  470. // There is a special case to consider here (testGenericsBang_pr95993
  471. // highlights it)
  472. // You may have an unresolvedType for a parameterized type but it
  473. // is backed by a simple type rather than a generic type. This occurs
  474. // for
  475. // inner types of generic types that inherit their enclosing types
  476. // type variables.
  477. if (rawType.isSimpleType() && (anUnresolvedType.typeParameters == null || anUnresolvedType.typeParameters.length == 0)) {
  478. rawType.world = this;
  479. return rawType;
  480. }
  481. if (genericType != null) {
  482. genericType.world = this;
  483. return genericType;
  484. } else {
  485. // Fault in the generic that underpins the raw type ;)
  486. ReferenceTypeDelegate delegate = resolveDelegate((ReferenceType) rawType);
  487. ReferenceType genericRefType = makeGenericTypeFrom(delegate, ((ReferenceType) rawType));
  488. ((ReferenceType) rawType).setGenericType(genericRefType);
  489. genericRefType.setDelegate(delegate);
  490. ((ReferenceType) rawType).setDelegate(delegate);
  491. return genericRefType;
  492. }
  493. }
  494. private ReferenceType makeGenericTypeFrom(ReferenceTypeDelegate delegate, ReferenceType rawType) {
  495. String genericSig = delegate.getDeclaredGenericSignature();
  496. if (genericSig != null) {
  497. return new ReferenceType(UnresolvedType.forGenericTypeSignature(rawType.getSignature(),
  498. delegate.getDeclaredGenericSignature()), this);
  499. } else {
  500. return new ReferenceType(UnresolvedType.forGenericTypeVariables(rawType.getSignature(), delegate.getTypeVariables()),
  501. this);
  502. }
  503. }
  504. /**
  505. * Go from an unresolved generic wildcard (represented by UnresolvedType) to a resolved version (BoundedReferenceType).
  506. */
  507. private ReferenceType resolveGenericWildcardFor(WildcardedUnresolvedType aType) {
  508. BoundedReferenceType ret = null;
  509. // FIXME asc doesnt take account of additional interface bounds (e.g. ? super R & Serializable - can you do that?)
  510. if (aType.isExtends()) {
  511. ResolvedType resolvedUpperBound = resolve(aType.getUpperBound());
  512. if (resolvedUpperBound.isMissing()) {
  513. return getWildcard();
  514. }
  515. ret = new BoundedReferenceType((ReferenceType)resolvedUpperBound, true, this);
  516. } else if (aType.isSuper()) {
  517. ResolvedType resolvedLowerBound = resolve(aType.getLowerBound());
  518. if (resolvedLowerBound.isMissing()) {
  519. return getWildcard();
  520. }
  521. ret = new BoundedReferenceType((ReferenceType)resolvedLowerBound, false, this);
  522. } else {
  523. // must be ? on its own!
  524. ret = getWildcard();
  525. }
  526. return ret;
  527. }
  528. /**
  529. * Find the ReferenceTypeDelegate behind this reference type so that it can fulfill its contract.
  530. */
  531. protected abstract ReferenceTypeDelegate resolveDelegate(ReferenceType ty);
  532. /**
  533. * Special resolution for "core" types like OBJECT. These are resolved just like any other type, but if they are not found it is
  534. * more serious and we issue an error message immediately.
  535. */
  536. // OPTIMIZE streamline path for core types? They are just simple types,
  537. // could look straight in the typemap?
  538. public ResolvedType getCoreType(UnresolvedType tx) {
  539. ResolvedType coreTy = resolve(tx, true);
  540. if (coreTy.isMissing()) {
  541. MessageUtil.error(messageHandler, WeaverMessages.format(WeaverMessages.CANT_FIND_CORE_TYPE, tx.getName()));
  542. }
  543. return coreTy;
  544. }
  545. /**
  546. * Lookup a type by signature, if not found then build one and put it in the map.
  547. */
  548. public ReferenceType lookupOrCreateName(UnresolvedType ty) {
  549. String signature = ty.getSignature();
  550. ReferenceType ret = lookupBySignature(signature);
  551. if (ret == null) {
  552. ret = ReferenceType.fromTypeX(ty, this);
  553. typeMap.put(signature, ret);
  554. }
  555. return ret;
  556. }
  557. /**
  558. * Lookup a reference type in the world by its signature. Returns null if not found.
  559. */
  560. public ReferenceType lookupBySignature(String signature) {
  561. return (ReferenceType) typeMap.get(signature);
  562. }
  563. // ==========================================================================
  564. // ===
  565. // T Y P E R E S O L U T I O N -- E N D
  566. // ==========================================================================
  567. // ===
  568. /**
  569. * Member resolution is achieved by resolving the declaring type and then looking up the member in the resolved declaring type.
  570. */
  571. public ResolvedMember resolve(Member member) {
  572. ResolvedType declaring = member.getDeclaringType().resolve(this);
  573. if (declaring.isRawType()) {
  574. declaring = declaring.getGenericType();
  575. }
  576. ResolvedMember ret;
  577. if (member.getKind() == Member.FIELD) {
  578. ret = declaring.lookupField(member);
  579. } else {
  580. ret = declaring.lookupMethod(member);
  581. }
  582. if (ret != null) {
  583. return ret;
  584. }
  585. return declaring.lookupSyntheticMember(member);
  586. }
  587. private boolean allLintIgnored = false;
  588. public void setAllLintIgnored() {
  589. allLintIgnored = true;
  590. }
  591. public boolean areAllLintIgnored() {
  592. return allLintIgnored;
  593. }
  594. public abstract IWeavingSupport getWeavingSupport();
  595. /**
  596. * Create an advice shadow munger from the given advice attribute
  597. */
  598. // public abstract Advice createAdviceMunger(AjAttribute.AdviceAttribute
  599. // attribute, Pointcut pointcut, Member signature);
  600. /**
  601. * Create an advice shadow munger for the given advice kind
  602. */
  603. public final Advice createAdviceMunger(AdviceKind kind, Pointcut p, Member signature, int extraParameterFlags,
  604. IHasSourceLocation loc, ResolvedType declaringAspect) {
  605. AjAttribute.AdviceAttribute attribute = new AjAttribute.AdviceAttribute(kind, p, extraParameterFlags, loc.getStart(),
  606. loc.getEnd(), loc.getSourceContext());
  607. return getWeavingSupport().createAdviceMunger(attribute, p, signature, declaringAspect);
  608. }
  609. /**
  610. * Same signature as org.aspectj.util.PartialOrder.PartialComparable.compareTo
  611. */
  612. public int compareByPrecedence(ResolvedType aspect1, ResolvedType aspect2) {
  613. return precedenceCalculator.compareByPrecedence(aspect1, aspect2);
  614. }
  615. public Integer getPrecedenceIfAny(ResolvedType aspect1, ResolvedType aspect2) {
  616. return precedenceCalculator.getPrecedenceIfAny(aspect1, aspect2);
  617. }
  618. /**
  619. * compares by precedence with the additional rule that a super-aspect is sorted before its sub-aspects
  620. */
  621. public int compareByPrecedenceAndHierarchy(ResolvedType aspect1, ResolvedType aspect2) {
  622. return precedenceCalculator.compareByPrecedenceAndHierarchy(aspect1, aspect2);
  623. }
  624. // simple property getter and setters
  625. // ===========================================================
  626. /**
  627. * Nobody should hold onto a copy of this message handler, or setMessageHandler won't work right.
  628. */
  629. public IMessageHandler getMessageHandler() {
  630. return messageHandler;
  631. }
  632. public void setMessageHandler(IMessageHandler messageHandler) {
  633. if (this.isInPinpointMode()) {
  634. this.messageHandler = new PinpointingMessageHandler(messageHandler);
  635. } else {
  636. this.messageHandler = messageHandler;
  637. }
  638. }
  639. /**
  640. * convenenience method for creating and issuing messages via the message handler - if you supply two locations you will get two
  641. * messages.
  642. */
  643. public void showMessage(Kind kind, String message, ISourceLocation loc1, ISourceLocation loc2) {
  644. if (loc1 != null) {
  645. messageHandler.handleMessage(new Message(message, kind, null, loc1));
  646. if (loc2 != null) {
  647. messageHandler.handleMessage(new Message(message, kind, null, loc2));
  648. }
  649. } else {
  650. messageHandler.handleMessage(new Message(message, kind, null, loc2));
  651. }
  652. }
  653. public void setCrossReferenceHandler(ICrossReferenceHandler xrefHandler) {
  654. this.xrefHandler = xrefHandler;
  655. }
  656. /**
  657. * Get the cross-reference handler for the world, may be null.
  658. */
  659. public ICrossReferenceHandler getCrossReferenceHandler() {
  660. return xrefHandler;
  661. }
  662. public void setTypeVariableLookupScope(TypeVariableDeclaringElement scope) {
  663. typeVariableLookupScope = scope;
  664. }
  665. public TypeVariableDeclaringElement getTypeVariableLookupScope() {
  666. return typeVariableLookupScope;
  667. }
  668. public List<DeclareParents> getDeclareParents() {
  669. return crosscuttingMembersSet.getDeclareParents();
  670. }
  671. public List<DeclareAnnotation> getDeclareAnnotationOnTypes() {
  672. return crosscuttingMembersSet.getDeclareAnnotationOnTypes();
  673. }
  674. public List<DeclareAnnotation> getDeclareAnnotationOnFields() {
  675. return crosscuttingMembersSet.getDeclareAnnotationOnFields();
  676. }
  677. public List<DeclareAnnotation> getDeclareAnnotationOnMethods() {
  678. return crosscuttingMembersSet.getDeclareAnnotationOnMethods();
  679. }
  680. public List<DeclareTypeErrorOrWarning> getDeclareTypeEows() {
  681. return crosscuttingMembersSet.getDeclareTypeEows();
  682. }
  683. public List<DeclareSoft> getDeclareSoft() {
  684. return crosscuttingMembersSet.getDeclareSofts();
  685. }
  686. public CrosscuttingMembersSet getCrosscuttingMembersSet() {
  687. return crosscuttingMembersSet;
  688. }
  689. public IStructureModel getModel() {
  690. return model;
  691. }
  692. public void setModel(IStructureModel model) {
  693. this.model = model;
  694. }
  695. public Lint getLint() {
  696. return lint;
  697. }
  698. public void setLint(Lint lint) {
  699. this.lint = lint;
  700. }
  701. public boolean isXnoInline() {
  702. return XnoInline;
  703. }
  704. public void setXnoInline(boolean xnoInline) {
  705. XnoInline = xnoInline;
  706. }
  707. public boolean isXlazyTjp() {
  708. return XlazyTjp;
  709. }
  710. public void setXlazyTjp(boolean b) {
  711. XlazyTjp = b;
  712. }
  713. public boolean isHasMemberSupportEnabled() {
  714. return XhasMember;
  715. }
  716. public void setXHasMemberSupportEnabled(boolean b) {
  717. XhasMember = b;
  718. }
  719. public boolean isInPinpointMode() {
  720. return Xpinpoint;
  721. }
  722. public void setPinpointMode(boolean b) {
  723. Xpinpoint = b;
  724. }
  725. public boolean useFinal() {
  726. return useFinal;
  727. }
  728. public boolean isMinimalModel() {
  729. ensureAdvancedConfigurationProcessed();
  730. return minimalModel;
  731. }
  732. public boolean isTargettingRuntime1_6_10() {
  733. ensureAdvancedConfigurationProcessed();
  734. return targettingRuntime1_6_10;
  735. }
  736. public void setBehaveInJava5Way(boolean b) {
  737. behaveInJava5Way = b;
  738. }
  739. /**
  740. * Set the timing option (whether to collect timing info), this will also need INFO messages turned on for the message handler
  741. * being used. The reportPeriodically flag should be set to false under AJDT so numbers just come out at the end.
  742. */
  743. public void setTiming(boolean timersOn, boolean reportPeriodically) {
  744. timing = timersOn;
  745. timingPeriodically = reportPeriodically;
  746. }
  747. /**
  748. * Set the error and warning threashold which can be taken from CompilerOptions (see bug 129282)
  749. *
  750. * @param errorThreshold
  751. * @param warningThreshold
  752. */
  753. public void setErrorAndWarningThreshold(boolean errorThreshold, boolean warningThreshold) {
  754. this.errorThreshold = errorThreshold;
  755. this.warningThreshold = warningThreshold;
  756. }
  757. /**
  758. * @return true if ignoring the UnusedDeclaredThrownException and false if this compiler option is set to error or warning
  759. */
  760. public boolean isIgnoringUnusedDeclaredThrownException() {
  761. // the 0x800000 is CompilerOptions.UnusedDeclaredThrownException
  762. // which is ASTNode.bit24
  763. return errorThreshold||warningThreshold;
  764. // if ((errorThreshold & 0x800000) != 0 || (warningThreshold & 0x800000) != 0) {
  765. // return false;
  766. // }
  767. // return true;
  768. }
  769. public void performExtraConfiguration(String config) {
  770. if (config == null) {
  771. return;
  772. }
  773. // Bunch of name value pairs to split
  774. extraConfiguration = new Properties();
  775. int pos = -1;
  776. while ((pos = config.indexOf(",")) != -1) {
  777. String nvpair = config.substring(0, pos);
  778. int pos2 = nvpair.indexOf("=");
  779. if (pos2 != -1) {
  780. String n = nvpair.substring(0, pos2);
  781. String v = nvpair.substring(pos2 + 1);
  782. extraConfiguration.setProperty(n, v);
  783. }
  784. config = config.substring(pos + 1);
  785. }
  786. if (config.length() > 0) {
  787. int pos2 = config.indexOf("=");
  788. if (pos2 != -1) {
  789. String n = config.substring(0, pos2);
  790. String v = config.substring(pos2 + 1);
  791. extraConfiguration.setProperty(n, v);
  792. }
  793. }
  794. ensureAdvancedConfigurationProcessed();
  795. }
  796. public boolean areInfoMessagesEnabled() {
  797. if (infoMessagesEnabled == 0) {
  798. infoMessagesEnabled = (messageHandler.isIgnoring(IMessage.INFO) ? 1 : 2);
  799. }
  800. return infoMessagesEnabled == 2;
  801. }
  802. /**
  803. * may return null
  804. */
  805. public Properties getExtraConfiguration() {
  806. return extraConfiguration;
  807. }
  808. public final static String xsetAVOID_FINAL = "avoidFinal"; // default true
  809. public final static String xsetWEAVE_JAVA_PACKAGES = "weaveJavaPackages"; // default
  810. // false
  811. // -
  812. // controls
  813. // LTW
  814. public final static String xsetWEAVE_JAVAX_PACKAGES = "weaveJavaxPackages"; // default
  815. // false
  816. // -
  817. // controls
  818. // LTW
  819. public final static String xsetCAPTURE_ALL_CONTEXT = "captureAllContext"; // default
  820. // false
  821. public final static String xsetRUN_MINIMAL_MEMORY = "runMinimalMemory"; // default
  822. // true
  823. public final static String xsetDEBUG_STRUCTURAL_CHANGES_CODE = "debugStructuralChangesCode"; // default
  824. // false
  825. public final static String xsetDEBUG_BRIDGING = "debugBridging"; // default
  826. // false
  827. public final static String xsetTRANSIENT_TJP_FIELDS = "makeTjpFieldsTransient"; // default false
  828. public final static String xsetBCEL_REPOSITORY_CACHING = "bcelRepositoryCaching";
  829. public final static String xsetPIPELINE_COMPILATION = "pipelineCompilation";
  830. public final static String xsetGENERATE_STACKMAPS = "generateStackMaps";
  831. public final static String xsetPIPELINE_COMPILATION_DEFAULT = "true";
  832. public final static String xsetCOMPLETE_BINARY_TYPES = "completeBinaryTypes";
  833. public final static String xsetCOMPLETE_BINARY_TYPES_DEFAULT = "false";
  834. public final static String xsetTYPE_DEMOTION = "typeDemotion";
  835. public final static String xsetTYPE_DEMOTION_DEBUG = "typeDemotionDebug";
  836. public final static String xsetTYPE_REFS = "useWeakTypeRefs";
  837. public final static String xsetBCEL_REPOSITORY_CACHING_DEFAULT = "true";
  838. public final static String xsetFAST_PACK_METHODS = "fastPackMethods"; // default true
  839. public final static String xsetOVERWEAVING = "overWeaving";
  840. public final static String xsetOPTIMIZED_MATCHING = "optimizedMatching";
  841. public final static String xsetTIMERS_PER_JOINPOINT = "timersPerJoinpoint";
  842. public final static String xsetTIMERS_PER_FASTMATCH_CALL = "timersPerFastMatchCall";
  843. public final static String xsetITD_VERSION = "itdVersion";
  844. public final static String xsetITD_VERSION_ORIGINAL = "1";
  845. public final static String xsetITD_VERSION_2NDGEN = "2";
  846. public final static String xsetITD_VERSION_DEFAULT = xsetITD_VERSION_2NDGEN;
  847. public final static String xsetMINIMAL_MODEL = "minimalModel";
  848. public final static String xsetTARGETING_RUNTIME_1610 = "targetRuntime1_6_10";
  849. // This option allows you to prevent AspectJ adding local variable tables - some tools (e.g. dex) may
  850. // not like what gets created because even though it is valid, the bytecode they are processing has
  851. // unexpected quirks that mean the table entries are violated in the code. See issue:
  852. // https://bugs.eclipse.org/bugs/show_bug.cgi?id=470658
  853. public final static String xsetGENERATE_NEW_LVTS="generateNewLocalVariableTables";
  854. public boolean isInJava5Mode() {
  855. return behaveInJava5Way;
  856. }
  857. public boolean isTimingEnabled() {
  858. return timing;
  859. }
  860. public void setTargetAspectjRuntimeLevel(String s) {
  861. targetAspectjRuntimeLevel = RuntimeVersion.getVersionFor(s);
  862. }
  863. public void setOptionalJoinpoints(String jps) {
  864. if (jps == null) {
  865. return;
  866. }
  867. if (jps.contains("arrayconstruction")) {
  868. optionalJoinpoint_ArrayConstruction = true;
  869. }
  870. if (jps.contains("synchronization")) {
  871. optionalJoinpoint_Synchronization = true;
  872. }
  873. }
  874. public boolean isJoinpointArrayConstructionEnabled() {
  875. return optionalJoinpoint_ArrayConstruction;
  876. }
  877. public boolean isJoinpointSynchronizationEnabled() {
  878. return optionalJoinpoint_Synchronization;
  879. }
  880. public RuntimeVersion getTargetAspectjRuntimeLevel() {
  881. return targetAspectjRuntimeLevel;
  882. }
  883. // OPTIMIZE are users falling foul of not supplying -1.5 and so targetting the old runtime?
  884. public boolean isTargettingAspectJRuntime12() {
  885. boolean b = false; // pr116679
  886. if (!isInJava5Mode()) {
  887. b = true;
  888. } else {
  889. b = (getTargetAspectjRuntimeLevel() == RuntimeVersion.V1_2);
  890. }
  891. return b;
  892. }
  893. /*
  894. * Map of types in the world, can have 'references' to expendable ones which can be garbage collected to recover memory. An
  895. * expendable type is a reference type that is not exposed to the weaver (ie just pulled in for type resolution purposes).
  896. * Generic types have their raw form added to the map, which has a pointer to the underlying generic.
  897. */
  898. public static class TypeMap {
  899. // Strategy for entries in the expendable map
  900. public final static int DONT_USE_REFS = 0; // Hang around forever
  901. public final static int USE_WEAK_REFS = 1; // Collected asap
  902. public final static int USE_SOFT_REFS = 2; // Collected when short on memory
  903. public List<String> addedSinceLastDemote;
  904. public List<String> writtenClasses;
  905. private static boolean debug = false;
  906. public static boolean useExpendableMap = true; // configurable for reliable testing
  907. private boolean demotionSystemActive;
  908. private boolean debugDemotion = false;
  909. public int policy = USE_WEAK_REFS;
  910. // Map of types that never get thrown away
  911. final Map<String, ResolvedType> tMap = new HashMap<String, ResolvedType>();
  912. // Map of types that may be ejected from the cache if we need space
  913. final Map<String, Reference<ResolvedType>> expendableMap = Collections
  914. .synchronizedMap(new WeakHashMap<String, Reference<ResolvedType>>());
  915. private final World w;
  916. // profiling tools...
  917. private boolean memoryProfiling = false;
  918. private int maxExpendableMapSize = -1;
  919. private int collectedTypes = 0;
  920. private final ReferenceQueue<ResolvedType> rq = new ReferenceQueue<ResolvedType>();
  921. TypeMap(World w) {
  922. // Demotion activated when switched on and loadtime weaving or in AJDT
  923. demotionSystemActive = w.isDemotionActive() && (w.isLoadtimeWeaving() || w.couldIncrementalCompileFollow());
  924. addedSinceLastDemote = new ArrayList<String>();
  925. writtenClasses = new ArrayList<String>();
  926. this.w = w;
  927. memoryProfiling = false;// !w.getMessageHandler().isIgnoring(Message.INFO);
  928. }
  929. // For testing
  930. public Map<String, Reference<ResolvedType>> getExpendableMap() {
  931. return expendableMap;
  932. }
  933. // For testing
  934. public Map<String, ResolvedType> getMainMap() {
  935. return tMap;
  936. }
  937. public int demote() {
  938. return demote(false);
  939. }
  940. /**
  941. * Go through any types added during the previous file weave. If any are suitable for demotion, then put them in the
  942. * expendable map where GC can claim them at some point later. Demotion means: the type is not an aspect, the type is not
  943. * java.lang.Object, the type is not primitive and the type is not affected by type mungers in any way. Further refinements
  944. * of these conditions may allow for more demotions.
  945. *
  946. * @return number of types demoted
  947. */
  948. public int demote(boolean atEndOfCompile) {
  949. if (!demotionSystemActive) {
  950. return 0;
  951. }
  952. if (debugDemotion) {
  953. System.out.println("Demotion running " + addedSinceLastDemote);
  954. }
  955. boolean isLtw = w.isLoadtimeWeaving();
  956. int demotionCounter = 0;
  957. if (isLtw) {
  958. // Loadtime weaving demotion strategy
  959. for (String key : addedSinceLastDemote) {
  960. ResolvedType type = tMap.get(key);
  961. if (type != null && !type.isAspect() && !type.equals(UnresolvedType.OBJECT) && !type.isPrimitiveType()) {
  962. List<ConcreteTypeMunger> typeMungers = type.getInterTypeMungers();
  963. if (typeMungers == null || typeMungers.size() == 0) {
  964. tMap.remove(key);
  965. insertInExpendableMap(key, type);
  966. demotionCounter++;
  967. }
  968. }
  969. }
  970. addedSinceLastDemote.clear();
  971. } else {
  972. // Compile time demotion strategy
  973. List<String> forRemoval = new ArrayList<String>();
  974. for (String key : addedSinceLastDemote) {
  975. ResolvedType type = tMap.get(key);
  976. if (type == null) {
  977. // TODO not 100% sure why it is not there, where did it go?
  978. forRemoval.add(key);
  979. continue;
  980. }
  981. if (!writtenClasses.contains(type.getName())) { // COSTLY
  982. continue;
  983. }
  984. if (type != null && !type.isAspect() && !type.equals(UnresolvedType.OBJECT) && !type.isPrimitiveType()) {
  985. List<ConcreteTypeMunger> typeMungers = type.getInterTypeMungers();
  986. if (typeMungers == null || typeMungers.size() == 0) {
  987. /*
  988. * if (type.isNested()) { try { ReferenceType rt = (ReferenceType) w.resolve(type.getOutermostType());
  989. * if (!rt.isMissing()) { ReferenceTypeDelegate delegate = ((ReferenceType) type).getDelegate(); boolean
  990. * isWeavable = delegate == null ? false : delegate.isExposedToWeaver(); boolean hasBeenWoven = delegate
  991. * == null ? false : delegate.hasBeenWoven(); if (isWeavable && !hasBeenWoven) { // skip demotion of
  992. * this inner type for now continue; } } } catch (ClassCastException cce) { cce.printStackTrace();
  993. * System.out.println("outer of " + key + " is not a reftype? " + type.getOutermostType()); // throw new
  994. * IllegalStateException(cce); } }
  995. */
  996. ReferenceTypeDelegate delegate = ((ReferenceType) type).getDelegate();
  997. boolean isWeavable = delegate == null ? false : delegate.isExposedToWeaver();
  998. boolean hasBeenWoven = delegate == null ? false : delegate.hasBeenWoven();
  999. if (!isWeavable || hasBeenWoven) {
  1000. if (debugDemotion) {
  1001. System.out.println("Demoting " + key);
  1002. }
  1003. forRemoval.add(key);
  1004. tMap.remove(key);
  1005. insertInExpendableMap(key, type);
  1006. demotionCounter++;
  1007. }
  1008. } else {
  1009. // no need to try this again, it will never be demoted
  1010. writtenClasses.remove(type.getName());
  1011. forRemoval.add(key);
  1012. }
  1013. } else {
  1014. writtenClasses.remove(type.getName());
  1015. // no need to try this again, it will never be demoted
  1016. forRemoval.add(key);
  1017. }
  1018. }
  1019. addedSinceLastDemote.removeAll(forRemoval);
  1020. }
  1021. if (debugDemotion) {
  1022. System.out.println("Demoted " + demotionCounter + " types. Types remaining in fixed set #" + tMap.keySet().size()
  1023. + ". addedSinceLastDemote size is " + addedSinceLastDemote.size());
  1024. System.out.println("writtenClasses.size() = " + writtenClasses.size() + ": " + writtenClasses);
  1025. }
  1026. if (atEndOfCompile) {
  1027. if (debugDemotion) {
  1028. System.out.println("Clearing writtenClasses");
  1029. }
  1030. writtenClasses.clear();
  1031. }
  1032. return demotionCounter;
  1033. }
  1034. private void insertInExpendableMap(String key, ResolvedType type) {
  1035. if (useExpendableMap) {
  1036. // Need to check both whether the entry is gone, or whether the entry has had
  1037. // the WR to the value cleared.
  1038. Reference<ResolvedType> existingReference = expendableMap.get(key);
  1039. if (existingReference == null || existingReference.get() == null) {
  1040. // If a previous key is in there, WeakHashMap.put will update the value on the
  1041. // entry but not the key. We can't allow this as the old key won't
  1042. // be directly referenced by the new type, meaning that the key and value
  1043. // might be GC'd independently.
  1044. expendableMap.remove(key);
  1045. if (policy == USE_SOFT_REFS) {
  1046. expendableMap.put(key, new SoftReference<ResolvedType>(type));
  1047. } else {
  1048. expendableMap.put(key, new WeakReference<ResolvedType>(type));
  1049. }
  1050. }
  1051. }
  1052. }
  1053. /**
  1054. * Add a new type into the map, the key is the type signature. Some types do *not* go in the map, these are ones involving
  1055. * *member* type variables. The reason is that when all you have is the signature which gives you a type variable name, you
  1056. * cannot guarantee you are using the type variable in the same way as someone previously working with a similarly named
  1057. * type variable. So, these do not go into the map: - TypeVariableReferenceType. - ParameterizedType where a member type
  1058. * variable is involved. - BoundedReferenceType when one of the bounds is a type variable.
  1059. *
  1060. * definition: "member type variables" - a tvar declared on a generic method/ctor as opposed to those you see declared on a
  1061. * generic type.
  1062. */
  1063. public ResolvedType put(String key, ResolvedType type) {
  1064. if (!type.isCacheable()) {
  1065. return type;
  1066. }
  1067. if (type.isParameterizedType() && type.isParameterizedWithTypeVariable()) {
  1068. if (debug) {
  1069. System.err
  1070. .println("Not putting a parameterized type that utilises member declared type variables into the typemap: key="
  1071. + key + " type=" + type);
  1072. }
  1073. return type;
  1074. }
  1075. if (type.isTypeVariableReference()) {
  1076. if (debug) {
  1077. System.err.println("Not putting a type variable reference type into the typemap: key=" + key + " type=" + type);
  1078. }
  1079. return type;
  1080. }
  1081. // this test should be improved - only avoid putting them in if one of the
  1082. // bounds is a member type variable
  1083. if (type instanceof BoundedReferenceType) {
  1084. if (debug) {
  1085. System.err.println("Not putting a bounded reference type into the typemap: key=" + key + " type=" + type);
  1086. }
  1087. return type;
  1088. }
  1089. if (type instanceof MissingResolvedTypeWithKnownSignature) {
  1090. if (debug) {
  1091. System.err.println("Not putting a missing type into the typemap: key=" + key + " type=" + type);
  1092. }
  1093. return type;
  1094. }
  1095. if ((type instanceof ReferenceType) && (((ReferenceType) type).getDelegate() == null) && w.isExpendable(type)) {
  1096. if (debug) {
  1097. System.err.println("Not putting expendable ref type with null delegate into typemap: key=" + key + " type="
  1098. + type);
  1099. }
  1100. return type;
  1101. }
  1102. // TODO should this be in as a permanent assertion?
  1103. if ((type instanceof ReferenceType) && type.getWorld().isInJava5Mode()
  1104. && (((ReferenceType) type).getDelegate() != null) && type.isGenericType()) {
  1105. throw new BCException("Attempt to add generic type to typemap " + type.toString() + " (should be raw)");
  1106. }
  1107. if (w.isExpendable(type)) {
  1108. if (useExpendableMap) {
  1109. // If a previous key is in there, WeakHashMap.put will update the value on the
  1110. // entry but not the key. We can't allow this as the old key won't be directly
  1111. // referenced by the new type, meaning that the key and value might
  1112. // be GC'd independently.
  1113. expendableMap.remove(key);
  1114. // Dont use reference queue for tracking if not profiling...
  1115. if (policy == USE_WEAK_REFS) {
  1116. if (memoryProfiling) {
  1117. expendableMap.put(key, new WeakReference<ResolvedType>(type, rq));
  1118. } else {
  1119. expendableMap.put(key, new WeakReference<ResolvedType>(type));
  1120. }
  1121. } else if (policy == USE_SOFT_REFS) {
  1122. if (memoryProfiling) {
  1123. expendableMap.put(key, new SoftReference<ResolvedType>(type, rq));
  1124. } else {
  1125. expendableMap.put(key, new SoftReference<ResolvedType>(type));
  1126. }
  1127. // } else {
  1128. // expendableMap.put(key, type);
  1129. }
  1130. }
  1131. if (memoryProfiling && expendableMap.size() > maxExpendableMapSize) {
  1132. maxExpendableMapSize = expendableMap.size();
  1133. }
  1134. return type;
  1135. } else {
  1136. if (demotionSystemActive) {
  1137. // System.out.println("Added since last demote " + key);
  1138. addedSinceLastDemote.add(key);
  1139. }
  1140. return tMap.put(key, type);
  1141. }
  1142. }
  1143. public void report() {
  1144. if (!memoryProfiling) {
  1145. return;
  1146. }
  1147. checkq();
  1148. w.getMessageHandler().handleMessage(
  1149. MessageUtil.info("MEMORY: world expendable type map reached maximum size of #" + maxExpendableMapSize
  1150. + " entries"));
  1151. w.getMessageHandler().handleMessage(
  1152. MessageUtil.info("MEMORY: types collected through garbage collection #" + collectedTypes + " entries"));
  1153. }
  1154. public void checkq() {
  1155. if (!memoryProfiling) {
  1156. return;
  1157. }
  1158. Reference<? extends ResolvedType> r = null;
  1159. while ((r=rq.poll()) != null) {
  1160. collectedTypes++;
  1161. }
  1162. }
  1163. /**
  1164. * Lookup a type by its signature, always look in the real map before the expendable map
  1165. */
  1166. public ResolvedType get(String key) {
  1167. checkq();
  1168. ResolvedType ret = tMap.get(key);
  1169. if (ret == null) {
  1170. if (policy == USE_WEAK_REFS) {
  1171. WeakReference<ResolvedType> ref = (WeakReference<ResolvedType>) expendableMap.get(key);
  1172. if (ref != null) {
  1173. ret = ref.get();
  1174. // if (ret==null) {
  1175. // expendableMap.remove(key);
  1176. // }
  1177. }
  1178. } else if (policy == USE_SOFT_REFS) {
  1179. SoftReference<ResolvedType> ref = (SoftReference<ResolvedType>) expendableMap.get(key);
  1180. if (ref != null) {
  1181. ret = ref.get();
  1182. // if (ret==null) {
  1183. // expendableMap.remove(key);
  1184. // }
  1185. }
  1186. // } else {
  1187. // return (ResolvedType) expendableMap.get(key);
  1188. }
  1189. }
  1190. return ret;
  1191. }
  1192. /** Remove a type from the map */
  1193. public ResolvedType remove(String key) {
  1194. ResolvedType ret = tMap.remove(key);
  1195. if (ret == null) {
  1196. if (policy == USE_WEAK_REFS) {
  1197. WeakReference<ResolvedType> wref = (WeakReference<ResolvedType>) expendableMap.remove(key);
  1198. if (wref != null) {
  1199. ret = wref.get();
  1200. }
  1201. } else if (policy == USE_SOFT_REFS) {
  1202. SoftReference<ResolvedType> wref = (SoftReference<ResolvedType>) expendableMap.remove(key);
  1203. if (wref != null) {
  1204. ret = wref.get();
  1205. }
  1206. // } else {
  1207. // ret = (ResolvedType) expendableMap.remove(key);
  1208. }
  1209. }
  1210. return ret;
  1211. }
  1212. public void classWriteEvent(String classname) {
  1213. // that is a name com.Foo and not a signature Lcom/Foo; boooooooooo!
  1214. if (demotionSystemActive) {
  1215. writtenClasses.add(classname);
  1216. }
  1217. if (debugDemotion) {
  1218. System.out.println("Class write event for " + classname);
  1219. }
  1220. }
  1221. public void demote(ResolvedType type) {
  1222. String key = type.getSignature();
  1223. if (debugDemotion) {
  1224. addedSinceLastDemote.remove(key);
  1225. }
  1226. tMap.remove(key);
  1227. insertInExpendableMap(key, type);
  1228. }
  1229. // public ResolvedType[] getAllTypes() {
  1230. // List/* ResolvedType */results = new ArrayList();
  1231. //
  1232. // collectTypes(expendableMap, results);
  1233. // collectTypes(tMap, results);
  1234. // return (ResolvedType[]) results.toArray(new
  1235. // ResolvedType[results.size()]);
  1236. // }
  1237. //
  1238. // private void collectTypes(Map map, List/* ResolvedType */results) {
  1239. // for (Iterator iterator = map.keySet().iterator();
  1240. // iterator.hasNext();) {
  1241. // String key = (String) iterator.next();
  1242. // ResolvedType type = get(key);
  1243. // if (type != null)
  1244. // results.add(type);
  1245. // else
  1246. // System.err.println("null!:" + key);
  1247. // }
  1248. // }
  1249. }
  1250. /**
  1251. * This class is used to compute and store precedence relationships between aspects.
  1252. */
  1253. private static class AspectPrecedenceCalculator {
  1254. private final World world;
  1255. private final Map<PrecedenceCacheKey, Integer> cachedResults;
  1256. public AspectPrecedenceCalculator(World forSomeWorld) {
  1257. world = forSomeWorld;
  1258. cachedResults = new HashMap<PrecedenceCacheKey, Integer>();
  1259. }
  1260. /**
  1261. * Ask every declare precedence in the world to order the two aspects. If more than one declare precedence gives an
  1262. * ordering, and the orderings conflict, then that's an error.
  1263. */
  1264. public int compareByPrecedence(ResolvedType firstAspect, ResolvedType secondAspect) {
  1265. PrecedenceCacheKey key = new PrecedenceCacheKey(firstAspect, secondAspect);
  1266. if (cachedResults.containsKey(key)) {
  1267. return (cachedResults.get(key)).intValue();
  1268. } else {
  1269. int order = 0;
  1270. DeclarePrecedence orderer = null; // Records the declare
  1271. // precedence statement that
  1272. // gives the first ordering
  1273. for (Declare declare : world.getCrosscuttingMembersSet().getDeclareDominates()) {
  1274. DeclarePrecedence d = (DeclarePrecedence) declare;
  1275. int thisOrder = d.compare(firstAspect, secondAspect);
  1276. if (thisOrder != 0) {
  1277. if (orderer == null) {
  1278. orderer = d;
  1279. }
  1280. if (order != 0 && order != thisOrder) {
  1281. ISourceLocation[] isls = new ISourceLocation[2];
  1282. isls[0] = orderer.getSourceLocation();
  1283. isls[1] = d.getSourceLocation();
  1284. Message m = new Message("conflicting declare precedence orderings for aspects: "
  1285. + firstAspect.getName() + " and " + secondAspect.getName(), null, true, isls);
  1286. world.getMessageHandler().handleMessage(m);
  1287. } else {
  1288. order = thisOrder;
  1289. }
  1290. }
  1291. }
  1292. cachedResults.put(key, new Integer(order));
  1293. return order;
  1294. }
  1295. }
  1296. public Integer getPrecedenceIfAny(ResolvedType aspect1, ResolvedType aspect2) {
  1297. return cachedResults.get(new PrecedenceCacheKey(aspect1, aspect2));
  1298. }
  1299. public int compareByPrecedenceAndHierarchy(ResolvedType firstAspect, ResolvedType secondAspect) {
  1300. if (firstAspect.equals(secondAspect)) {
  1301. return 0;
  1302. }
  1303. int ret = compareByPrecedence(firstAspect, secondAspect);
  1304. if (ret != 0) {
  1305. return ret;
  1306. }
  1307. if (firstAspect.isAssignableFrom(secondAspect)) {
  1308. return -1;
  1309. } else if (secondAspect.isAssignableFrom(firstAspect)) {
  1310. return +1;
  1311. }
  1312. return 0;
  1313. }
  1314. private static class PrecedenceCacheKey {
  1315. public ResolvedType aspect1;
  1316. public ResolvedType aspect2;
  1317. public PrecedenceCacheKey(ResolvedType a1, ResolvedType a2) {
  1318. aspect1 = a1;
  1319. aspect2 = a2;
  1320. }
  1321. @Override
  1322. public boolean equals(Object obj) {
  1323. if (!(obj instanceof PrecedenceCacheKey)) {
  1324. return false;
  1325. }
  1326. PrecedenceCacheKey other = (PrecedenceCacheKey) obj;
  1327. return (aspect1 == other.aspect1 && aspect2 == other.aspect2);
  1328. }
  1329. @Override
  1330. public int hashCode() {
  1331. return aspect1.hashCode() + aspect2.hashCode();
  1332. }
  1333. }
  1334. }
  1335. public void validateType(UnresolvedType type) {
  1336. }
  1337. // --- with java5 we can get into a recursive mess if we aren't careful when
  1338. // resolving types (*cough* java.lang.Enum) ---
  1339. public boolean isDemotionActive() {
  1340. return true;
  1341. }
  1342. // --- this first map is for java15 delegates which may try and recursively
  1343. // access the same type variables.
  1344. // --- I would rather stash this against a reference type - but we don't
  1345. // guarantee referencetypes are unique for
  1346. // so we can't :(
  1347. private final Map<Class<?>, TypeVariable[]> workInProgress1 = new HashMap<Class<?>, TypeVariable[]>();
  1348. public TypeVariable[] getTypeVariablesCurrentlyBeingProcessed(Class<?> baseClass) {
  1349. return workInProgress1.get(baseClass);
  1350. }
  1351. public void recordTypeVariablesCurrentlyBeingProcessed(Class<?> baseClass, TypeVariable[] typeVariables) {
  1352. workInProgress1.put(baseClass, typeVariables);
  1353. }
  1354. public void forgetTypeVariablesCurrentlyBeingProcessed(Class<?> baseClass) {
  1355. workInProgress1.remove(baseClass);
  1356. }
  1357. public void setAddSerialVerUID(boolean b) {
  1358. addSerialVerUID = b;
  1359. }
  1360. public boolean isAddSerialVerUID() {
  1361. return addSerialVerUID;
  1362. }
  1363. /** be careful calling this - pr152257 */
  1364. public void flush() {
  1365. typeMap.expendableMap.clear();
  1366. }
  1367. public void ensureAdvancedConfigurationProcessed() {
  1368. // Check *once* whether the user has switched asm support off
  1369. if (!checkedAdvancedConfiguration) {
  1370. Properties p = getExtraConfiguration();
  1371. if (p != null) {
  1372. String s = p.getProperty(xsetBCEL_REPOSITORY_CACHING, xsetBCEL_REPOSITORY_CACHING_DEFAULT);
  1373. bcelRepositoryCaching = s.equalsIgnoreCase("true");
  1374. if (!bcelRepositoryCaching) {
  1375. getMessageHandler().handleMessage(
  1376. MessageUtil
  1377. .info("[bcelRepositoryCaching=false] AspectJ will not use a bcel cache for class information"));
  1378. }
  1379. // ITD Versions
  1380. // 1 is the first version in use up to AspectJ 1.6.8
  1381. // 2 is from 1.6.9 onwards
  1382. s = p.getProperty(xsetITD_VERSION, xsetITD_VERSION_DEFAULT);
  1383. if (s.equals(xsetITD_VERSION_ORIGINAL)) {
  1384. itdVersion = 1;
  1385. }
  1386. s = p.getProperty(xsetAVOID_FINAL, "false");
  1387. if (s.equalsIgnoreCase("true")) {
  1388. useFinal = false; // if avoidFinal=true, then set useFinal to false
  1389. }
  1390. s = p.getProperty(xsetMINIMAL_MODEL, "true");
  1391. if (s.equalsIgnoreCase("false")) {
  1392. minimalModel = false;
  1393. }
  1394. s = p.getProperty(xsetTARGETING_RUNTIME_1610, "false");
  1395. if (s.equalsIgnoreCase("true")) {
  1396. targettingRuntime1_6_10 = true;
  1397. }
  1398. s = p.getProperty(xsetFAST_PACK_METHODS, "true");
  1399. fastMethodPacking = s.equalsIgnoreCase("true");
  1400. s = p.getProperty(xsetPIPELINE_COMPILATION, xsetPIPELINE_COMPILATION_DEFAULT);
  1401. shouldPipelineCompilation = s.equalsIgnoreCase("true");
  1402. s = p.getProperty(xsetGENERATE_STACKMAPS, "false");
  1403. shouldGenerateStackMaps = s.equalsIgnoreCase("true");
  1404. s = p.getProperty(xsetCOMPLETE_BINARY_TYPES, xsetCOMPLETE_BINARY_TYPES_DEFAULT);
  1405. completeBinaryTypes = s.equalsIgnoreCase("true");
  1406. if (completeBinaryTypes) {
  1407. getMessageHandler().handleMessage(
  1408. MessageUtil.info("[completeBinaryTypes=true] Completion of binary types activated"));
  1409. }
  1410. s = p.getProperty(xsetTYPE_DEMOTION); // default is: ON
  1411. if (s != null) {
  1412. boolean b = typeMap.demotionSystemActive;
  1413. if (b && s.equalsIgnoreCase("false")) {
  1414. System.out.println("typeDemotion=false: type demotion switched OFF");
  1415. typeMap.demotionSystemActive = false;
  1416. } else if (!b && s.equalsIgnoreCase("true")) {
  1417. System.out.println("typeDemotion=true: type demotion switched ON");
  1418. typeMap.demotionSystemActive = true;
  1419. }
  1420. }
  1421. s = p.getProperty(xsetOVERWEAVING, "false");
  1422. if (s.equalsIgnoreCase("true")) {
  1423. overWeaving = true;
  1424. }
  1425. s = p.getProperty(xsetTYPE_DEMOTION_DEBUG, "false");
  1426. if (s.equalsIgnoreCase("true")) {
  1427. typeMap.debugDemotion = true;
  1428. }
  1429. s = p.getProperty(xsetTYPE_REFS, "true");
  1430. if (s.equalsIgnoreCase("false")) {
  1431. typeMap.policy = TypeMap.USE_SOFT_REFS;
  1432. }
  1433. runMinimalMemorySet = p.getProperty(xsetRUN_MINIMAL_MEMORY) != null;
  1434. s = p.getProperty(xsetRUN_MINIMAL_MEMORY, "false");
  1435. runMinimalMemory = s.equalsIgnoreCase("true");
  1436. // if (runMinimalMemory)
  1437. // getMessageHandler().handleMessage(MessageUtil.info(
  1438. // "[runMinimalMemory=true] Optimizing bcel processing (and cost of performance) to use less memory"
  1439. // ));
  1440. s = p.getProperty(xsetDEBUG_STRUCTURAL_CHANGES_CODE, "false");
  1441. forDEBUG_structuralChangesCode = s.equalsIgnoreCase("true");
  1442. s = p.getProperty(xsetTRANSIENT_TJP_FIELDS,"false");
  1443. transientTjpFields = s.equalsIgnoreCase("true");
  1444. s = p.getProperty(xsetDEBUG_BRIDGING, "false");
  1445. forDEBUG_bridgingCode = s.equalsIgnoreCase("true");
  1446. s = p.getProperty(xsetGENERATE_NEW_LVTS,"true");
  1447. generateNewLvts = s.equalsIgnoreCase("true");
  1448. if (!generateNewLvts) {
  1449. getMessageHandler().handleMessage(MessageUtil.info("[generateNewLvts=false] for methods without an incoming local variable table, do not generate one"));
  1450. }
  1451. s = p.getProperty(xsetOPTIMIZED_MATCHING, "true");
  1452. optimizedMatching = s.equalsIgnoreCase("true");
  1453. if (!optimizedMatching) {
  1454. getMessageHandler().handleMessage(MessageUtil.info("[optimizedMatching=false] optimized matching turned off"));
  1455. }
  1456. s = p.getProperty(xsetTIMERS_PER_JOINPOINT, "25000");
  1457. try {
  1458. timersPerJoinpoint = Integer.parseInt(s);
  1459. } catch (Exception e) {
  1460. getMessageHandler().handleMessage(MessageUtil.error("unable to process timersPerJoinpoint value of " + s));
  1461. timersPerJoinpoint = 25000;
  1462. }
  1463. s = p.getProperty(xsetTIMERS_PER_FASTMATCH_CALL, "250");
  1464. try {
  1465. timersPerType = Integer.parseInt(s);
  1466. } catch (Exception e) {
  1467. getMessageHandler().handleMessage(MessageUtil.error("unable to process timersPerType value of " + s));
  1468. timersPerType = 250;
  1469. }
  1470. }
  1471. try {
  1472. if (systemPropertyOverWeaving) {
  1473. overWeaving = true;
  1474. }
  1475. String value = null;
  1476. value = System.getProperty("aspectj.typeDemotion", "false");
  1477. if (value.equalsIgnoreCase("true")) {
  1478. System.out.println("ASPECTJ: aspectj.typeDemotion=true: type demotion switched ON");
  1479. typeMap.demotionSystemActive = true;
  1480. }
  1481. value = System.getProperty("aspectj.minimalModel", "false");
  1482. if (value.equalsIgnoreCase("true")) {
  1483. System.out.println("ASPECTJ: aspectj.minimalModel=true: minimal model switched ON");
  1484. minimalModel = true;
  1485. }
  1486. } catch (Throwable t) {
  1487. System.err.println("ASPECTJ: Unable to read system properties");
  1488. t.printStackTrace();
  1489. }
  1490. checkedAdvancedConfiguration = true;
  1491. }
  1492. }
  1493. public boolean isRunMinimalMemory() {
  1494. ensureAdvancedConfigurationProcessed();
  1495. return runMinimalMemory;
  1496. }
  1497. public boolean isTransientTjpFields() {
  1498. ensureAdvancedConfigurationProcessed();
  1499. return transientTjpFields;
  1500. }
  1501. public boolean isRunMinimalMemorySet() {
  1502. ensureAdvancedConfigurationProcessed();
  1503. return runMinimalMemorySet;
  1504. }
  1505. public boolean shouldFastPackMethods() {
  1506. ensureAdvancedConfigurationProcessed();
  1507. return fastMethodPacking;
  1508. }
  1509. public boolean shouldPipelineCompilation() {
  1510. ensureAdvancedConfigurationProcessed();
  1511. return shouldPipelineCompilation;
  1512. }
  1513. public boolean shouldGenerateStackMaps() {
  1514. ensureAdvancedConfigurationProcessed();
  1515. return shouldGenerateStackMaps;
  1516. }
  1517. public void setIncrementalCompileCouldFollow(boolean b) {
  1518. incrementalCompileCouldFollow = b;
  1519. }
  1520. public boolean couldIncrementalCompileFollow() {
  1521. return incrementalCompileCouldFollow;
  1522. }
  1523. public void setSynchronizationPointcutsInUse() {
  1524. if (trace.isTraceEnabled()) {
  1525. trace.enter("setSynchronizationPointcutsInUse", this);
  1526. }
  1527. synchronizationPointcutsInUse = true;
  1528. if (trace.isTraceEnabled()) {
  1529. trace.exit("setSynchronizationPointcutsInUse");
  1530. }
  1531. }
  1532. public boolean areSynchronizationPointcutsInUse() {
  1533. return synchronizationPointcutsInUse;
  1534. }
  1535. /**
  1536. * Register a new pointcut designator handler with the world - this can be used by any pointcut parsers attached to the world.
  1537. *
  1538. * @param designatorHandler handler for the new pointcut
  1539. */
  1540. public void registerPointcutHandler(PointcutDesignatorHandler designatorHandler) {
  1541. if (pointcutDesignators == null) {
  1542. pointcutDesignators = new HashSet<PointcutDesignatorHandler>();
  1543. }
  1544. pointcutDesignators.add(designatorHandler);
  1545. }
  1546. public Set<PointcutDesignatorHandler> getRegisteredPointcutHandlers() {
  1547. if (pointcutDesignators == null) {
  1548. return Collections.emptySet();
  1549. }
  1550. return pointcutDesignators;
  1551. }
  1552. public void reportMatch(ShadowMunger munger, Shadow shadow) {
  1553. }
  1554. public boolean isOverWeaving() {
  1555. return overWeaving;
  1556. }
  1557. public void reportCheckerMatch(Checker checker, Shadow shadow) {
  1558. }
  1559. /**
  1560. * @return true if this world has the activation and scope of application of the aspects controlled via aop.xml files
  1561. */
  1562. public boolean isXmlConfigured() {
  1563. return false;
  1564. }
  1565. public boolean isAspectIncluded(ResolvedType aspectType) {
  1566. return true;
  1567. }
  1568. /**
  1569. * Determine if the named aspect requires a particular type around in order to be useful. The type is named in the aop.xml file
  1570. * against the aspect.
  1571. *
  1572. * @return true if there is a type missing that this aspect really needed around
  1573. */
  1574. public boolean hasUnsatisfiedDependency(ResolvedType aspectType) {
  1575. return false;
  1576. }
  1577. public TypePattern getAspectScope(ResolvedType declaringType) {
  1578. return null;
  1579. }
  1580. public Map<String, ResolvedType> getFixed() {
  1581. return typeMap.tMap;
  1582. }
  1583. public Map<String, Reference<ResolvedType>> getExpendable() {
  1584. return typeMap.expendableMap;
  1585. }
  1586. /**
  1587. * Ask the type map to demote any types it can - we don't want them anchored forever.
  1588. */
  1589. public void demote() {
  1590. typeMap.demote();
  1591. }
  1592. // protected boolean isExpendable(ResolvedType type) {
  1593. // if (type.equals(UnresolvedType.OBJECT))
  1594. // return false;
  1595. // if (type == null)
  1596. // return false;
  1597. // boolean isExposed = type.isExposedToWeaver();
  1598. // boolean nullDele = (type instanceof ReferenceType) ? ((ReferenceType) type).getDelegate() != null : true;
  1599. // if (isExposed || !isExposed && nullDele)
  1600. // return false;
  1601. // return !type.isPrimitiveType();
  1602. // }
  1603. /**
  1604. * Reference types we don't intend to weave may be ejected from the cache if we need the space.
  1605. */
  1606. protected boolean isExpendable(ResolvedType type) {
  1607. return !type.equals(UnresolvedType.OBJECT) && !type.isExposedToWeaver() && !type.isPrimitiveType()
  1608. && !type.isPrimitiveArray();
  1609. }
  1610. // map from aspect > excluded types
  1611. // memory issue here?
  1612. private Map<ResolvedType, Set<ResolvedType>> exclusionMap = new HashMap<ResolvedType, Set<ResolvedType>>();
  1613. public Map<ResolvedType, Set<ResolvedType>> getExclusionMap() {
  1614. return exclusionMap;
  1615. }
  1616. private TimeCollector timeCollector = null;
  1617. /**
  1618. * Record the time spent matching a pointcut - this will accumulate over the lifetime of this world/weaver and be reported every
  1619. * 25000 join points.
  1620. */
  1621. public void record(Pointcut pointcut, long timetaken) {
  1622. if (timeCollector == null) {
  1623. ensureAdvancedConfigurationProcessed();
  1624. timeCollector = new TimeCollector(this);
  1625. }
  1626. timeCollector.record(pointcut, timetaken);
  1627. }
  1628. /**
  1629. * Record the time spent fastmatching a pointcut - this will accumulate over the lifetime of this world/weaver and be reported
  1630. * every 250 types.
  1631. */
  1632. public void recordFastMatch(Pointcut pointcut, long timetaken) {
  1633. if (timeCollector == null) {
  1634. ensureAdvancedConfigurationProcessed();
  1635. timeCollector = new TimeCollector(this);
  1636. }
  1637. timeCollector.recordFastMatch(pointcut, timetaken);
  1638. }
  1639. public void reportTimers() {
  1640. if (timeCollector != null && !timingPeriodically) {
  1641. timeCollector.report();
  1642. timeCollector = new TimeCollector(this);
  1643. }
  1644. }
  1645. private static class TimeCollector {
  1646. private World world;
  1647. long joinpointCount;
  1648. long typeCount;
  1649. long perJoinpointCount;
  1650. long perTypes;
  1651. Map<String, Long> joinpointsPerPointcut = new HashMap<String, Long>();
  1652. Map<String, Long> timePerPointcut = new HashMap<String, Long>();
  1653. Map<String, Long> fastMatchTimesPerPointcut = new HashMap<String, Long>();
  1654. Map<String, Long> fastMatchTypesPerPointcut = new HashMap<String, Long>();
  1655. TimeCollector(World world) {
  1656. this.perJoinpointCount = world.timersPerJoinpoint;
  1657. this.perTypes = world.timersPerType;
  1658. this.world = world;
  1659. this.joinpointCount = 0;
  1660. this.typeCount = 0;
  1661. this.joinpointsPerPointcut = new HashMap<String, Long>();
  1662. this.timePerPointcut = new HashMap<String, Long>();
  1663. }
  1664. public void report() {
  1665. long totalTime = 0L;
  1666. for (String p : joinpointsPerPointcut.keySet()) {
  1667. totalTime += timePerPointcut.get(p);
  1668. }
  1669. world.getMessageHandler().handleMessage(
  1670. MessageUtil.info("Pointcut matching cost (total=" + (totalTime / 1000000) + "ms for " + joinpointCount
  1671. + " joinpoint match calls):"));
  1672. for (String p : joinpointsPerPointcut.keySet()) {
  1673. StringBuffer sb = new StringBuffer();
  1674. sb.append("Time:" + (timePerPointcut.get(p) / 1000000) + "ms (jps:#" + joinpointsPerPointcut.get(p)
  1675. + ") matching against " + p);
  1676. world.getMessageHandler().handleMessage(MessageUtil.info(sb.toString()));
  1677. }
  1678. world.getMessageHandler().handleMessage(MessageUtil.info("---"));
  1679. totalTime = 0L;
  1680. for (String p : fastMatchTimesPerPointcut.keySet()) {
  1681. totalTime += fastMatchTimesPerPointcut.get(p);
  1682. }
  1683. world.getMessageHandler().handleMessage(
  1684. MessageUtil.info("Pointcut fast matching cost (total=" + (totalTime / 1000000) + "ms for " + typeCount
  1685. + " fast match calls):"));
  1686. for (String p : fastMatchTimesPerPointcut.keySet()) {
  1687. StringBuffer sb = new StringBuffer();
  1688. sb.append("Time:" + (fastMatchTimesPerPointcut.get(p) / 1000000) + "ms (types:#" + fastMatchTypesPerPointcut.get(p)
  1689. + ") fast matching against " + p);
  1690. world.getMessageHandler().handleMessage(MessageUtil.info(sb.toString()));
  1691. }
  1692. world.getMessageHandler().handleMessage(MessageUtil.info("---"));
  1693. }
  1694. void record(Pointcut pointcut, long timetakenInNs) {
  1695. joinpointCount++;
  1696. String pointcutText = pointcut.toString();
  1697. Long jpcounter = joinpointsPerPointcut.get(pointcutText);
  1698. if (jpcounter == null) {
  1699. jpcounter = 1L;
  1700. } else {
  1701. jpcounter++;
  1702. }
  1703. joinpointsPerPointcut.put(pointcutText, jpcounter);
  1704. Long time = timePerPointcut.get(pointcutText);
  1705. if (time == null) {
  1706. time = timetakenInNs;
  1707. } else {
  1708. time += timetakenInNs;
  1709. }
  1710. timePerPointcut.put(pointcutText, time);
  1711. if (world.timingPeriodically) {
  1712. if ((joinpointCount % perJoinpointCount) == 0) {
  1713. long totalTime = 0L;
  1714. for (String p : joinpointsPerPointcut.keySet()) {
  1715. totalTime += timePerPointcut.get(p);
  1716. }
  1717. world.getMessageHandler().handleMessage(
  1718. MessageUtil.info("Pointcut matching cost (total=" + (totalTime / 1000000) + "ms for " + joinpointCount
  1719. + " joinpoint match calls):"));
  1720. for (String p : joinpointsPerPointcut.keySet()) {
  1721. StringBuffer sb = new StringBuffer();
  1722. sb.append("Time:" + (timePerPointcut.get(p) / 1000000) + "ms (jps:#" + joinpointsPerPointcut.get(p)
  1723. + ") matching against " + p);
  1724. world.getMessageHandler().handleMessage(MessageUtil.info(sb.toString()));
  1725. }
  1726. world.getMessageHandler().handleMessage(MessageUtil.info("---"));
  1727. }
  1728. }
  1729. }
  1730. void recordFastMatch(Pointcut pointcut, long timetakenInNs) {
  1731. typeCount++;
  1732. String pointcutText = pointcut.toString();
  1733. Long typecounter = fastMatchTypesPerPointcut.get(pointcutText);
  1734. if (typecounter == null) {
  1735. typecounter = 1L;
  1736. } else {
  1737. typecounter++;
  1738. }
  1739. fastMatchTypesPerPointcut.put(pointcutText, typecounter);
  1740. Long time = fastMatchTimesPerPointcut.get(pointcutText);
  1741. if (time == null) {
  1742. time = timetakenInNs;
  1743. } else {
  1744. time += timetakenInNs;
  1745. }
  1746. fastMatchTimesPerPointcut.put(pointcutText, time);
  1747. if (world.timingPeriodically) {
  1748. if ((typeCount % perTypes) == 0) {
  1749. long totalTime = 0L;
  1750. for (String p : fastMatchTimesPerPointcut.keySet()) {
  1751. totalTime += fastMatchTimesPerPointcut.get(p);
  1752. }
  1753. world.getMessageHandler().handleMessage(
  1754. MessageUtil.info("Pointcut fast matching cost (total=" + (totalTime / 1000000) + "ms for " + typeCount
  1755. + " fast match calls):"));
  1756. for (String p : fastMatchTimesPerPointcut.keySet()) {
  1757. StringBuffer sb = new StringBuffer();
  1758. sb.append("Time:" + (fastMatchTimesPerPointcut.get(p) / 1000000) + "ms (types:#"
  1759. + fastMatchTypesPerPointcut.get(p) + ") fast matching against " + p);
  1760. world.getMessageHandler().handleMessage(MessageUtil.info(sb.toString()));
  1761. }
  1762. world.getMessageHandler().handleMessage(MessageUtil.info("---"));
  1763. }
  1764. }
  1765. }
  1766. }
  1767. public TypeMap getTypeMap() {
  1768. return typeMap;
  1769. }
  1770. public static void reset() {
  1771. // ResolvedType.resetPrimitives();
  1772. }
  1773. /**
  1774. * Returns the version of ITD that this world wants to create. The default is the new style (2) but in some cases where there
  1775. * might be a clash, the old style can be used. It is set through the option -Xset:itdVersion=1
  1776. *
  1777. * @return the ITD version this world wants to create - 1=oldstyle 2=new, transparent style
  1778. */
  1779. public int getItdVersion() {
  1780. return itdVersion;
  1781. }
  1782. // if not loadtime weaving then we are compile time weaving or post-compile time weaving
  1783. public abstract boolean isLoadtimeWeaving();
  1784. public void classWriteEvent(char[][] compoundName) {
  1785. // override if interested in write events
  1786. }
  1787. }