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

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