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

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