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

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