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

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