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

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