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.

BcelTypeMunger.java 88KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129
  1. /* *******************************************************************
  2. * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
  3. * All rights reserved.
  4. * This program and the accompanying materials are made available
  5. * under the terms of the Eclipse Public License v 2.0
  6. * which accompanies this distribution and is available at
  7. * https://www.eclipse.org/org/documents/epl-2.0/EPL-2.0.txt
  8. *
  9. * Contributors:
  10. * PARC initial implementation
  11. * Alexandre Vasseur @AspectJ ITDs
  12. * ******************************************************************/
  13. package org.aspectj.weaver.bcel;
  14. import java.lang.reflect.Modifier;
  15. import java.util.ArrayList;
  16. import java.util.HashMap;
  17. import java.util.HashSet;
  18. import java.util.Iterator;
  19. import java.util.List;
  20. import java.util.Map;
  21. import java.util.Set;
  22. import org.aspectj.apache.bcel.Constants;
  23. import org.aspectj.apache.bcel.classfile.ClassFormatException;
  24. import org.aspectj.apache.bcel.classfile.ConstantPool;
  25. import org.aspectj.apache.bcel.classfile.Signature;
  26. import org.aspectj.apache.bcel.classfile.annotation.AnnotationGen;
  27. import org.aspectj.apache.bcel.generic.FieldGen;
  28. import org.aspectj.apache.bcel.generic.InstructionBranch;
  29. import org.aspectj.apache.bcel.generic.InstructionConstants;
  30. import org.aspectj.apache.bcel.generic.InstructionFactory;
  31. import org.aspectj.apache.bcel.generic.InstructionHandle;
  32. import org.aspectj.apache.bcel.generic.InstructionList;
  33. import org.aspectj.apache.bcel.generic.InvokeInstruction;
  34. import org.aspectj.apache.bcel.generic.Type;
  35. import org.aspectj.asm.AsmManager;
  36. import org.aspectj.asm.IProgramElement;
  37. import org.aspectj.bridge.IMessage;
  38. import org.aspectj.bridge.ISourceLocation;
  39. import org.aspectj.bridge.Message;
  40. import org.aspectj.bridge.MessageUtil;
  41. import org.aspectj.bridge.WeaveMessage;
  42. import org.aspectj.bridge.context.CompilationAndWeavingContext;
  43. import org.aspectj.bridge.context.ContextToken;
  44. import org.aspectj.weaver.AjcMemberMaker;
  45. import org.aspectj.weaver.AnnotationAJ;
  46. import org.aspectj.weaver.AnnotationOnTypeMunger;
  47. import org.aspectj.weaver.BCException;
  48. import org.aspectj.weaver.ConcreteTypeMunger;
  49. import org.aspectj.weaver.Member;
  50. import org.aspectj.weaver.MemberUtils;
  51. import org.aspectj.weaver.MethodDelegateTypeMunger;
  52. import org.aspectj.weaver.NameMangler;
  53. import org.aspectj.weaver.NewConstructorTypeMunger;
  54. import org.aspectj.weaver.NewFieldTypeMunger;
  55. import org.aspectj.weaver.NewMemberClassTypeMunger;
  56. import org.aspectj.weaver.NewMethodTypeMunger;
  57. import org.aspectj.weaver.NewParentTypeMunger;
  58. import org.aspectj.weaver.PerObjectInterfaceTypeMunger;
  59. import org.aspectj.weaver.PrivilegedAccessMunger;
  60. import org.aspectj.weaver.ResolvedMember;
  61. import org.aspectj.weaver.ResolvedMemberImpl;
  62. import org.aspectj.weaver.ResolvedType;
  63. import org.aspectj.weaver.ResolvedTypeMunger;
  64. import org.aspectj.weaver.Shadow;
  65. import org.aspectj.weaver.TypeVariableReference;
  66. import org.aspectj.weaver.UnresolvedType;
  67. import org.aspectj.weaver.WeaverMessages;
  68. import org.aspectj.weaver.WeaverStateInfo;
  69. import org.aspectj.weaver.World;
  70. import org.aspectj.weaver.model.AsmRelationshipProvider;
  71. import org.aspectj.weaver.patterns.DeclareAnnotation;
  72. import org.aspectj.weaver.patterns.Pointcut;
  73. public class BcelTypeMunger extends ConcreteTypeMunger {
  74. public BcelTypeMunger(ResolvedTypeMunger munger, ResolvedType aspectType) {
  75. super(munger, aspectType);
  76. }
  77. @Override
  78. public String toString() {
  79. return "(BcelTypeMunger " + getMunger() + ")";
  80. }
  81. @Override
  82. public boolean shouldOverwrite() {
  83. return false;
  84. }
  85. public boolean munge(BcelClassWeaver weaver) {
  86. ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.MUNGING_WITH, this);
  87. boolean changed = false;
  88. boolean worthReporting = true;
  89. if (weaver.getWorld().isOverWeaving()) {
  90. WeaverStateInfo typeWeaverState = weaver.getLazyClassGen().getType().getWeaverState();
  91. if (typeWeaverState != null && typeWeaverState.isAspectAlreadyApplied(getAspectType())) {
  92. return false;
  93. }
  94. }
  95. if (munger.getKind() == ResolvedTypeMunger.Field) {
  96. changed = mungeNewField(weaver, (NewFieldTypeMunger) munger);
  97. } else if (munger.getKind() == ResolvedTypeMunger.Method) {
  98. changed = mungeNewMethod(weaver, (NewMethodTypeMunger) munger);
  99. } else if (munger.getKind() == ResolvedTypeMunger.InnerClass) {
  100. changed = mungeNewMemberType(weaver, (NewMemberClassTypeMunger) munger);
  101. } else if (munger.getKind() == ResolvedTypeMunger.MethodDelegate2) {
  102. changed = mungeMethodDelegate(weaver, (MethodDelegateTypeMunger) munger);
  103. } else if (munger.getKind() == ResolvedTypeMunger.FieldHost) {
  104. changed = mungeFieldHost(weaver, (MethodDelegateTypeMunger.FieldHostTypeMunger) munger);
  105. } else if (munger.getKind() == ResolvedTypeMunger.PerObjectInterface) {
  106. changed = mungePerObjectInterface(weaver, (PerObjectInterfaceTypeMunger) munger);
  107. worthReporting = false;
  108. } else if (munger.getKind() == ResolvedTypeMunger.PerTypeWithinInterface) {
  109. // PTWIMPL Transform the target type (add the aspect instance field)
  110. changed = mungePerTypeWithinTransformer(weaver);
  111. worthReporting = false;
  112. } else if (munger.getKind() == ResolvedTypeMunger.PrivilegedAccess) {
  113. changed = mungePrivilegedAccess(weaver, (PrivilegedAccessMunger) munger);
  114. worthReporting = false;
  115. } else if (munger.getKind() == ResolvedTypeMunger.Constructor) {
  116. changed = mungeNewConstructor(weaver, (NewConstructorTypeMunger) munger);
  117. } else if (munger.getKind() == ResolvedTypeMunger.Parent) {
  118. changed = mungeNewParent(weaver, (NewParentTypeMunger) munger);
  119. } else if (munger.getKind() == ResolvedTypeMunger.AnnotationOnType) {
  120. changed = mungeNewAnnotationOnType(weaver, (AnnotationOnTypeMunger) munger);
  121. worthReporting = false;
  122. } else {
  123. throw new RuntimeException("unimplemented");
  124. }
  125. if (changed && munger.changesPublicSignature()) {
  126. WeaverStateInfo info = weaver.getLazyClassGen().getOrCreateWeaverStateInfo(weaver.getReweavableMode());
  127. info.addConcreteMunger(this);
  128. }
  129. if (changed && worthReporting) {
  130. ResolvedType declaringAspect = null;
  131. AsmManager model = ((BcelWorld) getWorld()).getModelAsAsmManager();
  132. if (model != null) {
  133. if (munger instanceof NewParentTypeMunger) {
  134. NewParentTypeMunger nptMunger = (NewParentTypeMunger) munger;
  135. declaringAspect = nptMunger.getDeclaringType();
  136. if (declaringAspect.isParameterizedOrGenericType()) {
  137. declaringAspect = declaringAspect.getRawType();
  138. }
  139. ResolvedType thisAspect = getAspectType();
  140. AsmRelationshipProvider.addRelationship(model, weaver.getLazyClassGen().getType(), munger, thisAspect);
  141. // Add a relationship on the actual declaring aspect too
  142. if (!thisAspect.equals(declaringAspect)) {
  143. // Might be the case the declaring aspect is generic and thisAspect is parameterizing it. In that case
  144. // record the actual parameterizations
  145. ResolvedType target = weaver.getLazyClassGen().getType();
  146. ResolvedType newParent = nptMunger.getNewParent();
  147. IProgramElement thisAspectNode = model.getHierarchy().findElementForType(thisAspect.getPackageName(),
  148. thisAspect.getClassName());
  149. Map<String, List<String>> declareParentsMap = thisAspectNode.getDeclareParentsMap();
  150. if (declareParentsMap == null) {
  151. declareParentsMap = new HashMap<>();
  152. thisAspectNode.setDeclareParentsMap(declareParentsMap);
  153. }
  154. String tname = target.getName();
  155. String pname = newParent.getName();
  156. List<String> newparents = declareParentsMap.computeIfAbsent(tname, k -> new ArrayList<>());
  157. newparents.add(pname);
  158. AsmRelationshipProvider.addRelationship(model, weaver.getLazyClassGen().getType(), munger, declaringAspect);
  159. }
  160. } else {
  161. declaringAspect = getAspectType();
  162. AsmRelationshipProvider.addRelationship(model, weaver.getLazyClassGen().getType(), munger, declaringAspect);
  163. }
  164. }
  165. }
  166. // TAG: WeavingMessage
  167. if (changed && worthReporting && munger != null && !weaver.getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) {
  168. String tName = weaver.getLazyClassGen().getType().getSourceLocation().getSourceFile().getName();
  169. if (tName.contains("no debug info available")) {
  170. tName = "no debug info available";
  171. } else {
  172. tName = getShortname(weaver.getLazyClassGen().getType().getSourceLocation().getSourceFile().getPath());
  173. }
  174. String fName = getShortname(getAspectType().getSourceLocation().getSourceFile().getPath());
  175. if (munger.getKind().equals(ResolvedTypeMunger.Parent)) {
  176. // This message could come out of AjLookupEnvironment.addParent
  177. // if doing parents munging at compile time only...
  178. NewParentTypeMunger parentTM = (NewParentTypeMunger) munger;
  179. if (parentTM.isMixin()) {
  180. weaver.getWorld()
  181. .getMessageHandler()
  182. .handleMessage(
  183. WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_MIXIN, new String[] {
  184. parentTM.getNewParent().getName(), fName, weaver.getLazyClassGen().getType().getName(),
  185. tName }, weaver.getLazyClassGen().getClassName(), getAspectType().getName()));
  186. } else {
  187. if (parentTM.getNewParent().isInterface()) {
  188. weaver.getWorld()
  189. .getMessageHandler()
  190. .handleMessage(
  191. WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSIMPLEMENTS,
  192. new String[] { weaver.getLazyClassGen().getType().getName(), tName,
  193. parentTM.getNewParent().getName(), fName }, weaver.getLazyClassGen()
  194. .getClassName(), getAspectType().getName()));
  195. } else {
  196. weaver.getWorld()
  197. .getMessageHandler()
  198. .handleMessage(
  199. WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSEXTENDS,
  200. new String[] { weaver.getLazyClassGen().getType().getName(), tName,
  201. parentTM.getNewParent().getName(), fName }));
  202. // TAG: WeavingMessage DECLARE PARENTS: EXTENDS
  203. // reportDeclareParentsMessage(WeaveMessage.
  204. // WEAVEMESSAGE_DECLAREPARENTSEXTENDS,sourceType,parent);
  205. }
  206. }
  207. } else if (munger.getKind().equals(ResolvedTypeMunger.FieldHost)) {
  208. // hidden
  209. } else {
  210. ResolvedMember declaredSig = munger.getSignature();
  211. String fromString = fName + ":'" + declaredSig + "'";
  212. // if (declaredSig==null) declaredSig= munger.getSignature();
  213. String kindString = munger.getKind().toString().toLowerCase();
  214. if (kindString.equals("innerclass")) {
  215. kindString = "member class";
  216. fromString = fName;
  217. }
  218. weaver.getWorld()
  219. .getMessageHandler()
  220. .handleMessage(
  221. WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ITD, new String[] {
  222. weaver.getLazyClassGen().getType().getName(), tName, kindString, getAspectType().getName(),
  223. fromString }, weaver.getLazyClassGen().getClassName(), getAspectType().getName()));
  224. }
  225. }
  226. CompilationAndWeavingContext.leavingPhase(tok);
  227. return changed;
  228. }
  229. private String getShortname(String path) {
  230. int takefrom = path.lastIndexOf('/');
  231. if (takefrom == -1) {
  232. takefrom = path.lastIndexOf('\\');
  233. }
  234. return path.substring(takefrom + 1);
  235. }
  236. private boolean mungeNewAnnotationOnType(BcelClassWeaver weaver, AnnotationOnTypeMunger munger) {
  237. // FIXME asc this has already been done up front, need to do it here too?
  238. try {
  239. BcelAnnotation anno = (BcelAnnotation) munger.getNewAnnotation();
  240. weaver.getLazyClassGen().addAnnotation(anno.getBcelAnnotation());
  241. } catch (ClassCastException cce) {
  242. throw new IllegalStateException("DiagnosticsFor318237: The typemunger "+munger+" contains an annotation of type "+
  243. munger.getNewAnnotation().getClass().getName()+" when it should be a BcelAnnotation",cce);
  244. }
  245. return true;
  246. }
  247. /**
  248. * For a long time, AspectJ did not allow binary weaving of declare parents. This restriction is now lifted but could do with
  249. * more testing!
  250. */
  251. private boolean mungeNewParent(BcelClassWeaver weaver, NewParentTypeMunger typeTransformer) {
  252. LazyClassGen newParentTarget = weaver.getLazyClassGen();
  253. ResolvedType newParent = typeTransformer.getNewParent();
  254. boolean performChange = true;
  255. performChange = enforceDecpRule1_abstractMethodsImplemented(weaver, typeTransformer.getSourceLocation(), newParentTarget,
  256. newParent);
  257. performChange = enforceDecpRule2_cantExtendFinalClass(weaver, typeTransformer.getSourceLocation(), newParentTarget,
  258. newParent) && performChange;
  259. List<ResolvedMember> methods = newParent.getMethodsWithoutIterator(false, true, false);
  260. for (ResolvedMember method : methods) {
  261. if (!method.getName().equals("<init>")) {
  262. LazyMethodGen subMethod = findMatchingMethod(newParentTarget, method);
  263. // FIXME asc is this safe for all bridge methods?
  264. if (subMethod != null && !subMethod.isBridgeMethod()) {
  265. if (!(subMethod.isSynthetic() && method.isSynthetic())) {
  266. if (!(subMethod.isStatic() && subMethod.getName().startsWith("access$"))) {
  267. // ignore generated accessors
  268. performChange = enforceDecpRule3_visibilityChanges(weaver, newParent, method, subMethod)
  269. && performChange;
  270. performChange = enforceDecpRule4_compatibleReturnTypes(weaver, method, subMethod) && performChange;
  271. performChange = enforceDecpRule5_cantChangeFromStaticToNonstatic(weaver,
  272. typeTransformer.getSourceLocation(), method, subMethod)
  273. && performChange;
  274. }
  275. }
  276. }
  277. }
  278. }
  279. if (!performChange) {
  280. // A rule was violated and an error message already reported
  281. return false;
  282. }
  283. if (newParent.isClass()) {
  284. // Changing the supertype
  285. if (!attemptToModifySuperCalls(weaver, newParentTarget, newParent)) {
  286. return false;
  287. }
  288. newParentTarget.setSuperClass(newParent);
  289. } else {
  290. // Add a new interface
  291. newParentTarget.addInterface(newParent, getSourceLocation());
  292. }
  293. return true;
  294. }
  295. /**
  296. * Rule 1: For the declare parents to be allowed, the target type must override and implement inherited abstract methods (if the
  297. * type is not declared abstract)
  298. */
  299. private boolean enforceDecpRule1_abstractMethodsImplemented(BcelClassWeaver weaver, ISourceLocation mungerLoc,
  300. LazyClassGen newParentTarget, ResolvedType newParent) {
  301. // Ignore abstract classes or interfaces
  302. if (newParentTarget.isAbstract() || newParentTarget.isInterface()) {
  303. return true;
  304. }
  305. boolean ruleCheckingSucceeded = true;
  306. List<ResolvedMember> newParentMethods = newParent.getMethodsWithoutIterator(false, true, false);
  307. for (ResolvedMember newParentMethod : newParentMethods) {
  308. String newParentMethodName = newParentMethod.getName();
  309. // Ignore abstract ajc$interField prefixed methods
  310. if (newParentMethod.isAbstract() && !newParentMethodName.startsWith("ajc$interField")) {
  311. ResolvedMember discoveredImpl = null;
  312. List<ResolvedMember> targetMethods = newParentTarget.getType().getMethodsWithoutIterator(false, true, false);
  313. for (ResolvedMember targetMethod : targetMethods) {
  314. if (!targetMethod.isAbstract() && targetMethod.getName().equals(newParentMethodName)) {
  315. String newParentMethodSig = newParentMethod.getParameterSignature(); // ([TT;)
  316. String targetMethodSignature = targetMethod.getParameterSignature(); // ([Ljava/lang/Object;)
  317. // could be a match
  318. if (targetMethodSignature.equals(newParentMethodSig)) {
  319. discoveredImpl = targetMethod;
  320. } else {
  321. // Does the erasure match? In which case a bridge method will be created later to
  322. // satisfy the abstract method
  323. if (targetMethod.hasBackingGenericMember()
  324. && targetMethod.getBackingGenericMember().getParameterSignature().equals(newParentMethodSig)) {
  325. discoveredImpl = targetMethod;
  326. } else if (newParentMethod.hasBackingGenericMember()) {
  327. if (newParentMethod.getBackingGenericMember().getParameterSignature().equals(targetMethodSignature)) { // newParentMethod.getBackingGenericMember().getParameterSignature gives: (Pjava/util/List<TI;>;) targetMethodSignature= (Ljava/util/List;)
  328. discoveredImpl = targetMethod;
  329. } else if (targetMethod instanceof BcelMethod) {
  330. // BcelMethod does not have backing generic member set (need to investigate why). For now, special case here:
  331. UnresolvedType[] targetMethodGenericParameterTypes = targetMethod.getGenericParameterTypes();
  332. if (targetMethodGenericParameterTypes !=null) {
  333. StringBuilder b = new StringBuilder("(");
  334. for (UnresolvedType p: targetMethodGenericParameterTypes) {
  335. b.append(p.getSignature());
  336. }
  337. b.append(')');
  338. if (b.toString().equals(newParentMethodSig)) {
  339. discoveredImpl = targetMethod;
  340. }
  341. }
  342. }
  343. }
  344. }
  345. if (discoveredImpl != null) {
  346. break;
  347. }
  348. }
  349. }
  350. if (discoveredImpl == null) {
  351. // didnt find a valid implementation, lets check the
  352. // ITDs on this type to see if they satisfy it
  353. boolean satisfiedByITD = false;
  354. for (ConcreteTypeMunger m : newParentTarget.getType().getInterTypeMungersIncludingSupers()) {
  355. if (m.getMunger() != null && m.getMunger().getKind() == ResolvedTypeMunger.Method) {
  356. ResolvedMember sig = m.getSignature();
  357. if (!Modifier.isAbstract(sig.getModifiers())) {
  358. // If the ITD shares a type variable with some target type, we need to tailor it
  359. // for that type
  360. if (m.isTargetTypeParameterized()) {
  361. ResolvedType genericOnType = getWorld().resolve(sig.getDeclaringType()).getGenericType();
  362. ResolvedType actualOccurrence = newParent.discoverActualOccurrenceOfTypeInHierarchy(genericOnType);
  363. if (actualOccurrence == null) {
  364. // Handle the case where the ITD is onto the type targeted by the declare parents (PR478003)
  365. actualOccurrence = newParentTarget.getType().discoverActualOccurrenceOfTypeInHierarchy(genericOnType);
  366. }
  367. m = m.parameterizedFor(actualOccurrence);
  368. // possible sig change when type parameters filled in
  369. sig = m.getSignature();
  370. }
  371. if (ResolvedType.matches(
  372. AjcMemberMaker.interMethod(sig, m.getAspectType(),
  373. sig.getDeclaringType().resolve(weaver.getWorld()).isInterface()), newParentMethod)) {
  374. satisfiedByITD = true;
  375. }
  376. }
  377. } else if (m.getMunger() != null && m.getMunger().getKind() == ResolvedTypeMunger.MethodDelegate2) {
  378. // AV - that should be enough, no need to check more
  379. satisfiedByITD = true;
  380. }
  381. }
  382. if (!satisfiedByITD) {
  383. error(weaver,
  384. "The type " + newParentTarget.getName() + " must implement the inherited abstract method "
  385. + newParentMethod.getDeclaringType() + "." + newParentMethodName
  386. + newParentMethod.getParameterSignature(), newParentTarget.getType().getSourceLocation(),
  387. new ISourceLocation[] { newParentMethod.getSourceLocation(), mungerLoc });
  388. ruleCheckingSucceeded = false;
  389. }
  390. }
  391. }
  392. }
  393. return ruleCheckingSucceeded;
  394. }
  395. /**
  396. * Rule 2. Can't extend final types
  397. */
  398. private boolean enforceDecpRule2_cantExtendFinalClass(BcelClassWeaver weaver, ISourceLocation transformerLoc,
  399. LazyClassGen targetType, ResolvedType newParent) {
  400. if (newParent.isFinal()) {
  401. error(weaver, "Cannot make type " + targetType.getName() + " extend final class " + newParent.getName(), targetType
  402. .getType().getSourceLocation(), new ISourceLocation[] { transformerLoc });
  403. return false;
  404. }
  405. return true;
  406. }
  407. /**
  408. * Rule 3. Can't narrow visibility of methods when overriding
  409. */
  410. private boolean enforceDecpRule3_visibilityChanges(BcelClassWeaver weaver, ResolvedType newParent, ResolvedMember superMethod,
  411. LazyMethodGen subMethod) {
  412. boolean cont = true;
  413. if (Modifier.isPublic(superMethod.getModifiers())) {
  414. if (subMethod.isProtected() || subMethod.isDefault() || subMethod.isPrivate()) {
  415. weaver.getWorld()
  416. .getMessageHandler()
  417. .handleMessage(
  418. MessageUtil.error("Cannot reduce the visibility of the inherited method '" + superMethod
  419. + "' from " + newParent.getName(), superMethod.getSourceLocation()));
  420. cont = false;
  421. }
  422. } else if (Modifier.isProtected(superMethod.getModifiers())) {
  423. if (subMethod.isDefault() || subMethod.isPrivate()) {
  424. weaver.getWorld()
  425. .getMessageHandler()
  426. .handleMessage(
  427. MessageUtil.error("Cannot reduce the visibility of the inherited method '" + superMethod
  428. + "' from " + newParent.getName(), superMethod.getSourceLocation()));
  429. cont = false;
  430. }
  431. } else if (superMethod.isDefault()) {
  432. if (subMethod.isPrivate()) {
  433. weaver.getWorld()
  434. .getMessageHandler()
  435. .handleMessage(
  436. MessageUtil.error("Cannot reduce the visibility of the inherited method '" + superMethod
  437. + "' from " + newParent.getName(), superMethod.getSourceLocation()));
  438. cont = false;
  439. }
  440. }
  441. return cont;
  442. }
  443. /**
  444. * Rule 4. Can't have incompatible return types
  445. */
  446. private boolean enforceDecpRule4_compatibleReturnTypes(BcelClassWeaver weaver, ResolvedMember superMethod,
  447. LazyMethodGen subMethod) {
  448. boolean cont = true;
  449. String superReturnTypeSig = superMethod.getGenericReturnType().getSignature(); // eg. Pjava/util/Collection<LFoo;>
  450. String subReturnTypeSig = subMethod.getGenericReturnTypeSignature();
  451. superReturnTypeSig = superReturnTypeSig.replace('.', '/');
  452. subReturnTypeSig = subReturnTypeSig.replace('.', '/');
  453. if (!superReturnTypeSig.equals(subReturnTypeSig)) {
  454. // Check for covariance
  455. ResolvedType subType = weaver.getWorld().resolve(subMethod.getReturnType());
  456. ResolvedType superType = weaver.getWorld().resolve(superMethod.getReturnType());
  457. if (!superType.isAssignableFrom(subType)) {
  458. weaver.getWorld()
  459. .getMessageHandler()
  460. .handleMessage(
  461. MessageUtil.error("The return type is incompatible with " + superMethod.getDeclaringType() + "."
  462. + superMethod.getName() + superMethod.getParameterSignature(),
  463. subMethod.getSourceLocation()));
  464. // this just might be a better error message...
  465. // "The return type '"+subReturnTypeSig+
  466. // "' is incompatible with the overridden method "
  467. // +superMethod.getDeclaringType()+"."+
  468. // superMethod.getName()+superMethod.getParameterSignature()+
  469. // " which returns '"+superReturnTypeSig+"'",
  470. cont = false;
  471. }
  472. }
  473. return cont;
  474. }
  475. /**
  476. * Rule5. Method overrides can't change the staticality (word?) - you can't override and make an instance method static or
  477. * override and make a static method an instance method.
  478. */
  479. private boolean enforceDecpRule5_cantChangeFromStaticToNonstatic(BcelClassWeaver weaver, ISourceLocation mungerLoc,
  480. ResolvedMember superMethod, LazyMethodGen subMethod) {
  481. boolean superMethodStatic = Modifier.isStatic(superMethod.getModifiers());
  482. if (superMethodStatic && !subMethod.isStatic()) {
  483. error(weaver, "This instance method " + subMethod.getName() + subMethod.getParameterSignature()
  484. + " cannot override the static method from " + superMethod.getDeclaringType().getName(),
  485. subMethod.getSourceLocation(), new ISourceLocation[] { mungerLoc });
  486. return false;
  487. } else if (!superMethodStatic && subMethod.isStatic()) {
  488. error(weaver, "The static method " + subMethod.getName() + subMethod.getParameterSignature()
  489. + " cannot hide the instance method from " + superMethod.getDeclaringType().getName(),
  490. subMethod.getSourceLocation(), new ISourceLocation[] { mungerLoc });
  491. return false;
  492. }
  493. return true;
  494. }
  495. public void error(BcelClassWeaver weaver, String text, ISourceLocation primaryLoc, ISourceLocation[] extraLocs) {
  496. IMessage msg = new Message(text, primaryLoc, true, extraLocs);
  497. weaver.getWorld().getMessageHandler().handleMessage(msg);
  498. }
  499. /**
  500. * Search the specified type for a particular method - do not use the return value in the comparison as it is not considered for
  501. * overriding.
  502. */
  503. private LazyMethodGen findMatchingMethod(LazyClassGen type, ResolvedMember searchMethod) {
  504. String searchName = searchMethod.getName();
  505. String searchSig = searchMethod.getParameterSignature();
  506. for (LazyMethodGen method : type.getMethodGens()) {
  507. if (method.getName().equals(searchName) && method.getParameterSignature().equals(searchSig)) {
  508. return method;
  509. }
  510. }
  511. return null;
  512. }
  513. /**
  514. * The main part of implementing declare parents extends. Modify super ctor calls to target the new type.
  515. */
  516. public boolean attemptToModifySuperCalls(BcelClassWeaver weaver, LazyClassGen newParentTarget, ResolvedType newParent) {
  517. ResolvedType currentParentType = newParentTarget.getSuperClass();
  518. if (currentParentType.getGenericType() != null) {
  519. currentParentType = currentParentType.getGenericType();
  520. }
  521. String currentParent = currentParentType.getName();
  522. if (newParent.getGenericType() != null) {
  523. newParent = newParent.getGenericType(); // target new super calls at
  524. }
  525. // the generic type if its raw or parameterized
  526. List<LazyMethodGen> mgs = newParentTarget.getMethodGens();
  527. // Look for ctors to modify
  528. for (LazyMethodGen aMethod : mgs) {
  529. if (LazyMethodGen.isConstructor(aMethod)) {
  530. InstructionList insList = aMethod.getBody();
  531. InstructionHandle handle = insList.getStart();
  532. while (handle != null) {
  533. if (handle.getInstruction().opcode == Constants.INVOKESPECIAL) {
  534. ConstantPool cpg = newParentTarget.getConstantPool();
  535. InvokeInstruction invokeSpecial = (InvokeInstruction) handle.getInstruction();
  536. if (invokeSpecial.getClassName(cpg).equals(currentParent)
  537. && invokeSpecial.getMethodName(cpg).equals("<init>")) {
  538. // System.err.println("Transforming super call '<init>" + invokeSpecial.getSignature(cpg) + "'");
  539. // 1. Check there is a ctor in the new parent with
  540. // the same signature
  541. ResolvedMember newCtor = getConstructorWithSignature(newParent, invokeSpecial.getSignature(cpg));
  542. if (newCtor == null) {
  543. // 2. Check ITDCs to see if the necessary ctor is provided that way
  544. boolean satisfiedByITDC = false;
  545. for (Iterator<ConcreteTypeMunger> ii = newParentTarget.getType()
  546. .getInterTypeMungersIncludingSupers().iterator(); ii.hasNext() && !satisfiedByITDC;) {
  547. ConcreteTypeMunger m = ii.next();
  548. if (m.getMunger() instanceof NewConstructorTypeMunger) {
  549. if (m.getSignature().getSignature().equals(invokeSpecial.getSignature(cpg))) {
  550. satisfiedByITDC = true;
  551. }
  552. }
  553. }
  554. if (!satisfiedByITDC) {
  555. String csig = createReadableCtorSig(newParent, cpg, invokeSpecial);
  556. weaver.getWorld()
  557. .getMessageHandler()
  558. .handleMessage(
  559. MessageUtil.error(
  560. "Unable to modify hierarchy for " + newParentTarget.getClassName()
  561. + " - the constructor " + csig + " is missing",
  562. this.getSourceLocation()));
  563. return false;
  564. }
  565. }
  566. int idx = cpg.addMethodref(newParent.getName(), invokeSpecial.getMethodName(cpg),
  567. invokeSpecial.getSignature(cpg));
  568. invokeSpecial.setIndex(idx);
  569. }
  570. }
  571. handle = handle.getNext();
  572. }
  573. }
  574. }
  575. return true;
  576. }
  577. /**
  578. * Creates a nice signature for the ctor, something like "(int,Integer,String)"
  579. */
  580. private String createReadableCtorSig(ResolvedType newParent, ConstantPool cpg, InvokeInstruction invokeSpecial) {
  581. StringBuilder sb = new StringBuilder();
  582. Type[] ctorArgs = invokeSpecial.getArgumentTypes(cpg);
  583. sb.append(newParent.getClassName());
  584. sb.append("(");
  585. for (int i = 0; i < ctorArgs.length; i++) {
  586. String argtype = ctorArgs[i].toString();
  587. if (argtype.lastIndexOf(".") != -1) {
  588. sb.append(argtype.substring(argtype.lastIndexOf(".") + 1));
  589. } else {
  590. sb.append(argtype);
  591. }
  592. if (i + 1 < ctorArgs.length) {
  593. sb.append(",");
  594. }
  595. }
  596. sb.append(")");
  597. return sb.toString();
  598. }
  599. private ResolvedMember getConstructorWithSignature(ResolvedType type, String searchSig) {
  600. for (ResolvedMember method : type.getDeclaredJavaMethods()) {
  601. if (MemberUtils.isConstructor(method)) {
  602. if (method.getSignature().equals(searchSig)) {
  603. return method;
  604. }
  605. }
  606. }
  607. return null;
  608. }
  609. private boolean mungePrivilegedAccess(BcelClassWeaver weaver, PrivilegedAccessMunger munger) {
  610. LazyClassGen gen = weaver.getLazyClassGen();
  611. ResolvedMember member = munger.getMember();
  612. ResolvedType onType = weaver.getWorld().resolve(member.getDeclaringType(), munger.getSourceLocation());
  613. if (onType.isRawType()) {
  614. onType = onType.getGenericType();
  615. }
  616. // System.out.println("munging: " + gen + " with " + member);
  617. if (onType.equals(gen.getType())) {
  618. if (member.getKind() == Member.FIELD) {
  619. // System.out.println("matched: " + gen);
  620. addFieldGetter(gen, member,
  621. AjcMemberMaker.privilegedAccessMethodForFieldGet(aspectType, member, munger.shortSyntax));
  622. addFieldSetter(gen, member,
  623. AjcMemberMaker.privilegedAccessMethodForFieldSet(aspectType, member, munger.shortSyntax));
  624. return true;
  625. } else if (member.getKind() == Member.METHOD) {
  626. addMethodDispatch(gen, member, AjcMemberMaker.privilegedAccessMethodForMethod(aspectType, member));
  627. return true;
  628. } else if (member.getKind() == Member.CONSTRUCTOR) {
  629. for (LazyMethodGen m : gen.getMethodGens()) {
  630. if (m.getMemberView() != null && m.getMemberView().getKind() == Member.CONSTRUCTOR) {
  631. // m.getMemberView().equals(member)) {
  632. m.forcePublic();
  633. // return true;
  634. }
  635. }
  636. return true;
  637. // throw new BCException("no match for " + member + " in " +
  638. // gen);
  639. } else if (member.getKind() == Member.STATIC_INITIALIZATION) {
  640. gen.forcePublic();
  641. return true;
  642. } else {
  643. throw new RuntimeException("unimplemented");
  644. }
  645. }
  646. return false;
  647. }
  648. private void addFieldGetter(LazyClassGen gen, ResolvedMember field, ResolvedMember accessMethod) {
  649. LazyMethodGen mg = makeMethodGen(gen, accessMethod);
  650. InstructionList il = new InstructionList();
  651. InstructionFactory fact = gen.getFactory();
  652. if (Modifier.isStatic(field.getModifiers())) {
  653. il.append(fact.createFieldAccess(gen.getClassName(), field.getName(), BcelWorld.makeBcelType(field.getType()),
  654. Constants.GETSTATIC));
  655. } else {
  656. il.append(InstructionConstants.ALOAD_0);
  657. il.append(fact.createFieldAccess(gen.getClassName(), field.getName(), BcelWorld.makeBcelType(field.getType()),
  658. Constants.GETFIELD));
  659. }
  660. il.append(InstructionFactory.createReturn(BcelWorld.makeBcelType(field.getType())));
  661. mg.getBody().insert(il);
  662. gen.addMethodGen(mg, getSignature().getSourceLocation());
  663. }
  664. private void addFieldSetter(LazyClassGen gen, ResolvedMember field, ResolvedMember accessMethod) {
  665. LazyMethodGen mg = makeMethodGen(gen, accessMethod);
  666. InstructionList il = new InstructionList();
  667. InstructionFactory fact = gen.getFactory();
  668. Type fieldType = BcelWorld.makeBcelType(field.getType());
  669. if (Modifier.isStatic(field.getModifiers())) {
  670. il.append(InstructionFactory.createLoad(fieldType, 0));
  671. il.append(fact.createFieldAccess(gen.getClassName(), field.getName(), fieldType, Constants.PUTSTATIC));
  672. } else {
  673. il.append(InstructionConstants.ALOAD_0);
  674. il.append(InstructionFactory.createLoad(fieldType, 1));
  675. il.append(fact.createFieldAccess(gen.getClassName(), field.getName(), fieldType, Constants.PUTFIELD));
  676. }
  677. il.append(InstructionFactory.createReturn(Type.VOID));
  678. mg.getBody().insert(il);
  679. gen.addMethodGen(mg, getSignature().getSourceLocation());
  680. }
  681. private void addMethodDispatch(LazyClassGen gen, ResolvedMember method, ResolvedMember accessMethod) {
  682. LazyMethodGen mg = makeMethodGen(gen, accessMethod);
  683. InstructionList il = new InstructionList();
  684. InstructionFactory fact = gen.getFactory();
  685. Type[] paramTypes = BcelWorld.makeBcelTypes(method.getParameterTypes());
  686. int pos = 0;
  687. if (!Modifier.isStatic(method.getModifiers())) {
  688. il.append(InstructionConstants.ALOAD_0);
  689. pos++;
  690. }
  691. for (Type paramType : paramTypes) {
  692. il.append(InstructionFactory.createLoad(paramType, pos));
  693. pos += paramType.getSize();
  694. }
  695. il.append(Utility.createInvoke(fact, (BcelWorld) aspectType.getWorld(), method));
  696. il.append(InstructionFactory.createReturn(BcelWorld.makeBcelType(method.getReturnType())));
  697. mg.getBody().insert(il);
  698. gen.addMethodGen(mg);
  699. }
  700. protected LazyMethodGen makeMethodGen(LazyClassGen gen, ResolvedMember member) {
  701. try {
  702. Type returnType = BcelWorld.makeBcelType(member.getReturnType());
  703. Type[] parameterTypes = BcelWorld.makeBcelTypes(member.getParameterTypes());
  704. LazyMethodGen ret = new LazyMethodGen(member.getModifiers(), returnType,
  705. member.getName(), parameterTypes, UnresolvedType.getNames(member
  706. .getExceptions()), gen);
  707. // 43972 : Static crosscutting makes interfaces unusable for javac
  708. // ret.makeSynthetic();
  709. return ret;
  710. } catch (ClassFormatException cfe) {
  711. throw new RuntimeException("Problem with makeMethodGen for method "+member.getName()+" in type "+gen.getName()+" ret="+member.getReturnType(),cfe);
  712. }
  713. }
  714. protected FieldGen makeFieldGen(LazyClassGen gen, ResolvedMember member) {
  715. return new FieldGen(member.getModifiers(), BcelWorld.makeBcelType(member.getReturnType()), member.getName(),
  716. gen.getConstantPool());
  717. }
  718. private boolean mungePerObjectInterface(BcelClassWeaver weaver, PerObjectInterfaceTypeMunger munger) {
  719. // System.err.println("Munging perobject ["+munger+"] onto "+weaver.
  720. // getLazyClassGen().getClassName());
  721. LazyClassGen gen = weaver.getLazyClassGen();
  722. if (couldMatch(gen.getBcelObjectType(), munger.getTestPointcut())) {
  723. FieldGen fg = makeFieldGen(gen, AjcMemberMaker.perObjectField(gen.getType(), aspectType));
  724. gen.addField(fg, getSourceLocation());
  725. Type fieldType = BcelWorld.makeBcelType(aspectType);
  726. LazyMethodGen mg = new LazyMethodGen(Modifier.PUBLIC, fieldType, NameMangler.perObjectInterfaceGet(aspectType),
  727. Type.NO_ARGS, new String[0], gen);
  728. InstructionList il = new InstructionList();
  729. InstructionFactory fact = gen.getFactory();
  730. il.append(InstructionConstants.ALOAD_0);
  731. il.append(fact.createFieldAccess(gen.getClassName(), fg.getName(), fieldType, Constants.GETFIELD));
  732. il.append(InstructionFactory.createReturn(fieldType));
  733. mg.getBody().insert(il);
  734. gen.addMethodGen(mg);
  735. LazyMethodGen mg1 = new LazyMethodGen(Modifier.PUBLIC, Type.VOID, NameMangler.perObjectInterfaceSet(aspectType),
  736. new Type[] { fieldType, }, new String[0], gen);
  737. InstructionList il1 = new InstructionList();
  738. il1.append(InstructionConstants.ALOAD_0);
  739. il1.append(InstructionFactory.createLoad(fieldType, 1));
  740. il1.append(fact.createFieldAccess(gen.getClassName(), fg.getName(), fieldType, Constants.PUTFIELD));
  741. il1.append(InstructionFactory.createReturn(Type.VOID));
  742. mg1.getBody().insert(il1);
  743. gen.addMethodGen(mg1);
  744. gen.addInterface(munger.getInterfaceType().resolve(weaver.getWorld()), getSourceLocation());
  745. return true;
  746. } else {
  747. return false;
  748. }
  749. }
  750. // PTWIMPL Add field to hold aspect instance and an accessor
  751. private boolean mungePerTypeWithinTransformer(BcelClassWeaver weaver) {
  752. LazyClassGen gen = weaver.getLazyClassGen();
  753. // if (couldMatch(gen.getBcelObjectType(), munger.getTestPointcut())) {
  754. // Add (to the target type) the field that will hold the aspect instance
  755. // e.g ajc$com_blah_SecurityAspect$ptwAspectInstance
  756. FieldGen fg = makeFieldGen(gen, AjcMemberMaker.perTypeWithinField(gen.getType(), aspectType));
  757. gen.addField(fg, getSourceLocation());
  758. if (!gen.getType().canBeSeenBy(aspectType) && aspectType.isPrivilegedAspect()) {
  759. gen.forcePublic();
  760. }
  761. // Add an accessor for this new field, the
  762. // ajc$<aspectname>$localAspectOf() method
  763. // e.g.
  764. // "public com_blah_SecurityAspect ajc$com_blah_SecurityAspect$localAspectOf()"
  765. Type fieldType = BcelWorld.makeBcelType(aspectType);
  766. LazyMethodGen mg = new LazyMethodGen(Modifier.PUBLIC | Modifier.STATIC, fieldType,
  767. NameMangler.perTypeWithinLocalAspectOf(aspectType), Type.NO_ARGS, new String[0], gen);
  768. InstructionList il = new InstructionList();
  769. // PTWIMPL ?? Should check if it is null and throw
  770. // NoAspectBoundException
  771. InstructionFactory fact = gen.getFactory();
  772. il.append(fact.createFieldAccess(gen.getClassName(), fg.getName(), fieldType, Constants.GETSTATIC));
  773. il.append(InstructionFactory.createReturn(fieldType));
  774. mg.getBody().insert(il);
  775. gen.addMethodGen(mg);
  776. return true;
  777. // } else {
  778. // return false;
  779. // }
  780. }
  781. // ??? Why do we have this method? I thought by now we would know if it
  782. // matched or not
  783. private boolean couldMatch(BcelObjectType bcelObjectType, Pointcut pointcut) {
  784. return !bcelObjectType.isInterface();
  785. }
  786. private boolean mungeNewMemberType(BcelClassWeaver classWeaver, NewMemberClassTypeMunger munger) {
  787. World world = classWeaver.getWorld();
  788. ResolvedType onType = world.resolve(munger.getTargetType());
  789. if (onType.isRawType()) {
  790. onType = onType.getGenericType();
  791. }
  792. return onType.equals(classWeaver.getLazyClassGen().getType());
  793. }
  794. private boolean mungeNewMethod(BcelClassWeaver classWeaver, NewMethodTypeMunger munger) {
  795. World world = classWeaver.getWorld();
  796. // Resolving it will sort out the tvars
  797. ResolvedMember unMangledInterMethod = munger.getSignature().resolve(world);
  798. // do matching on the unMangled one, but actually add them to the mangled method
  799. ResolvedMember interMethodBody = munger.getDeclaredInterMethodBody(aspectType, world);
  800. ResolvedMember interMethodDispatcher = munger.getDeclaredInterMethodDispatcher(aspectType, world);
  801. ResolvedMember memberHoldingAnyAnnotations = interMethodDispatcher;
  802. LazyClassGen classGen = classWeaver.getLazyClassGen();
  803. ResolvedType onType = world.resolve(unMangledInterMethod.getDeclaringType(), munger.getSourceLocation());
  804. if (onType.isRawType()) {
  805. onType = onType.getGenericType();
  806. }
  807. // Simple checks, can't ITD on annotations or enums
  808. if (onType.isAnnotation()) {
  809. signalError(WeaverMessages.ITDM_ON_ANNOTATION_NOT_ALLOWED, classWeaver, onType);
  810. return false;
  811. }
  812. if (onType.isEnum()) {
  813. signalError(WeaverMessages.ITDM_ON_ENUM_NOT_ALLOWED, classWeaver, onType);
  814. return false;
  815. }
  816. boolean mungingInterface = classGen.isInterface();
  817. boolean onInterface = onType.isInterface();
  818. if (onInterface
  819. && classGen.getLazyMethodGen(unMangledInterMethod.getName(), unMangledInterMethod.getSignature(), true) != null) {
  820. // this is ok, we could be providing the default implementation of a
  821. // method
  822. // that the target has already declared
  823. return false;
  824. }
  825. // If we are processing the intended ITD target type (might be an interface)
  826. if (onType.equals(classGen.getType())) {
  827. ResolvedMember mangledInterMethod = AjcMemberMaker.interMethod(unMangledInterMethod, aspectType, onInterface);
  828. LazyMethodGen newMethod = makeMethodGen(classGen, mangledInterMethod);
  829. if (mungingInterface) {
  830. // we want the modifiers of the ITD to be used for all *implementors* of the
  831. // interface, but the method itself we add to the interface must be public abstract
  832. newMethod.setAccessFlags(Modifier.PUBLIC | Modifier.ABSTRACT);
  833. }
  834. // pr98901
  835. // For copying the annotations across, we have to discover the real
  836. // member in the aspect which is holding them.
  837. if (classWeaver.getWorld().isInJava5Mode()) {
  838. AnnotationAJ annotationsOnRealMember[] = null;
  839. ResolvedType toLookOn = aspectType;
  840. if (aspectType.isRawType()) {
  841. toLookOn = aspectType.getGenericType();
  842. }
  843. ResolvedMember realMember = getRealMemberForITDFromAspect(toLookOn, memberHoldingAnyAnnotations, false);
  844. // 266602 - consider it missing to mean that the corresponding aspect had errors
  845. if (realMember == null) {
  846. // signalWarning("Unable to apply any annotations attached to " + munger.getSignature(), weaver);
  847. // throw new BCException("Couldn't find ITD init member '" + interMethodBody + "' on aspect " + aspectType);
  848. } else {
  849. annotationsOnRealMember = realMember.getAnnotations();
  850. }
  851. Set<ResolvedType> addedAnnotations = new HashSet<>();
  852. if (annotationsOnRealMember != null) {
  853. for (AnnotationAJ anno : annotationsOnRealMember) {
  854. AnnotationGen a = ((BcelAnnotation) anno).getBcelAnnotation();
  855. AnnotationGen ag = new AnnotationGen(a, classGen.getConstantPool(), true);
  856. newMethod.addAnnotation(new BcelAnnotation(ag, classWeaver.getWorld()));
  857. addedAnnotations.add(anno.getType());
  858. }
  859. }
  860. if (realMember != null) {
  861. copyOverParameterAnnotations(newMethod, realMember);
  862. }
  863. // the code below was originally added to cope with the case where an aspect declares an annotation on an ITD
  864. // declared within itself (an unusual situation). However, it also addresses the case where we may not find the
  865. // annotation on the real representation of the ITD. This can happen in a load-time weaving situation where
  866. // we couldn't add the annotation in time - and so here we recheck the declare annotations. Not quite ideal but
  867. // works. pr288635
  868. List<DeclareAnnotation> allDecams = world.getDeclareAnnotationOnMethods();
  869. for (DeclareAnnotation declareAnnotationMC : allDecams) {
  870. if (declareAnnotationMC.matches(unMangledInterMethod, world)) {
  871. // && newMethod.getEnclosingClass().getType() == aspectType) {
  872. AnnotationAJ annotation = declareAnnotationMC.getAnnotation();
  873. if (!addedAnnotations.contains(annotation.getType())) {
  874. newMethod.addAnnotation(annotation);
  875. }
  876. }
  877. }
  878. }
  879. // If it doesn't target an interface and there is a body (i.e. it isnt abstract)
  880. if (!onInterface && !Modifier.isAbstract(mangledInterMethod.getModifiers())) {
  881. InstructionList body = newMethod.getBody();
  882. InstructionFactory fact = classGen.getFactory();
  883. int pos = 0;
  884. if (!Modifier.isStatic(unMangledInterMethod.getModifiers())) {
  885. body.append(InstructionFactory.createThis());
  886. pos++;
  887. }
  888. Type[] paramTypes = BcelWorld.makeBcelTypes(mangledInterMethod.getParameterTypes());
  889. for (Type paramType : paramTypes) {
  890. body.append(InstructionFactory.createLoad(paramType, pos));
  891. pos += paramType.getSize();
  892. }
  893. body.append(Utility.createInvoke(fact, classWeaver.getWorld(), interMethodBody));
  894. body.append(InstructionFactory.createReturn(BcelWorld.makeBcelType(mangledInterMethod.getReturnType())));
  895. if (classWeaver.getWorld().isInJava5Mode()) { // Don't need bridge
  896. // methods if not in
  897. // 1.5 mode.
  898. createAnyBridgeMethodsForCovariance(classWeaver, munger, unMangledInterMethod, onType, classGen, paramTypes);
  899. }
  900. } else {
  901. // ??? this is okay
  902. // if (!(mg.getBody() == null)) throw new
  903. // RuntimeException("bas");
  904. }
  905. if (world.isInJava5Mode()) {
  906. String basicSignature = mangledInterMethod.getSignature();
  907. String genericSignature = ((ResolvedMemberImpl) mangledInterMethod).getSignatureForAttribute();
  908. if (!basicSignature.equals(genericSignature)) {
  909. // Add a signature attribute to it
  910. newMethod.addAttribute(createSignatureAttribute(classGen.getConstantPool(), genericSignature));
  911. }
  912. }
  913. // XXX make sure to check that we set exceptions properly on this
  914. // guy.
  915. classWeaver.addLazyMethodGen(newMethod);
  916. classWeaver.getLazyClassGen().warnOnAddedMethod(newMethod.getMethod(), getSignature().getSourceLocation());
  917. addNeededSuperCallMethods(classWeaver, onType, munger.getSuperMethodsCalled());
  918. return true;
  919. } else if (onInterface && !Modifier.isAbstract(unMangledInterMethod.getModifiers())) {
  920. // This means the 'gen' should be the top most implementor
  921. // - if it is *not* then something went wrong after we worked
  922. // out that it was the top most implementor (see pr49657)
  923. if (!classGen.getType().isTopmostImplementor(onType)) {
  924. ResolvedType rtx = classGen.getType().getTopmostImplementor(onType);
  925. if (rtx == null) {
  926. // pr302460
  927. // null means there is something wrong with what we are looking at
  928. ResolvedType rt = classGen.getType();
  929. if (rt.isInterface()) {
  930. ISourceLocation sloc = munger.getSourceLocation();
  931. classWeaver
  932. .getWorld()
  933. .getMessageHandler()
  934. .handleMessage(
  935. MessageUtil.error(
  936. "ITD target "
  937. + rt.getName()
  938. + " is an interface but has been incorrectly determined to be the topmost implementor of "
  939. + onType.getName() + ". ITD is " + this.getSignature(), sloc));
  940. }
  941. if (!onType.isAssignableFrom(rt)) {
  942. ISourceLocation sloc = munger.getSourceLocation();
  943. classWeaver
  944. .getWorld()
  945. .getMessageHandler()
  946. .handleMessage(
  947. MessageUtil.error(
  948. "ITD target " + rt.getName() + " doesn't appear to implement " + onType.getName()
  949. + " why did we consider it the top most implementor? ITD is "
  950. + this.getSignature(), sloc));
  951. }
  952. } else if (!rtx.isExposedToWeaver()) {
  953. ISourceLocation sLoc = munger.getSourceLocation();
  954. classWeaver
  955. .getWorld()
  956. .getMessageHandler()
  957. .handleMessage(
  958. MessageUtil.error(WeaverMessages.format(WeaverMessages.ITD_NON_EXPOSED_IMPLEMENTOR, rtx,
  959. getAspectType().getName()), (sLoc == null ? getAspectType().getSourceLocation() : sLoc)));
  960. } else {
  961. // XXX what does this state mean?
  962. // We have incorrectly identified what is the top most
  963. // implementor and its not because
  964. // a type wasn't exposed to the weaver
  965. }
  966. return false;
  967. } else {
  968. ResolvedMember mangledInterMethod = AjcMemberMaker.interMethod(unMangledInterMethod, aspectType, false);
  969. LazyMethodGen mg = makeMethodGen(classGen, mangledInterMethod);
  970. // From 98901#29 - need to copy annotations across
  971. if (classWeaver.getWorld().isInJava5Mode()) {
  972. AnnotationAJ annotationsOnRealMember[] = null;
  973. ResolvedType toLookOn = aspectType;
  974. if (aspectType.isRawType()) {
  975. toLookOn = aspectType.getGenericType();
  976. }
  977. ResolvedMember realMember = getRealMemberForITDFromAspect(toLookOn, memberHoldingAnyAnnotations, false);
  978. if (realMember == null) {
  979. throw new BCException("Couldn't find ITD holder member '" + memberHoldingAnyAnnotations + "' on aspect "
  980. + aspectType);
  981. }
  982. annotationsOnRealMember = realMember.getAnnotations();
  983. if (annotationsOnRealMember != null) {
  984. for (AnnotationAJ annotationX : annotationsOnRealMember) {
  985. AnnotationGen a = ((BcelAnnotation) annotationX).getBcelAnnotation();
  986. AnnotationGen ag = new AnnotationGen(a, classWeaver.getLazyClassGen().getConstantPool(), true);
  987. mg.addAnnotation(new BcelAnnotation(ag, classWeaver.getWorld()));
  988. }
  989. }
  990. copyOverParameterAnnotations(mg, realMember);
  991. }
  992. if (mungingInterface) {
  993. // we want the modifiers of the ITD to be used for all
  994. // *implementors* of the
  995. // interface, but the method itself we add to the interface
  996. // must be public abstract
  997. mg.setAccessFlags(Modifier.PUBLIC | Modifier.ABSTRACT);
  998. }
  999. Type[] paramTypes = BcelWorld.makeBcelTypes(mangledInterMethod.getParameterTypes());
  1000. Type returnType = BcelWorld.makeBcelType(mangledInterMethod.getReturnType());
  1001. InstructionList body = mg.getBody();
  1002. InstructionFactory fact = classGen.getFactory();
  1003. int pos = 0;
  1004. if (!Modifier.isStatic(mangledInterMethod.getModifiers())) {
  1005. body.append(InstructionFactory.createThis());
  1006. pos++;
  1007. }
  1008. for (Type paramType : paramTypes) {
  1009. body.append(InstructionFactory.createLoad(paramType, pos));
  1010. pos += paramType.getSize();
  1011. }
  1012. body.append(Utility.createInvoke(fact, classWeaver.getWorld(), interMethodBody));
  1013. Type t = BcelWorld.makeBcelType(interMethodBody.getReturnType());
  1014. if (!t.equals(returnType)) {
  1015. body.append(fact.createCast(t, returnType));
  1016. }
  1017. body.append(InstructionFactory.createReturn(returnType));
  1018. mg.definingType = onType;
  1019. if (world.isInJava5Mode()) {
  1020. String basicSignature = mangledInterMethod.getSignature();
  1021. String genericSignature = ((ResolvedMemberImpl) mangledInterMethod).getSignatureForAttribute();
  1022. if (!basicSignature.equals(genericSignature)) {
  1023. // Add a signature attribute to it
  1024. mg.addAttribute(createSignatureAttribute(classGen.getConstantPool(), genericSignature));
  1025. }
  1026. }
  1027. classWeaver.addOrReplaceLazyMethodGen(mg);
  1028. addNeededSuperCallMethods(classWeaver, onType, munger.getSuperMethodsCalled());
  1029. // Work out if we need a bridge method for the new method added to the topmostimplementor.
  1030. // Check if the munger being processed is a parameterized form of the original munger
  1031. createBridgeIfNecessary(classWeaver, munger, unMangledInterMethod, classGen);
  1032. return true;
  1033. }
  1034. } else {
  1035. return false;
  1036. }
  1037. }
  1038. private void createBridgeIfNecessary(BcelClassWeaver classWeaver, NewMethodTypeMunger munger,
  1039. ResolvedMember unMangledInterMethod, LazyClassGen classGen) {
  1040. if (munger.getDeclaredSignature() != null) {
  1041. boolean needsbridging = false;
  1042. ResolvedMember mungerSignature = munger.getSignature();
  1043. ResolvedMember toBridgeTo = munger.getDeclaredSignature().parameterizedWith(null,
  1044. mungerSignature.getDeclaringType().resolve(getWorld()), false, munger.getTypeVariableAliases());
  1045. if (!toBridgeTo.getReturnType().getErasureSignature().equals(mungerSignature.getReturnType().getErasureSignature())) {
  1046. needsbridging = true;
  1047. }
  1048. UnresolvedType[] originalParams = toBridgeTo.getParameterTypes();
  1049. UnresolvedType[] newParams = mungerSignature.getParameterTypes();
  1050. for (int ii = 0; ii < originalParams.length; ii++) {
  1051. if (!originalParams[ii].getErasureSignature().equals(newParams[ii].getErasureSignature())) {
  1052. needsbridging = true;
  1053. }
  1054. }
  1055. if (needsbridging) {
  1056. createBridge(classWeaver, unMangledInterMethod, classGen, toBridgeTo);
  1057. }
  1058. }
  1059. }
  1060. private void copyOverParameterAnnotations(LazyMethodGen receiverMethod, ResolvedMember donorMethod) {
  1061. AnnotationAJ[][] pAnnos = donorMethod.getParameterAnnotations();
  1062. if (pAnnos != null) {
  1063. int offset = receiverMethod.isStatic() ? 0 : 1;
  1064. int param = 0;
  1065. for (int i = offset; i < pAnnos.length; i++) {
  1066. AnnotationAJ[] annosOnParam = pAnnos[i];
  1067. if (annosOnParam != null) {
  1068. for (AnnotationAJ anno : annosOnParam) {
  1069. receiverMethod.addParameterAnnotation(param, anno);
  1070. }
  1071. }
  1072. param++;
  1073. }
  1074. }
  1075. }
  1076. private void createBridge(BcelClassWeaver weaver, ResolvedMember unMangledInterMethod, LazyClassGen classGen,
  1077. ResolvedMember toBridgeTo) {
  1078. Type[] paramTypes;
  1079. Type returnType;
  1080. InstructionList body;
  1081. InstructionFactory fact;
  1082. int pos;
  1083. ResolvedMember bridgerMethod = AjcMemberMaker.bridgerToInterMethod(unMangledInterMethod, classGen.getType());
  1084. ResolvedMember bridgingSetter = AjcMemberMaker.interMethodBridger(toBridgeTo, aspectType, false); // pr250493
  1085. LazyMethodGen bridgeMethod = makeMethodGen(classGen, bridgingSetter);
  1086. paramTypes = BcelWorld.makeBcelTypes(bridgingSetter.getParameterTypes());
  1087. Type[] bridgingToParms = BcelWorld.makeBcelTypes(unMangledInterMethod.getParameterTypes());
  1088. returnType = BcelWorld.makeBcelType(bridgingSetter.getReturnType());
  1089. body = bridgeMethod.getBody();
  1090. fact = classGen.getFactory();
  1091. pos = 0;
  1092. if (!Modifier.isStatic(bridgingSetter.getModifiers())) {
  1093. body.append(InstructionFactory.createThis());
  1094. pos++;
  1095. }
  1096. for (int i = 0, len = paramTypes.length; i < len; i++) {
  1097. Type paramType = paramTypes[i];
  1098. body.append(InstructionFactory.createLoad(paramType, pos));
  1099. if (!bridgingSetter.getParameterTypes()[i].getErasureSignature().equals(
  1100. unMangledInterMethod.getParameterTypes()[i].getErasureSignature())) {
  1101. // System.err.println("Putting in cast from "+
  1102. // paramType+" to "+bridgingToParms[i]);
  1103. body.append(fact.createCast(paramType, bridgingToParms[i]));
  1104. }
  1105. pos += paramType.getSize();
  1106. }
  1107. body.append(Utility.createInvoke(fact, weaver.getWorld(), bridgerMethod));
  1108. body.append(InstructionFactory.createReturn(returnType));
  1109. classGen.addMethodGen(bridgeMethod);
  1110. // mg.definingType = onType;
  1111. }
  1112. /**
  1113. * Helper method to create a signature attribute based on a string signature: e.g. "Ljava/lang/Object;LI<Ljava/lang/Double;>;"
  1114. */
  1115. private Signature createSignatureAttribute(ConstantPool cp, String signature) {
  1116. int nameIndex = cp.addUtf8("Signature");
  1117. int sigIndex = cp.addUtf8(signature);
  1118. return new Signature(nameIndex, 2, sigIndex, cp);
  1119. }
  1120. /**
  1121. * Create any bridge method required because of covariant returns being used. This method is used in the case where an ITD is
  1122. * applied to some type and it may be in an override relationship with a method from the supertype - but due to covariance there
  1123. * is a mismatch in return values. Example of when required: Super defines: Object m(String s) Sub defines: String m(String s)
  1124. * then we need a bridge method in Sub called 'Object m(String s)' that forwards to 'String m(String s)'
  1125. */
  1126. private void createAnyBridgeMethodsForCovariance(BcelClassWeaver weaver, NewMethodTypeMunger munger,
  1127. ResolvedMember unMangledInterMethod, ResolvedType onType, LazyClassGen gen, Type[] paramTypes) {
  1128. // PERFORMANCE BOTTLENECK? Might need investigating, method analysis
  1129. // between types in a hierarchy just seems expensive...
  1130. // COVARIANCE BRIDGING
  1131. // Algorithm: Step1. Check in this type - has someone already created
  1132. // the bridge method?
  1133. // Step2. Look above us - do we 'override' a method and yet differ in
  1134. // return type (i.e. covariance)
  1135. // Step3. Create a forwarding bridge method
  1136. // ResolvedType superclass = onType.getSuperclass();
  1137. boolean quitRightNow = false;
  1138. String localMethodName = unMangledInterMethod.getName();
  1139. String erasedSig = unMangledInterMethod.getSignatureErased(); // will be something like (LSuperB;)LFoo;
  1140. String localParameterSig = erasedSig.substring(0,erasedSig.lastIndexOf(')')+1);//unMangledInterMethod.getParameterSignature();
  1141. // getParameterSignatureErased() does not include parens, which we do need.
  1142. String localReturnTypeESig = unMangledInterMethod.getReturnType().getErasureSignature();
  1143. // Step1
  1144. boolean alreadyDone = false; // Compiler might have done it
  1145. ResolvedMember[] localMethods = onType.getDeclaredMethods();
  1146. for (ResolvedMember member : localMethods) {
  1147. if (member.getName().equals(localMethodName)) {
  1148. // Check the params
  1149. if (member.getParameterSignature().equals(localParameterSig)) {
  1150. alreadyDone = true;
  1151. }
  1152. }
  1153. }
  1154. // Step2
  1155. if (!alreadyDone) {
  1156. // Use the iterator form of 'getMethods()' so we do as little work as necessary
  1157. ResolvedType supertype = onType.getSuperclass();
  1158. if (supertype != null) {
  1159. for (Iterator<ResolvedMember> iter = supertype.getMethods(true, true); iter.hasNext() && !quitRightNow;) {
  1160. ResolvedMember aMethod = iter.next();
  1161. if (aMethod.getName().equals(localMethodName) && aMethod.getParameterSignature().equals(localParameterSig)) {
  1162. // check the return types, if they are different we need a
  1163. // bridging method.
  1164. if (!aMethod.getReturnType().getErasureSignature().equals(localReturnTypeESig)
  1165. && !Modifier.isPrivate(aMethod.getModifiers())) {
  1166. // Step3
  1167. createBridgeMethod(weaver.getWorld(), munger, unMangledInterMethod, gen, paramTypes, aMethod);
  1168. quitRightNow = true;
  1169. }
  1170. }
  1171. }
  1172. }
  1173. }
  1174. }
  1175. /**
  1176. * Create a bridge method for a particular munger.
  1177. *
  1178. * @param world
  1179. * @param munger
  1180. * @param unMangledInterMethod the method to bridge 'to' that we have already created in the 'subtype'
  1181. * @param clazz the class in which to put the bridge method
  1182. * @param paramTypes Parameter types for the bridge method, passed in as an optimization since the caller is likely to have
  1183. * already created them.
  1184. * @param theBridgeMethod
  1185. */
  1186. private void createBridgeMethod(BcelWorld world, NewMethodTypeMunger munger, ResolvedMember unMangledInterMethod,
  1187. LazyClassGen clazz, Type[] paramTypes, ResolvedMember theBridgeMethod) {
  1188. InstructionList body;
  1189. InstructionFactory fact;
  1190. int pos = 0;
  1191. // The bridge method in this type will have the same signature as the one in the supertype
  1192. LazyMethodGen bridgeMethod = makeMethodGen(clazz, theBridgeMethod);
  1193. bridgeMethod.setAccessFlags(bridgeMethod.getAccessFlags() | 0x00000040 /* BRIDGE = 0x00000040 */);
  1194. // UnresolvedType[] newParams = munger.getSignature().getParameterTypes();
  1195. Type returnType = BcelWorld.makeBcelType(theBridgeMethod.getReturnType());
  1196. body = bridgeMethod.getBody();
  1197. fact = clazz.getFactory();
  1198. if (!Modifier.isStatic(unMangledInterMethod.getModifiers())) {
  1199. body.append(InstructionFactory.createThis());
  1200. pos++;
  1201. }
  1202. for (Type paramType : paramTypes) {
  1203. body.append(InstructionFactory.createLoad(paramType, pos));
  1204. // if (!bridgingSetter.getParameterTypes()[i].getErasureSignature().
  1205. // equals
  1206. // (unMangledInterMethod.getParameterTypes()[i].getErasureSignature
  1207. // ())) {
  1208. // System.err.println("Putting in cast from "+paramType+" to "+
  1209. // bridgingToParms[i]);
  1210. // body.append(fact.createCast(paramType,bridgingToParms[i]));
  1211. // }
  1212. pos += paramType.getSize();
  1213. }
  1214. body.append(Utility.createInvoke(fact, world, unMangledInterMethod));
  1215. body.append(InstructionFactory.createReturn(returnType));
  1216. clazz.addMethodGen(bridgeMethod);
  1217. }
  1218. // Unlike toString() on a member, this does not include the declaring type
  1219. private String stringifyMember(ResolvedMember member) {
  1220. StringBuilder buf = new StringBuilder();
  1221. buf.append(member.getReturnType().getName());
  1222. buf.append(' ');
  1223. buf.append(member.getName());
  1224. if (member.getKind() != Member.FIELD) {
  1225. buf.append("(");
  1226. UnresolvedType[] params = member.getParameterTypes();
  1227. if (params.length != 0) {
  1228. buf.append(params[0]);
  1229. for (int i = 1, len = params.length; i < len; i++) {
  1230. buf.append(", ");
  1231. buf.append(params[i].getName());
  1232. }
  1233. }
  1234. buf.append(")");
  1235. }
  1236. return buf.toString();
  1237. }
  1238. private boolean mungeMethodDelegate(BcelClassWeaver weaver, MethodDelegateTypeMunger munger) {
  1239. World world = weaver.getWorld();
  1240. LazyClassGen gen = weaver.getLazyClassGen();
  1241. if (gen.getType().isAnnotation() || gen.getType().isEnum()) {
  1242. // don't signal error as it could be a consequence of a wild type pattern
  1243. return false;
  1244. }
  1245. ResolvedMember introduced = munger.getSignature();
  1246. ResolvedType fromType = world.resolve(introduced.getDeclaringType(), munger.getSourceLocation());
  1247. if (fromType.isRawType()) {
  1248. fromType = fromType.getGenericType();
  1249. }
  1250. boolean shouldApply = munger.matches(weaver.getLazyClassGen().getType(), aspectType);
  1251. if (shouldApply) {
  1252. Type bcelReturnType = BcelWorld.makeBcelType(introduced.getReturnType());
  1253. // If no implementation class was specified, the intention was that
  1254. // the types matching the pattern
  1255. // already implemented the interface, let's check that now!
  1256. if (munger.getImplClassName() == null && !munger.specifiesDelegateFactoryMethod()) {
  1257. boolean isOK = false;
  1258. List<LazyMethodGen> existingMethods = gen.getMethodGens();
  1259. for (LazyMethodGen m : existingMethods) {
  1260. if (m.getName().equals(introduced.getName())
  1261. && m.getParameterSignature().equals(introduced.getParameterSignature())
  1262. && m.getReturnType().equals(bcelReturnType)) {
  1263. isOK = true;
  1264. }
  1265. }
  1266. if (!isOK) {
  1267. // the class does not implement this method, they needed to
  1268. // supply a default impl class
  1269. IMessage msg = new Message("@DeclareParents: No defaultImpl was specified but the type '" + gen.getName()
  1270. + "' does not implement the method '" + stringifyMember(introduced) + "' defined on the interface '"
  1271. + introduced.getDeclaringType() + "'", weaver.getLazyClassGen().getType().getSourceLocation(), true,
  1272. new ISourceLocation[] { munger.getSourceLocation() });
  1273. weaver.getWorld().getMessageHandler().handleMessage(msg);
  1274. return false;
  1275. }
  1276. return true;
  1277. }
  1278. LazyMethodGen mg = new LazyMethodGen(introduced.getModifiers() - Modifier.ABSTRACT, bcelReturnType,
  1279. introduced.getName(), BcelWorld.makeBcelTypes(introduced.getParameterTypes()),
  1280. BcelWorld.makeBcelTypesAsClassNames(introduced.getExceptions()), gen);
  1281. // annotation copy from annotation on ITD interface
  1282. if (weaver.getWorld().isInJava5Mode()) {
  1283. AnnotationAJ annotationsOnRealMember[] = null;
  1284. ResolvedType toLookOn = weaver.getWorld().lookupOrCreateName(introduced.getDeclaringType());
  1285. if (fromType.isRawType()) {
  1286. toLookOn = fromType.getGenericType();
  1287. }
  1288. // lookup the method
  1289. ResolvedMember[] ms = toLookOn.getDeclaredJavaMethods();
  1290. for (ResolvedMember m : ms) {
  1291. if (introduced.getName().equals(m.getName()) && introduced.getSignature().equals(m.getSignature())) {
  1292. annotationsOnRealMember = m.getAnnotations();
  1293. break;
  1294. }
  1295. }
  1296. if (annotationsOnRealMember != null) {
  1297. for (AnnotationAJ anno : annotationsOnRealMember) {
  1298. AnnotationGen a = ((BcelAnnotation) anno).getBcelAnnotation();
  1299. AnnotationGen ag = new AnnotationGen(a, weaver.getLazyClassGen().getConstantPool(), true);
  1300. mg.addAnnotation(new BcelAnnotation(ag, weaver.getWorld()));
  1301. }
  1302. }
  1303. }
  1304. InstructionList body = new InstructionList();
  1305. InstructionFactory fact = gen.getFactory();
  1306. // Wrap delegate field initialisation in 'synchronized(this)' block - MONITORENTER (beginning of 'try')
  1307. body.append(InstructionConstants.ALOAD_0);
  1308. body.append(InstructionConstants.MONITORENTER);
  1309. // The JVM spec requires us add an exception handler ensuring MONITOREXIT in case of an exception inside the
  1310. // synchronized block, see https://docs.oracle.com/javase/specs/jvms/se17/html/jvms-3.html#jvms-3.14.
  1311. InstructionHandle tryStart = body.append(InstructionConstants.ALOAD_0);
  1312. body.append(Utility.createGet(fact, munger.getDelegate(weaver.getLazyClassGen().getType())));
  1313. InstructionBranch ifNonNull = InstructionFactory.createBranchInstruction(Constants.IFNONNULL, null);
  1314. body.append(ifNonNull);
  1315. // Create and store a new instance
  1316. body.append(InstructionConstants.ALOAD_0); // 'this' is where we'll store the field value
  1317. // TODO for non-static case, call aspectOf() then call the factory method on the retval
  1318. // TODO decide whether the value can really be cached
  1319. // locate the aspect and call the static method in it
  1320. if (munger.specifiesDelegateFactoryMethod()) {
  1321. ResolvedMember rm = munger.getDelegateFactoryMethod(weaver.getWorld());
  1322. // Check the method parameter is compatible with the type of the instance to be passed
  1323. if (rm.getArity() != 0) {
  1324. ResolvedType parameterType = rm.getParameterTypes()[0].resolve(weaver.getWorld());
  1325. if (!parameterType.isAssignableFrom(weaver.getLazyClassGen().getType())) {
  1326. signalError("For mixin factory method '" + rm + "': Instance type '" + weaver.getLazyClassGen().getType()
  1327. + "' is not compatible with factory parameter type '" + parameterType + "'", weaver);
  1328. return false;
  1329. }
  1330. }
  1331. if (Modifier.isStatic(rm.getModifiers())) {
  1332. if (rm.getArity() != 0) {
  1333. body.append(InstructionConstants.ALOAD_0);
  1334. }
  1335. body.append(fact.createInvoke(rm.getDeclaringType().getName(), rm.getName(), rm.getSignature(),
  1336. Constants.INVOKESTATIC));
  1337. body.append(Utility.createSet(fact, munger.getDelegate(weaver.getLazyClassGen().getType())));
  1338. } else {
  1339. // Need to call aspectOf() to obtain the aspect instance then call the factory method upon that
  1340. UnresolvedType theAspect = munger.getAspect();
  1341. body.append(fact.createInvoke(theAspect.getName(), "aspectOf", "()" + theAspect.getSignature(),
  1342. Constants.INVOKESTATIC));
  1343. if (rm.getArity() != 0) {
  1344. body.append(InstructionConstants.ALOAD_0);
  1345. }
  1346. body.append(fact.createInvoke(rm.getDeclaringType().getName(), rm.getName(), rm.getSignature(),
  1347. Constants.INVOKEVIRTUAL));
  1348. body.append(Utility.createSet(fact, munger.getDelegate(weaver.getLazyClassGen().getType())));
  1349. }
  1350. } else {
  1351. body.append(fact.createNew(munger.getImplClassName()));
  1352. body.append(InstructionConstants.DUP);
  1353. body.append(fact.createInvoke(munger.getImplClassName(), "<init>", Type.VOID, Type.NO_ARGS, Constants.INVOKESPECIAL));
  1354. body.append(Utility.createSet(fact, munger.getDelegate(weaver.getLazyClassGen().getType())));
  1355. }
  1356. // Wrap delegate field initialisation in 'synchronized(this)' block - MONITOREXIT (end of 'try')
  1357. InstructionHandle ifNonNullElse = body.append(InstructionConstants.ALOAD_0);
  1358. ifNonNull.setTarget(ifNonNullElse);
  1359. body.append(InstructionConstants.MONITOREXIT);
  1360. // There was no error in the 'synchronized(this)' block -> jump to first instruction after exception handler
  1361. InstructionBranch gotoAfterTryCatch = new InstructionBranch(Constants.GOTO, null);
  1362. InstructionHandle tryEnd = body.append(gotoAfterTryCatch);
  1363. // Exception handler (logical 'catch') for the 'synchronized(this)' block ensures that MONITOREXIT is also called
  1364. // in case of an error
  1365. InstructionHandle catchStart = body.append(InstructionConstants.ALOAD_0);
  1366. body.append(InstructionConstants.MONITOREXIT);
  1367. InstructionHandle catchEnd = body.append(InstructionConstants.ATHROW);
  1368. // Add exception handler for 'synchronized(this)' block
  1369. mg.addExceptionHandler(tryStart, tryEnd.getPrev(), catchStart, null, false);
  1370. // CAVEAT: Add an extra, self-referential exception handler entry. I.e., the handler handles its own exceptions.
  1371. // According to https://docs.oracle.com/javase/specs/jvms/se17/html/jvms-3.html#jvms-3.14, this is required, and
  1372. // Javac also creates code like this, which is why we are mimicking it.
  1373. mg.addExceptionHandler(catchStart, catchEnd.getPrev(), catchStart, null, false);
  1374. // if not null use the instance we've got
  1375. InstructionHandle afterTryCatch = body.append(InstructionConstants.ALOAD_0);
  1376. // Tell 'gotoAfterTryCatch' where to find the first statement after the exception handler
  1377. gotoAfterTryCatch.setTarget(afterTryCatch);
  1378. body.append(Utility.createGet(fact, munger.getDelegate(weaver.getLazyClassGen().getType())));
  1379. // args
  1380. int pos = 0;
  1381. if (!Modifier.isStatic(introduced.getModifiers())) { // skip 'this' (?? can this really
  1382. // happen)
  1383. // body.append(InstructionFactory.createThis());
  1384. pos++;
  1385. }
  1386. Type[] paramTypes = BcelWorld.makeBcelTypes(introduced.getParameterTypes());
  1387. for (Type paramType : paramTypes) {
  1388. body.append(InstructionFactory.createLoad(paramType, pos));
  1389. pos += paramType.getSize();
  1390. }
  1391. body.append(Utility.createInvoke(fact, Constants.INVOKEINTERFACE, introduced));
  1392. body.append(InstructionFactory.createReturn(bcelReturnType));
  1393. mg.getBody().append(body);
  1394. weaver.addLazyMethodGen(mg);
  1395. weaver.getLazyClassGen().warnOnAddedMethod(mg.getMethod(), getSignature().getSourceLocation());
  1396. return true;
  1397. }
  1398. return false;
  1399. }
  1400. private boolean mungeFieldHost(BcelClassWeaver weaver, MethodDelegateTypeMunger.FieldHostTypeMunger munger) {
  1401. LazyClassGen gen = weaver.getLazyClassGen();
  1402. if (gen.getType().isAnnotation() || gen.getType().isEnum()) {
  1403. // don't signal error as it could be a consequence of a wild type
  1404. // pattern
  1405. return false;
  1406. }
  1407. // boolean shouldApply =
  1408. munger.matches(weaver.getLazyClassGen().getType(), aspectType); // why
  1409. // do
  1410. // this?
  1411. ResolvedMember host = AjcMemberMaker.itdAtDeclareParentsField(weaver.getLazyClassGen().getType(), munger.getSignature()
  1412. .getType(), aspectType);
  1413. FieldGen field = makeFieldGen(weaver.getLazyClassGen(), host);
  1414. field.setModifiers(field.getModifiers() | BcelField.AccSynthetic);
  1415. weaver.getLazyClassGen().addField(field, null);
  1416. return true;
  1417. }
  1418. private ResolvedMember getRealMemberForITDFromAspect(ResolvedType aspectType, ResolvedMember lookingFor, boolean isCtorRelated) {
  1419. World world = aspectType.getWorld();
  1420. boolean debug = false;
  1421. if (debug) {
  1422. System.err.println("Searching for a member on type: " + aspectType);
  1423. System.err.println("Member we are looking for: " + lookingFor);
  1424. }
  1425. ResolvedMember aspectMethods[] = aspectType.getDeclaredMethods();
  1426. UnresolvedType[] lookingForParams = lookingFor.getParameterTypes();
  1427. ResolvedMember realMember = null;
  1428. for (int i = 0; realMember == null && i < aspectMethods.length; i++) {
  1429. ResolvedMember member = aspectMethods[i];
  1430. if (member.getName().equals(lookingFor.getName())) {
  1431. UnresolvedType[] memberParams = member.getGenericParameterTypes();
  1432. if (memberParams.length == lookingForParams.length) {
  1433. if (debug) {
  1434. System.err.println("Reviewing potential candidates: " + member);
  1435. }
  1436. boolean matchOK = true;
  1437. // If not related to a ctor ITD then the name is enough to
  1438. // confirm we have the
  1439. // right one. If it is ctor related we need to check the
  1440. // params all match, although
  1441. // only the erasure.
  1442. if (isCtorRelated) {
  1443. for (int j = 0; j < memberParams.length && matchOK; j++) {
  1444. ResolvedType pMember = memberParams[j].resolve(world);
  1445. ResolvedType pLookingFor = lookingForParams[j].resolve(world);
  1446. if (pMember.isTypeVariableReference()) {
  1447. pMember = ((TypeVariableReference) pMember).getTypeVariable().getFirstBound().resolve(world);
  1448. }
  1449. if (pMember.isParameterizedType() || pMember.isGenericType()) {
  1450. pMember = pMember.getRawType().resolve(aspectType.getWorld());
  1451. }
  1452. if (pLookingFor.isTypeVariableReference()) {
  1453. pLookingFor = ((TypeVariableReference) pLookingFor).getTypeVariable().getFirstBound()
  1454. .resolve(world);
  1455. }
  1456. if (pLookingFor.isParameterizedType() || pLookingFor.isGenericType()) {
  1457. pLookingFor = pLookingFor.getRawType().resolve(world);
  1458. }
  1459. if (debug) {
  1460. System.err.println("Comparing parameter " + j + " member=" + pMember + " lookingFor="
  1461. + pLookingFor);
  1462. }
  1463. if (!pMember.equals(pLookingFor)) {
  1464. matchOK = false;
  1465. }
  1466. }
  1467. }
  1468. if (matchOK) {
  1469. realMember = member;
  1470. }
  1471. }
  1472. }
  1473. }
  1474. if (debug && realMember == null) {
  1475. System.err.println("Didn't find a match");
  1476. }
  1477. return realMember;
  1478. }
  1479. private void addNeededSuperCallMethods(BcelClassWeaver weaver, ResolvedType onType, Set<ResolvedMember> neededSuperCalls) {
  1480. LazyClassGen gen = weaver.getLazyClassGen();
  1481. for (ResolvedMember superMethod: neededSuperCalls) {
  1482. if (weaver.addDispatchTarget(superMethod)) {
  1483. // System.err.println("super type: " + superMethod.getDeclaringType() + ", " + gen.getType());
  1484. boolean isSuper = !superMethod.getDeclaringType().equals(gen.getType());
  1485. String dispatchName;
  1486. if (isSuper) {
  1487. dispatchName = NameMangler.superDispatchMethod(onType, superMethod.getName());
  1488. } else {
  1489. dispatchName = NameMangler.protectedDispatchMethod(onType, superMethod.getName());
  1490. }
  1491. superMethod = superMethod.resolve(weaver.getWorld());
  1492. LazyMethodGen dispatcher = makeDispatcher(gen, dispatchName, superMethod, weaver.getWorld(), isSuper);
  1493. weaver.addLazyMethodGen(dispatcher);
  1494. }
  1495. }
  1496. }
  1497. private void signalError(String msgid, BcelClassWeaver weaver, UnresolvedType onType) {
  1498. IMessage msg = MessageUtil.error(WeaverMessages.format(msgid, onType.getName()), getSourceLocation());
  1499. weaver.getWorld().getMessageHandler().handleMessage(msg);
  1500. }
  1501. // private void signalWarning(String msgString, BcelClassWeaver weaver) {
  1502. // IMessage msg = MessageUtil.warn(msgString, getSourceLocation());
  1503. // weaver.getWorld().getMessageHandler().handleMessage(msg);
  1504. // }
  1505. private void signalError(String msgString, BcelClassWeaver weaver) {
  1506. IMessage msg = MessageUtil.error(msgString, getSourceLocation());
  1507. weaver.getWorld().getMessageHandler().handleMessage(msg);
  1508. }
  1509. private boolean mungeNewConstructor(BcelClassWeaver weaver, NewConstructorTypeMunger newConstructorTypeMunger) {
  1510. final LazyClassGen currentClass = weaver.getLazyClassGen();
  1511. final InstructionFactory fact = currentClass.getFactory();
  1512. ResolvedMember newConstructorMember = newConstructorTypeMunger.getSyntheticConstructor();
  1513. ResolvedType onType = newConstructorMember.getDeclaringType().resolve(weaver.getWorld());
  1514. if (onType.isRawType()) {
  1515. onType = onType.getGenericType();
  1516. }
  1517. if (onType.isAnnotation()) {
  1518. signalError(WeaverMessages.ITDC_ON_ANNOTATION_NOT_ALLOWED, weaver, onType);
  1519. return false;
  1520. }
  1521. if (onType.isEnum()) {
  1522. signalError(WeaverMessages.ITDC_ON_ENUM_NOT_ALLOWED, weaver, onType);
  1523. return false;
  1524. }
  1525. if (!onType.equals(currentClass.getType())) {
  1526. return false;
  1527. }
  1528. ResolvedMember explicitConstructor = newConstructorTypeMunger.getExplicitConstructor();
  1529. // int declaredParameterCount =
  1530. // newConstructorTypeMunger.getDeclaredParameterCount();
  1531. LazyMethodGen mg = makeMethodGen(currentClass, newConstructorMember);
  1532. mg.setEffectiveSignature(newConstructorTypeMunger.getSignature(), Shadow.ConstructorExecution, true);
  1533. // pr98901
  1534. // For copying the annotations across, we have to discover the real
  1535. // member in the aspect
  1536. // which is holding them.
  1537. if (weaver.getWorld().isInJava5Mode()) {
  1538. ResolvedMember interMethodDispatcher = AjcMemberMaker.postIntroducedConstructor(aspectType, onType,
  1539. newConstructorTypeMunger.getSignature().getParameterTypes());
  1540. AnnotationAJ annotationsOnRealMember[] = null;
  1541. ResolvedMember realMember = getRealMemberForITDFromAspect(aspectType, interMethodDispatcher, true);
  1542. // 266602 - consider it missing to mean that the corresponding aspect had errors
  1543. if (realMember == null) {
  1544. // signalWarning("Unable to apply any annotations attached to " + munger.getSignature(), weaver);
  1545. // throw new BCException("Couldn't find ITD init member '" + interMethodBody + "' on aspect " + aspectType);
  1546. } else {
  1547. annotationsOnRealMember = realMember.getAnnotations();
  1548. }
  1549. if (annotationsOnRealMember != null) {
  1550. for (AnnotationAJ annotationX : annotationsOnRealMember) {
  1551. AnnotationGen a = ((BcelAnnotation) annotationX).getBcelAnnotation();
  1552. AnnotationGen ag = new AnnotationGen(a, weaver.getLazyClassGen().getConstantPool(), true);
  1553. mg.addAnnotation(new BcelAnnotation(ag, weaver.getWorld()));
  1554. }
  1555. }
  1556. // the below loop fixes the very special (and very stupid)
  1557. // case where an aspect declares an annotation
  1558. // on an ITD it declared on itself.
  1559. List<DeclareAnnotation> allDecams = weaver.getWorld().getDeclareAnnotationOnMethods();
  1560. for (DeclareAnnotation decaMC : allDecams) {
  1561. if (decaMC.matches(explicitConstructor, weaver.getWorld()) && mg.getEnclosingClass().getType() == aspectType) {
  1562. mg.addAnnotation(decaMC.getAnnotation());
  1563. }
  1564. }
  1565. }
  1566. // Might have to remove the default constructor - b275032
  1567. // TODO could have tagged the type munger when the fact we needed to do this was detected earlier
  1568. if (mg.getArgumentTypes().length == 0) {
  1569. LazyMethodGen toRemove = null;
  1570. for (LazyMethodGen object : currentClass.getMethodGens()) {
  1571. if (object.getName().equals("<init>") && object.getArgumentTypes().length == 0) {
  1572. toRemove = object;
  1573. }
  1574. }
  1575. if (toRemove != null) {
  1576. currentClass.removeMethodGen(toRemove);
  1577. }
  1578. }
  1579. currentClass.addMethodGen(mg);
  1580. // weaver.addLazyMethodGen(freshConstructor);
  1581. InstructionList body = mg.getBody();
  1582. // add to body: push arts for call to pre, from actual args starting at
  1583. // 1 (skipping this), going to
  1584. // declared argcount + 1
  1585. UnresolvedType[] declaredParams = newConstructorTypeMunger.getSignature().getParameterTypes();
  1586. Type[] paramTypes = mg.getArgumentTypes();
  1587. int frameIndex = 1;
  1588. for (int i = 0, len = declaredParams.length; i < len; i++) {
  1589. body.append(InstructionFactory.createLoad(paramTypes[i], frameIndex));
  1590. frameIndex += paramTypes[i].getSize();
  1591. }
  1592. // do call to pre
  1593. Member preMethod = AjcMemberMaker.preIntroducedConstructor(aspectType, onType, declaredParams);
  1594. body.append(Utility.createInvoke(fact, null, preMethod));
  1595. // create a local, and store return pre stuff into it.
  1596. int arraySlot = mg.allocateLocal(1);
  1597. body.append(InstructionFactory.createStore(Type.OBJECT, arraySlot));
  1598. // put this on the stack
  1599. body.append(InstructionConstants.ALOAD_0);
  1600. // unpack pre args onto stack
  1601. UnresolvedType[] superParamTypes = explicitConstructor.getParameterTypes();
  1602. for (int i = 0, len = superParamTypes.length; i < len; i++) {
  1603. body.append(InstructionFactory.createLoad(Type.OBJECT, arraySlot));
  1604. body.append(Utility.createConstant(fact, i));
  1605. body.append(InstructionFactory.createArrayLoad(Type.OBJECT));
  1606. body.append(Utility.createConversion(fact, Type.OBJECT, BcelWorld.makeBcelType(superParamTypes[i])));
  1607. }
  1608. // call super/this
  1609. body.append(Utility.createInvoke(fact, null, explicitConstructor));
  1610. // put this back on the stack
  1611. body.append(InstructionConstants.ALOAD_0);
  1612. // unpack params onto stack
  1613. Member postMethod = AjcMemberMaker.postIntroducedConstructor(aspectType, onType, declaredParams);
  1614. UnresolvedType[] postParamTypes = postMethod.getParameterTypes();
  1615. for (int i = 1, len = postParamTypes.length; i < len; i++) {
  1616. body.append(InstructionFactory.createLoad(Type.OBJECT, arraySlot));
  1617. body.append(Utility.createConstant(fact, superParamTypes.length + i - 1));
  1618. body.append(InstructionFactory.createArrayLoad(Type.OBJECT));
  1619. body.append(Utility.createConversion(fact, Type.OBJECT, BcelWorld.makeBcelType(postParamTypes[i])));
  1620. }
  1621. // call post
  1622. body.append(Utility.createInvoke(fact, null, postMethod));
  1623. // don't forget to return!!
  1624. body.append(InstructionConstants.RETURN);
  1625. addNeededSuperCallMethods(weaver, onType, munger.getSuperMethodsCalled());
  1626. return true;
  1627. }
  1628. private static LazyMethodGen makeDispatcher(LazyClassGen onGen, String dispatchName, ResolvedMember superMethod,
  1629. BcelWorld world, boolean isSuper) {
  1630. Type[] paramTypes = BcelWorld.makeBcelTypes(superMethod.getParameterTypes());
  1631. Type returnType = BcelWorld.makeBcelType(superMethod.getReturnType());
  1632. int modifiers = Modifier.PUBLIC;
  1633. if (onGen.isInterface()) {
  1634. modifiers |= Modifier.ABSTRACT;
  1635. }
  1636. LazyMethodGen mg = new LazyMethodGen(modifiers, returnType, dispatchName, paramTypes, UnresolvedType.getNames(superMethod
  1637. .getExceptions()), onGen);
  1638. InstructionList body = mg.getBody();
  1639. if (onGen.isInterface()) {
  1640. return mg;
  1641. }
  1642. // assert (!superMethod.isStatic())
  1643. InstructionFactory fact = onGen.getFactory();
  1644. int pos = 0;
  1645. body.append(InstructionFactory.createThis());
  1646. pos++;
  1647. for (Type paramType : paramTypes) {
  1648. body.append(InstructionFactory.createLoad(paramType, pos));
  1649. pos += paramType.getSize();
  1650. }
  1651. if (isSuper) {
  1652. body.append(Utility.createSuperInvoke(fact, world, superMethod));
  1653. } else {
  1654. body.append(Utility.createInvoke(fact, world, superMethod));
  1655. }
  1656. body.append(InstructionFactory.createReturn(returnType));
  1657. return mg;
  1658. }
  1659. private boolean mungeNewField(BcelClassWeaver weaver, NewFieldTypeMunger munger) {
  1660. /* ResolvedMember initMethod = */munger.getInitMethod(aspectType);
  1661. LazyClassGen gen = weaver.getLazyClassGen();
  1662. ResolvedMember field = munger.getSignature();
  1663. ResolvedType onType = weaver.getWorld().resolve(field.getDeclaringType(), munger.getSourceLocation());
  1664. if (onType.isRawType()) {
  1665. onType = onType.getGenericType();
  1666. }
  1667. boolean onInterface = onType.isInterface();
  1668. if (onType.isAnnotation()) {
  1669. signalError(WeaverMessages.ITDF_ON_ANNOTATION_NOT_ALLOWED, weaver, onType);
  1670. return false;
  1671. }
  1672. if (onType.isEnum()) {
  1673. signalError(WeaverMessages.ITDF_ON_ENUM_NOT_ALLOWED, weaver, onType);
  1674. return false;
  1675. }
  1676. ResolvedMember interMethodBody = munger.getInitMethod(aspectType);
  1677. AnnotationAJ annotationsOnRealMember[] = null;
  1678. // pr98901
  1679. // For copying the annotations across, we have to discover the real
  1680. // member in the aspect
  1681. // which is holding them.
  1682. if (weaver.getWorld().isInJava5Mode()) {
  1683. // the below line just gets the method with the same name in
  1684. // aspectType.getDeclaredMethods();
  1685. ResolvedType toLookOn = aspectType;
  1686. if (aspectType.isRawType()) {
  1687. toLookOn = aspectType.getGenericType();
  1688. }
  1689. ResolvedMember realMember = getRealMemberForITDFromAspect(toLookOn, interMethodBody, false);
  1690. if (realMember == null) {
  1691. // signalWarning("Unable to apply any annotations attached to " + munger.getSignature(), weaver);
  1692. // throw new BCException("Couldn't find ITD init member '" + interMethodBody + "' on aspect " + aspectType);
  1693. } else {
  1694. annotationsOnRealMember = realMember.getAnnotations();
  1695. }
  1696. }
  1697. if (onType.equals(gen.getType())) {
  1698. if (onInterface) {
  1699. ResolvedMember itdfieldGetter = AjcMemberMaker.interFieldInterfaceGetter(field, onType, aspectType);
  1700. LazyMethodGen mg = makeMethodGen(gen, itdfieldGetter);
  1701. gen.addMethodGen(mg);
  1702. LazyMethodGen mg1 = makeMethodGen(gen, AjcMemberMaker.interFieldInterfaceSetter(field, onType, aspectType));
  1703. gen.addMethodGen(mg1);
  1704. } else {
  1705. weaver.addInitializer(this);
  1706. ResolvedMember newField = AjcMemberMaker.interFieldClassField(field, aspectType,
  1707. munger.version == NewFieldTypeMunger.VersionTwo);
  1708. FieldGen fg = makeFieldGen(gen, newField);
  1709. if (annotationsOnRealMember != null) {
  1710. for (AnnotationAJ annotationX : annotationsOnRealMember) {
  1711. AnnotationGen a = ((BcelAnnotation) annotationX).getBcelAnnotation();
  1712. AnnotationGen ag = new AnnotationGen(a, weaver.getLazyClassGen().getConstantPool(), true);
  1713. fg.addAnnotation(ag);
  1714. }
  1715. }
  1716. if (weaver.getWorld().isInJava5Mode()) {
  1717. String basicSignature = field.getSignature();
  1718. String genericSignature = field.getReturnType().resolve(weaver.getWorld()).getSignatureForAttribute();
  1719. // String genericSignature =
  1720. // ((ResolvedMemberImpl)field).getSignatureForAttribute();
  1721. if (!basicSignature.equals(genericSignature)) {
  1722. // Add a signature attribute to it
  1723. fg.addAttribute(createSignatureAttribute(gen.getConstantPool(), genericSignature));
  1724. }
  1725. }
  1726. gen.addField(fg, getSourceLocation());
  1727. }
  1728. return true;
  1729. } else if (onInterface && gen.getType().isTopmostImplementor(onType)) {
  1730. // we know that we can't be static since we don't allow statics on interfaces
  1731. if (Modifier.isStatic(field.getModifiers())) {
  1732. throw new RuntimeException("unimplemented");
  1733. }
  1734. boolean alreadyExists = false;
  1735. // only need to check for version 2 style mungers
  1736. if (munger.version==NewFieldTypeMunger.VersionTwo) {
  1737. for (BcelField fieldgen: gen.getFieldGens()) {
  1738. if (fieldgen.getName().equals(field.getName())) {
  1739. alreadyExists=true;
  1740. break;
  1741. }
  1742. }
  1743. }
  1744. // FieldGen fg = makeFieldGen(gen, AjcMemberMaker.interFieldInterfaceField(field, onType, aspectType));
  1745. ResolvedMember newField = AjcMemberMaker.interFieldInterfaceField(field, onType, aspectType, munger.version == NewFieldTypeMunger.VersionTwo);
  1746. String fieldName = newField.getName();
  1747. Type fieldType = BcelWorld.makeBcelType(field.getType());
  1748. if (!alreadyExists) {
  1749. weaver.addInitializer(this);
  1750. FieldGen fg = makeFieldGen(gen,newField);
  1751. if (annotationsOnRealMember != null) {
  1752. for (AnnotationAJ annotationX : annotationsOnRealMember) {
  1753. AnnotationGen a = ((BcelAnnotation) annotationX).getBcelAnnotation();
  1754. AnnotationGen ag = new AnnotationGen(a, weaver.getLazyClassGen().getConstantPool(), true);
  1755. fg.addAnnotation(ag);
  1756. }
  1757. }
  1758. if (weaver.getWorld().isInJava5Mode()) {
  1759. String basicSignature = field.getSignature();
  1760. String genericSignature = field.getReturnType().resolve(weaver.getWorld()).getSignatureForAttribute();
  1761. // String genericSignature =
  1762. // ((ResolvedMemberImpl)field).getSignatureForAttribute();
  1763. if (!basicSignature.equals(genericSignature)) {
  1764. // Add a signature attribute to it
  1765. fg.addAttribute(createSignatureAttribute(gen.getConstantPool(), genericSignature));
  1766. }
  1767. }
  1768. gen.addField(fg, getSourceLocation());
  1769. }
  1770. // this uses a shadow munger to add init method to constructors
  1771. // weaver.getShadowMungers().add(makeInitCallShadowMunger(initMethod)
  1772. // );
  1773. ResolvedMember itdfieldGetter = AjcMemberMaker.interFieldInterfaceGetter(field, gen.getType()/* onType */, aspectType);
  1774. LazyMethodGen mg = makeMethodGen(gen, itdfieldGetter);
  1775. InstructionList il = new InstructionList();
  1776. InstructionFactory fact = gen.getFactory();
  1777. if (Modifier.isStatic(field.getModifiers())) {
  1778. il.append(fact.createFieldAccess(gen.getClassName(), fieldName, fieldType, Constants.GETSTATIC));
  1779. } else {
  1780. il.append(InstructionConstants.ALOAD_0);
  1781. il.append(fact.createFieldAccess(gen.getClassName(), fieldName, fieldType, Constants.GETFIELD));
  1782. }
  1783. il.append(InstructionFactory.createReturn(fieldType));
  1784. mg.getBody().insert(il);
  1785. gen.addMethodGen(mg);
  1786. // Check if we need bridge methods for the field getter and setter
  1787. if (munger.getDeclaredSignature() != null) { // is this munger a
  1788. // parameterized
  1789. // form of some
  1790. // original munger?
  1791. ResolvedMember toBridgeTo = munger.getDeclaredSignature().parameterizedWith(null,
  1792. munger.getSignature().getDeclaringType().resolve(getWorld()), false, munger.getTypeVariableAliases());
  1793. boolean needsbridging = false;
  1794. if (!toBridgeTo.getReturnType().getErasureSignature()
  1795. .equals(munger.getSignature().getReturnType().getErasureSignature())) {
  1796. needsbridging = true;
  1797. }
  1798. if (needsbridging) {
  1799. ResolvedMember bridgingGetter = AjcMemberMaker.interFieldInterfaceGetter(toBridgeTo, gen.getType(), aspectType);
  1800. createBridgeMethodForITDF(weaver, gen, itdfieldGetter, bridgingGetter);
  1801. }
  1802. }
  1803. ResolvedMember itdfieldSetter = AjcMemberMaker.interFieldInterfaceSetter(field, gen.getType(), aspectType);
  1804. LazyMethodGen mg1 = makeMethodGen(gen, itdfieldSetter);
  1805. InstructionList il1 = new InstructionList();
  1806. if (Modifier.isStatic(field.getModifiers())) {
  1807. il1.append(InstructionFactory.createLoad(fieldType, 0));
  1808. il1.append(fact.createFieldAccess(gen.getClassName(), fieldName, fieldType, Constants.PUTSTATIC));
  1809. } else {
  1810. il1.append(InstructionConstants.ALOAD_0);
  1811. il1.append(InstructionFactory.createLoad(fieldType, 1));
  1812. il1.append(fact.createFieldAccess(gen.getClassName(), fieldName, fieldType, Constants.PUTFIELD));
  1813. }
  1814. il1.append(InstructionFactory.createReturn(Type.VOID));
  1815. mg1.getBody().insert(il1);
  1816. gen.addMethodGen(mg1);
  1817. if (munger.getDeclaredSignature() != null) {
  1818. ResolvedMember toBridgeTo = munger.getDeclaredSignature().parameterizedWith(null,
  1819. munger.getSignature().getDeclaringType().resolve(getWorld()), false, munger.getTypeVariableAliases());
  1820. boolean needsbridging = false;
  1821. if (!toBridgeTo.getReturnType().getErasureSignature()
  1822. .equals(munger.getSignature().getReturnType().getErasureSignature())) {
  1823. needsbridging = true;
  1824. }
  1825. if (needsbridging) {
  1826. ResolvedMember bridgingSetter = AjcMemberMaker.interFieldInterfaceSetter(toBridgeTo, gen.getType(), aspectType);
  1827. createBridgeMethodForITDF(weaver, gen, itdfieldSetter, bridgingSetter);
  1828. }
  1829. }
  1830. return true;
  1831. } else {
  1832. return false;
  1833. }
  1834. }
  1835. // FIXME asc combine with other createBridge.. method in this class, avoid
  1836. // the duplication...
  1837. private void createBridgeMethodForITDF(BcelClassWeaver weaver, LazyClassGen gen, ResolvedMember itdfieldSetter,
  1838. ResolvedMember bridgingSetter) {
  1839. InstructionFactory fact;
  1840. LazyMethodGen bridgeMethod = makeMethodGen(gen, bridgingSetter);
  1841. bridgeMethod.setAccessFlags(bridgeMethod.getAccessFlags() | 0x00000040); // BRIDGE = 0x00000040
  1842. Type[] paramTypes = BcelWorld.makeBcelTypes(bridgingSetter.getParameterTypes());
  1843. Type[] bridgingToParms = BcelWorld.makeBcelTypes(itdfieldSetter.getParameterTypes());
  1844. Type returnType = BcelWorld.makeBcelType(bridgingSetter.getReturnType());
  1845. InstructionList body = bridgeMethod.getBody();
  1846. fact = gen.getFactory();
  1847. int pos = 0;
  1848. if (!Modifier.isStatic(bridgingSetter.getModifiers())) {
  1849. body.append(InstructionFactory.createThis());
  1850. pos++;
  1851. }
  1852. for (int i = 0, len = paramTypes.length; i < len; i++) {
  1853. Type paramType = paramTypes[i];
  1854. body.append(InstructionFactory.createLoad(paramType, pos));
  1855. if (!bridgingSetter.getParameterTypes()[i].getErasureSignature().equals(
  1856. itdfieldSetter.getParameterTypes()[i].getErasureSignature())) {
  1857. body.append(fact.createCast(paramType, bridgingToParms[i]));
  1858. }
  1859. pos += paramType.getSize();
  1860. }
  1861. body.append(Utility.createInvoke(fact, weaver.getWorld(), itdfieldSetter));
  1862. body.append(InstructionFactory.createReturn(returnType));
  1863. gen.addMethodGen(bridgeMethod);
  1864. }
  1865. @Override
  1866. public ConcreteTypeMunger parameterizedFor(ResolvedType target) {
  1867. return new BcelTypeMunger(munger.parameterizedFor(target), aspectType);
  1868. }
  1869. @Override
  1870. public ConcreteTypeMunger parameterizeWith(Map<String, UnresolvedType> m, World w) {
  1871. return new BcelTypeMunger(munger.parameterizeWith(m, w), aspectType);
  1872. }
  1873. /**
  1874. * Returns a list of type variable aliases used in this munger. For example, if the ITD is 'int I&lt;A,B&gt;.m(List&lt;A&gt; las,List&lt;B&gt;
  1875. * lbs) {}' then this returns a list containing the strings "A" and "B".
  1876. */
  1877. public List<String> getTypeVariableAliases() {
  1878. return munger.getTypeVariableAliases();
  1879. }
  1880. @Override
  1881. public boolean equals(Object other) {
  1882. if (!(other instanceof BcelTypeMunger)) {
  1883. return false;
  1884. }
  1885. BcelTypeMunger o = (BcelTypeMunger) other;
  1886. return ((o.getMunger() == null) ? (getMunger() == null) : o.getMunger().equals(getMunger()))
  1887. && ((o.getAspectType() == null) ? (getAspectType() == null) : o.getAspectType().equals(getAspectType()));
  1888. // && (AsmManager.getDefault().getHandleProvider().dependsOnLocation() ? ((o.getSourceLocation() == null) ?
  1889. // (getSourceLocation() == null)
  1890. // : o.getSourceLocation().equals(getSourceLocation()))
  1891. // : true); // pr134471 - remove when handles are improved
  1892. // to be independent of location
  1893. }
  1894. private volatile int hashCode = 0;
  1895. @Override
  1896. public int hashCode() {
  1897. if (hashCode == 0) {
  1898. int result = 17;
  1899. result = 37 * result + ((getMunger() == null) ? 0 : getMunger().hashCode());
  1900. result = 37 * result + ((getAspectType() == null) ? 0 : getAspectType().hashCode());
  1901. hashCode = result;
  1902. }
  1903. return hashCode;
  1904. }
  1905. }