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

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