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

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