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

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