Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

BcelClassWeaver.java 131KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373
  1. /* *******************************************************************
  2. * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
  3. * All rights reserved.
  4. * This program and the accompanying materials are made available
  5. * under the terms of the Eclipse Public License v1.0
  6. * which accompanies this distribution and is available at
  7. * http://www.eclipse.org/legal/epl-v10.html
  8. *
  9. * Contributors:
  10. * PARC initial implementation
  11. * ******************************************************************/
  12. package org.aspectj.weaver.bcel;
  13. import java.lang.reflect.Modifier;
  14. import java.util.ArrayList;
  15. import java.util.Collection;
  16. import java.util.Collections;
  17. import java.util.Comparator;
  18. import java.util.HashMap;
  19. import java.util.HashSet;
  20. import java.util.Iterator;
  21. import java.util.LinkedHashSet;
  22. import java.util.List;
  23. import java.util.Map;
  24. import java.util.Properties;
  25. import java.util.Set;
  26. import org.aspectj.apache.bcel.Constants;
  27. import org.aspectj.apache.bcel.classfile.Attribute;
  28. import org.aspectj.apache.bcel.classfile.BootstrapMethods;
  29. import org.aspectj.apache.bcel.classfile.ConstantInvokeDynamic;
  30. import org.aspectj.apache.bcel.classfile.ConstantMethodHandle;
  31. import org.aspectj.apache.bcel.classfile.ConstantMethodref;
  32. import org.aspectj.apache.bcel.classfile.ConstantPool;
  33. import org.aspectj.apache.bcel.classfile.Method;
  34. import org.aspectj.apache.bcel.classfile.annotation.AnnotationGen;
  35. import org.aspectj.apache.bcel.generic.FieldGen;
  36. import org.aspectj.apache.bcel.generic.FieldInstruction;
  37. import org.aspectj.apache.bcel.generic.Instruction;
  38. import org.aspectj.apache.bcel.generic.InstructionBranch;
  39. import org.aspectj.apache.bcel.generic.InstructionCP;
  40. import org.aspectj.apache.bcel.generic.InstructionConstants;
  41. import org.aspectj.apache.bcel.generic.InstructionFactory;
  42. import org.aspectj.apache.bcel.generic.InstructionHandle;
  43. import org.aspectj.apache.bcel.generic.InstructionLV;
  44. import org.aspectj.apache.bcel.generic.InstructionList;
  45. import org.aspectj.apache.bcel.generic.InstructionSelect;
  46. import org.aspectj.apache.bcel.generic.InstructionTargeter;
  47. import org.aspectj.apache.bcel.generic.InvokeDynamic;
  48. import org.aspectj.apache.bcel.generic.InvokeInstruction;
  49. import org.aspectj.apache.bcel.generic.LineNumberTag;
  50. import org.aspectj.apache.bcel.generic.LocalVariableTag;
  51. import org.aspectj.apache.bcel.generic.MULTIANEWARRAY;
  52. import org.aspectj.apache.bcel.generic.MethodGen;
  53. import org.aspectj.apache.bcel.generic.ObjectType;
  54. import org.aspectj.apache.bcel.generic.RET;
  55. import org.aspectj.apache.bcel.generic.Tag;
  56. import org.aspectj.apache.bcel.generic.Type;
  57. import org.aspectj.asm.AsmManager;
  58. import org.aspectj.bridge.IMessage;
  59. import org.aspectj.bridge.ISourceLocation;
  60. import org.aspectj.bridge.Message;
  61. import org.aspectj.bridge.MessageUtil;
  62. import org.aspectj.bridge.WeaveMessage;
  63. import org.aspectj.bridge.context.CompilationAndWeavingContext;
  64. import org.aspectj.bridge.context.ContextToken;
  65. import org.aspectj.util.PartialOrder;
  66. import org.aspectj.weaver.AjAttribute;
  67. import org.aspectj.weaver.AjcMemberMaker;
  68. import org.aspectj.weaver.AnnotationAJ;
  69. import org.aspectj.weaver.BCException;
  70. import org.aspectj.weaver.ConcreteTypeMunger;
  71. import org.aspectj.weaver.IClassWeaver;
  72. import org.aspectj.weaver.IntMap;
  73. import org.aspectj.weaver.Member;
  74. import org.aspectj.weaver.MemberKind;
  75. import org.aspectj.weaver.MissingResolvedTypeWithKnownSignature;
  76. import org.aspectj.weaver.NameMangler;
  77. import org.aspectj.weaver.NewConstructorTypeMunger;
  78. import org.aspectj.weaver.NewFieldTypeMunger;
  79. import org.aspectj.weaver.NewMethodTypeMunger;
  80. import org.aspectj.weaver.ResolvedMember;
  81. import org.aspectj.weaver.ResolvedMemberImpl;
  82. import org.aspectj.weaver.ResolvedType;
  83. import org.aspectj.weaver.ResolvedTypeMunger;
  84. import org.aspectj.weaver.Shadow;
  85. import org.aspectj.weaver.ShadowMunger;
  86. import org.aspectj.weaver.UnresolvedType;
  87. import org.aspectj.weaver.UnresolvedTypeVariableReferenceType;
  88. import org.aspectj.weaver.WeaverStateInfo;
  89. import org.aspectj.weaver.World;
  90. import org.aspectj.weaver.model.AsmRelationshipProvider;
  91. import org.aspectj.weaver.patterns.DeclareAnnotation;
  92. import org.aspectj.weaver.patterns.ExactTypePattern;
  93. import org.aspectj.weaver.tools.Trace;
  94. import org.aspectj.weaver.tools.TraceFactory;
  95. class BcelClassWeaver implements IClassWeaver {
  96. private static Trace trace = TraceFactory.getTraceFactory().getTrace(BcelClassWeaver.class);
  97. public static boolean weave(BcelWorld world, LazyClassGen clazz, List<ShadowMunger> shadowMungers,
  98. List<ConcreteTypeMunger> typeMungers, List<ConcreteTypeMunger> lateTypeMungers, boolean inReweavableMode) {
  99. BcelClassWeaver classWeaver = new BcelClassWeaver(world, clazz, shadowMungers, typeMungers, lateTypeMungers);
  100. classWeaver.setReweavableMode(inReweavableMode);
  101. boolean b = classWeaver.weave();
  102. return b;
  103. }
  104. // --------------------------------------------
  105. private final LazyClassGen clazz;
  106. private final List<ShadowMunger> shadowMungers;
  107. private final List<ConcreteTypeMunger> typeMungers;
  108. private final List<ConcreteTypeMunger> lateTypeMungers;
  109. private List<ShadowMunger>[] indexedShadowMungers;
  110. private boolean canMatchBodyShadows = false;
  111. private final BcelObjectType ty; // alias of clazz.getType()
  112. private final BcelWorld world; // alias of ty.getWorld()
  113. private final ConstantPool cpg; // alias of clazz.getConstantPoolGen()
  114. private final InstructionFactory fact; // alias of clazz.getFactory();
  115. private final List<LazyMethodGen> addedLazyMethodGens = new ArrayList<LazyMethodGen>();
  116. private final Set<ResolvedMember> addedDispatchTargets = new HashSet<ResolvedMember>();
  117. private boolean inReweavableMode = false;
  118. private List<IfaceInitList> addedSuperInitializersAsList = null;
  119. private final Map<ResolvedType, IfaceInitList> addedSuperInitializers = new HashMap<ResolvedType, IfaceInitList>();
  120. private final List<ConcreteTypeMunger> addedThisInitializers = new ArrayList<ConcreteTypeMunger>();
  121. private final List<ConcreteTypeMunger> addedClassInitializers = new ArrayList<ConcreteTypeMunger>();
  122. private final Map<ResolvedMember, ResolvedMember> mapToAnnotationHolder = new HashMap<ResolvedMember, ResolvedMember>();
  123. // private BcelShadow clinitShadow = null;
  124. /**
  125. * This holds the initialization and pre-initialization shadows for this class that were actually matched by mungers (if no
  126. * match, then we don't even create the shadows really).
  127. */
  128. private final List<BcelShadow> initializationShadows = new ArrayList<BcelShadow>();
  129. private BcelClassWeaver(BcelWorld world, LazyClassGen clazz, List<ShadowMunger> shadowMungers,
  130. List<ConcreteTypeMunger> typeMungers, List<ConcreteTypeMunger> lateTypeMungers) {
  131. super();
  132. this.world = world;
  133. this.clazz = clazz;
  134. this.shadowMungers = shadowMungers;
  135. this.typeMungers = typeMungers;
  136. this.lateTypeMungers = lateTypeMungers;
  137. this.ty = clazz.getBcelObjectType();
  138. this.cpg = clazz.getConstantPool();
  139. this.fact = clazz.getFactory();
  140. indexShadowMungers();
  141. initializeSuperInitializerMap(ty.getResolvedTypeX());
  142. if (!checkedXsetForLowLevelContextCapturing) {
  143. Properties p = world.getExtraConfiguration();
  144. if (p != null) {
  145. String s = p.getProperty(World.xsetCAPTURE_ALL_CONTEXT, "false");
  146. captureLowLevelContext = s.equalsIgnoreCase("true");
  147. if (captureLowLevelContext) {
  148. world.getMessageHandler().handleMessage(
  149. MessageUtil.info("[" + World.xsetCAPTURE_ALL_CONTEXT
  150. + "=true] Enabling collection of low level context for debug/crash messages"));
  151. }
  152. }
  153. checkedXsetForLowLevelContextCapturing = true;
  154. }
  155. }
  156. private boolean canMatch(Shadow.Kind kind) {
  157. return indexedShadowMungers[kind.getKey()] != null;
  158. }
  159. // private void fastMatchShadowMungers(List shadowMungers, ArrayList
  160. // mungers, Kind kind) {
  161. // FastMatchInfo info = new FastMatchInfo(clazz.getType(), kind);
  162. // for (Iterator i = shadowMungers.iterator(); i.hasNext();) {
  163. // ShadowMunger munger = (ShadowMunger) i.next();
  164. // FuzzyBoolean fb = munger.getPointcut().fastMatch(info);
  165. // WeaverMetrics.recordFastMatchResult(fb);// Could pass:
  166. // munger.getPointcut().toString()
  167. // if (fb.maybeTrue()) mungers.add(munger);
  168. // }
  169. // }
  170. private void initializeSuperInitializerMap(ResolvedType child) {
  171. ResolvedType[] superInterfaces = child.getDeclaredInterfaces();
  172. for (int i = 0, len = superInterfaces.length; i < len; i++) {
  173. if (ty.getResolvedTypeX().isTopmostImplementor(superInterfaces[i])) {
  174. if (addSuperInitializer(superInterfaces[i])) {
  175. initializeSuperInitializerMap(superInterfaces[i]);
  176. }
  177. }
  178. }
  179. }
  180. /**
  181. * Process the shadow mungers into array 'buckets', each bucket represents a shadow kind and contains a list of shadowmungers
  182. * that could potentially apply at that shadow kind.
  183. */
  184. private void indexShadowMungers() {
  185. // beware the annoying property that SHADOW_KINDS[i].getKey == (i+1) !
  186. indexedShadowMungers = new List[Shadow.MAX_SHADOW_KIND + 1];
  187. for (ShadowMunger shadowMunger : shadowMungers) {
  188. int couldMatchKinds = shadowMunger.getPointcut().couldMatchKinds();
  189. for (Shadow.Kind kind : Shadow.SHADOW_KINDS) {
  190. if (kind.isSet(couldMatchKinds)) {
  191. byte k = kind.getKey();
  192. if (indexedShadowMungers[k] == null) {
  193. indexedShadowMungers[k] = new ArrayList<ShadowMunger>();
  194. if (!kind.isEnclosingKind()) {
  195. canMatchBodyShadows = true;
  196. }
  197. }
  198. indexedShadowMungers[k].add(shadowMunger);
  199. }
  200. }
  201. }
  202. }
  203. private boolean addSuperInitializer(ResolvedType onType) {
  204. if (onType.isRawType() || onType.isParameterizedType()) {
  205. onType = onType.getGenericType();
  206. }
  207. IfaceInitList l = addedSuperInitializers.get(onType);
  208. if (l != null) {
  209. return false;
  210. }
  211. l = new IfaceInitList(onType);
  212. addedSuperInitializers.put(onType, l);
  213. return true;
  214. }
  215. public void addInitializer(ConcreteTypeMunger cm) {
  216. NewFieldTypeMunger m = (NewFieldTypeMunger) cm.getMunger();
  217. ResolvedType onType = m.getSignature().getDeclaringType().resolve(world);
  218. if (onType.isRawType()) {
  219. onType = onType.getGenericType();
  220. }
  221. if (Modifier.isStatic(m.getSignature().getModifiers())) {
  222. addedClassInitializers.add(cm);
  223. } else {
  224. if (onType == ty.getResolvedTypeX()) {
  225. addedThisInitializers.add(cm);
  226. } else {
  227. IfaceInitList l = addedSuperInitializers.get(onType);
  228. l.list.add(cm);
  229. }
  230. }
  231. }
  232. private static class IfaceInitList implements PartialOrder.PartialComparable {
  233. final ResolvedType onType;
  234. List<ConcreteTypeMunger> list = new ArrayList<ConcreteTypeMunger>();
  235. IfaceInitList(ResolvedType onType) {
  236. this.onType = onType;
  237. }
  238. public int compareTo(Object other) {
  239. IfaceInitList o = (IfaceInitList) other;
  240. if (onType.isAssignableFrom(o.onType)) {
  241. return +1;
  242. } else if (o.onType.isAssignableFrom(onType)) {
  243. return -1;
  244. } else {
  245. return 0;
  246. }
  247. }
  248. public int fallbackCompareTo(Object other) {
  249. return 0;
  250. }
  251. }
  252. // XXX this is being called, but the result doesn't seem to be being used
  253. public boolean addDispatchTarget(ResolvedMember m) {
  254. return addedDispatchTargets.add(m);
  255. }
  256. public void addLazyMethodGen(LazyMethodGen gen) {
  257. addedLazyMethodGens.add(gen);
  258. }
  259. public void addOrReplaceLazyMethodGen(LazyMethodGen mg) {
  260. if (alreadyDefined(clazz, mg)) {
  261. return;
  262. }
  263. for (Iterator<LazyMethodGen> i = addedLazyMethodGens.iterator(); i.hasNext();) {
  264. LazyMethodGen existing = i.next();
  265. if (signaturesMatch(mg, existing)) {
  266. if (existing.definingType == null) {
  267. // this means existing was introduced on the class itself
  268. return;
  269. } else if (mg.definingType.isAssignableFrom(existing.definingType)) {
  270. // existing is mg's subtype and dominates mg
  271. return;
  272. } else if (existing.definingType.isAssignableFrom(mg.definingType)) {
  273. // mg is existing's subtype and dominates existing
  274. i.remove();
  275. addedLazyMethodGens.add(mg);
  276. return;
  277. } else {
  278. throw new BCException("conflict between: " + mg + " and " + existing);
  279. }
  280. }
  281. }
  282. addedLazyMethodGens.add(mg);
  283. }
  284. private boolean alreadyDefined(LazyClassGen clazz, LazyMethodGen mg) {
  285. for (Iterator<LazyMethodGen> i = clazz.getMethodGens().iterator(); i.hasNext();) {
  286. LazyMethodGen existing = i.next();
  287. if (signaturesMatch(mg, existing)) {
  288. if (!mg.isAbstract() && existing.isAbstract()) {
  289. i.remove();
  290. return false;
  291. }
  292. return true;
  293. }
  294. }
  295. return false;
  296. }
  297. private boolean signaturesMatch(LazyMethodGen mg, LazyMethodGen existing) {
  298. return mg.getName().equals(existing.getName()) && mg.getSignature().equals(existing.getSignature());
  299. }
  300. protected static LazyMethodGen makeBridgeMethod(LazyClassGen gen, ResolvedMember member) {
  301. // remove abstract modifier
  302. int mods = member.getModifiers();
  303. if (Modifier.isAbstract(mods)) {
  304. mods = mods - Modifier.ABSTRACT;
  305. }
  306. LazyMethodGen ret = new LazyMethodGen(mods, BcelWorld.makeBcelType(member.getReturnType()), member.getName(),
  307. BcelWorld.makeBcelTypes(member.getParameterTypes()), UnresolvedType.getNames(member.getExceptions()), gen);
  308. // 43972 : Static crosscutting makes interfaces unusable for javac
  309. // ret.makeSynthetic();
  310. return ret;
  311. }
  312. /**
  313. * Create a single bridge method called 'theBridgeMethod' that bridges to 'whatToBridgeTo'
  314. */
  315. private static void createBridgeMethod(BcelWorld world, LazyMethodGen whatToBridgeToMethodGen, LazyClassGen clazz, ResolvedMember theBridgeMethod) {
  316. InstructionList body;
  317. InstructionFactory fact;
  318. int pos = 0;
  319. ResolvedMember whatToBridgeTo = whatToBridgeToMethodGen.getMemberView();
  320. if (whatToBridgeTo == null) {
  321. whatToBridgeTo = new ResolvedMemberImpl(Member.METHOD, whatToBridgeToMethodGen.getEnclosingClass().getType(),
  322. whatToBridgeToMethodGen.getAccessFlags(), whatToBridgeToMethodGen.getName(),
  323. whatToBridgeToMethodGen.getSignature());
  324. }
  325. // The bridge method in this type will have the same signature as the one in the supertype
  326. LazyMethodGen bridgeMethod = makeBridgeMethod(clazz, theBridgeMethod);
  327. int newflags = bridgeMethod.getAccessFlags() | 0x00000040;// BRIDGE = 0x00000040
  328. if ((newflags & 0x00000100) != 0) {
  329. newflags = newflags - 0x100;// NATIVE = 0x00000100 - need to clear it
  330. }
  331. bridgeMethod.setAccessFlags(newflags);
  332. Type returnType = BcelWorld.makeBcelType(theBridgeMethod.getReturnType());
  333. Type[] paramTypes = BcelWorld.makeBcelTypes(theBridgeMethod.getParameterTypes());
  334. Type[] newParamTypes = whatToBridgeToMethodGen.getArgumentTypes();
  335. body = bridgeMethod.getBody();
  336. fact = clazz.getFactory();
  337. if (!whatToBridgeToMethodGen.isStatic()) {
  338. body.append(InstructionFactory.createThis());
  339. pos++;
  340. }
  341. for (int i = 0, len = paramTypes.length; i < len; i++) {
  342. Type paramType = paramTypes[i];
  343. body.append(InstructionFactory.createLoad(paramType, pos));
  344. if (!newParamTypes[i].equals(paramTypes[i])) {
  345. if (world.forDEBUG_bridgingCode) {
  346. System.err.println("Bridging: Cast " + newParamTypes[i] + " from " + paramTypes[i]);
  347. }
  348. body.append(fact.createCast(paramTypes[i], newParamTypes[i]));
  349. }
  350. pos += paramType.getSize();
  351. }
  352. body.append(Utility.createInvoke(fact, world, whatToBridgeTo));
  353. body.append(InstructionFactory.createReturn(returnType));
  354. clazz.addMethodGen(bridgeMethod);
  355. }
  356. /**
  357. * Weave a class and indicate through the return value whether the class was modified.
  358. *
  359. * @return true if the class was modified
  360. */
  361. public boolean weave() {
  362. if (clazz.isWoven() && !clazz.isReweavable()) {
  363. if (world.getLint().nonReweavableTypeEncountered.isEnabled()) {
  364. world.getLint().nonReweavableTypeEncountered.signal(clazz.getType().getName(), ty.getSourceLocation());
  365. }
  366. // Integer uniqueID = new Integer(rm.hashCode() * deca.hashCode());
  367. // if (!reportedProblems.contains(uniqueID)) {
  368. // reportedProblems.add(uniqueID);
  369. // world.getLint().elementAlreadyAnnotated.signal(new String[] { rm.toString(),
  370. // world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ALREADY_WOVEN, clazz.getType().getName()),
  371. // ty.getSourceLocation(), null);
  372. return false;
  373. }
  374. Set<String> aspectsAffectingType = null;
  375. if (inReweavableMode || clazz.getType().isAspect()) {
  376. aspectsAffectingType = new HashSet<String>();
  377. }
  378. boolean isChanged = false;
  379. // we want to "touch" all aspects
  380. if (clazz.getType().isAspect()) {
  381. isChanged = true;
  382. }
  383. WeaverStateInfo typeWeaverState = (world.isOverWeaving() ? getLazyClassGen().getType().getWeaverState() : null);
  384. // start by munging all typeMungers
  385. for (ConcreteTypeMunger o : typeMungers) {
  386. if (!(o instanceof BcelTypeMunger)) {
  387. // ???System.err.println("surprising: " + o);
  388. continue;
  389. }
  390. BcelTypeMunger munger = (BcelTypeMunger) o;
  391. if (typeWeaverState != null && typeWeaverState.isAspectAlreadyApplied(munger.getAspectType())) {
  392. continue;
  393. }
  394. boolean typeMungerAffectedType = munger.munge(this);
  395. if (typeMungerAffectedType) {
  396. isChanged = true;
  397. if (inReweavableMode || clazz.getType().isAspect()) {
  398. aspectsAffectingType.add(munger.getAspectType().getSignature());
  399. }
  400. }
  401. }
  402. // Weave special half type/half shadow mungers...
  403. isChanged = weaveDeclareAtMethodCtor(clazz) || isChanged;
  404. isChanged = weaveDeclareAtField(clazz) || isChanged;
  405. // XXX do major sort of stuff
  406. // sort according to: Major: type hierarchy
  407. // within each list: dominates
  408. // don't forget to sort addedThisInitialiers according to dominates
  409. addedSuperInitializersAsList = new ArrayList<IfaceInitList>(addedSuperInitializers.values());
  410. addedSuperInitializersAsList = PartialOrder.sort(addedSuperInitializersAsList);
  411. if (addedSuperInitializersAsList == null) {
  412. throw new BCException("circularity in inter-types");
  413. }
  414. // this will create a static initializer if there isn't one
  415. // this is in just as bad taste as NOPs
  416. LazyMethodGen staticInit = clazz.getStaticInitializer();
  417. staticInit.getBody().insert(genInitInstructions(addedClassInitializers, true));
  418. // now go through each method, and match against each method. This
  419. // sets up each method's {@link LazyMethodGen#matchedShadows} field,
  420. // and it also possibly adds to {@link #initializationShadows}.
  421. List<LazyMethodGen> methodGens = new ArrayList<LazyMethodGen>(clazz.getMethodGens());
  422. for (LazyMethodGen member : methodGens) {
  423. if (!member.hasBody()) {
  424. continue;
  425. }
  426. if (world.isJoinpointSynchronizationEnabled() && world.areSynchronizationPointcutsInUse()
  427. && member.getMethod().isSynchronized()) {
  428. transformSynchronizedMethod(member);
  429. }
  430. boolean shadowMungerMatched = match(member);
  431. if (shadowMungerMatched) {
  432. // For matching mungers, add their declaring aspects to the list
  433. // that affected this type
  434. if (inReweavableMode || clazz.getType().isAspect()) {
  435. aspectsAffectingType.addAll(findAspectsForMungers(member));
  436. }
  437. isChanged = true;
  438. }
  439. }
  440. // now we weave all but the initialization shadows
  441. for (LazyMethodGen methodGen : methodGens) {
  442. if (!methodGen.hasBody()) {
  443. continue;
  444. }
  445. implement(methodGen);
  446. }
  447. // if we matched any initialization shadows, we inline and weave
  448. if (!initializationShadows.isEmpty()) {
  449. // Repeat next step until nothing left to inline...cant go on
  450. // infinetly as compiler will have detected and reported
  451. // "Recursive constructor invocation"
  452. List<LazyMethodGen> recursiveCtors = new ArrayList<LazyMethodGen>();
  453. while (inlineSelfConstructors(methodGens, recursiveCtors)) {
  454. }
  455. positionAndImplement(initializationShadows);
  456. }
  457. // now proceed with late type mungers
  458. if (lateTypeMungers != null) {
  459. for (Iterator<ConcreteTypeMunger> i = lateTypeMungers.iterator(); i.hasNext();) {
  460. BcelTypeMunger munger = (BcelTypeMunger) i.next();
  461. if (munger.matches(clazz.getType())) {
  462. boolean typeMungerAffectedType = munger.munge(this);
  463. if (typeMungerAffectedType) {
  464. isChanged = true;
  465. if (inReweavableMode || clazz.getType().isAspect()) {
  466. aspectsAffectingType.add(munger.getAspectType().getSignature());
  467. }
  468. }
  469. }
  470. }
  471. }
  472. // FIXME AV - see #75442, for now this is not enough to fix the bug,
  473. // comment that out until we really fix it
  474. // // flush to save some memory
  475. // PerObjectInterfaceTypeMunger.unregisterFromAsAdvisedBy(clazz.getType()
  476. // );
  477. // finally, if we changed, we add in the introduced methods.
  478. if (isChanged) {
  479. clazz.getOrCreateWeaverStateInfo(inReweavableMode);
  480. weaveInAddedMethods();
  481. }
  482. if (inReweavableMode) {
  483. WeaverStateInfo wsi = clazz.getOrCreateWeaverStateInfo(true);
  484. wsi.addAspectsAffectingType(aspectsAffectingType);
  485. wsi.setUnwovenClassFileData(ty.getJavaClass().getBytes());
  486. wsi.setReweavable(true);
  487. } else {
  488. clazz.getOrCreateWeaverStateInfo(false).setReweavable(false);
  489. }
  490. // tidyup, reduce ongoing memory usage of BcelMethods that hang around
  491. for (LazyMethodGen mg : methodGens) {
  492. BcelMethod method = mg.getMemberView();
  493. if (method != null) {
  494. method.wipeJoinpointSignatures();
  495. }
  496. }
  497. return isChanged;
  498. }
  499. // **************************** start of bridge method creation code
  500. // *****************
  501. // FIXASC tidy this lot up !!
  502. // FIXASC refactor into ResolvedType or even ResolvedMember?
  503. /**
  504. * Check if a particular method is overriding another - refactored into this helper so it can be used from multiple places.
  505. * @return method that is overriding if it
  506. */
  507. private static ResolvedMember isOverriding(ResolvedType typeToCheck, ResolvedMember methodThatMightBeGettingOverridden,
  508. String mname, String mrettype, int mmods, boolean inSamePackage, UnresolvedType[] methodParamsArray) {
  509. // Check if we can be an override...
  510. if (Modifier.isStatic(methodThatMightBeGettingOverridden.getModifiers())) {
  511. // we can't be overriding a static method
  512. return null;
  513. }
  514. if (Modifier.isPrivate(methodThatMightBeGettingOverridden.getModifiers())) {
  515. // we can't be overriding a private method
  516. return null;
  517. }
  518. if (!methodThatMightBeGettingOverridden.getName().equals(mname)) {
  519. // names do not match (this will also skip <init> and <clinit>)
  520. return null;
  521. }
  522. if (methodThatMightBeGettingOverridden.getParameterTypes().length != methodParamsArray.length) {
  523. // not the same number of parameters
  524. return null;
  525. }
  526. if (!isVisibilityOverride(mmods, methodThatMightBeGettingOverridden, inSamePackage)) {
  527. // not override from visibility point of view
  528. return null;
  529. }
  530. if (typeToCheck.getWorld().forDEBUG_bridgingCode) {
  531. System.err.println(" Bridging:seriously considering this might be getting overridden '"
  532. + methodThatMightBeGettingOverridden + "'");
  533. }
  534. World w = typeToCheck.getWorld();
  535. // Look at erasures of parameters (List<String> erased is List)
  536. boolean sameParams = true;
  537. for (int p = 0, max = methodThatMightBeGettingOverridden.getParameterTypes().length; p < max; p++) {
  538. UnresolvedType mtmbgoParameter = methodThatMightBeGettingOverridden.getParameterTypes()[p];
  539. UnresolvedType ptype = methodParamsArray[p];
  540. if (mtmbgoParameter.isTypeVariableReference()) {
  541. if (!mtmbgoParameter.resolve(w).isAssignableFrom(ptype.resolve(w))) {
  542. sameParams = false;
  543. }
  544. } else {
  545. // old condition:
  546. boolean b = !methodThatMightBeGettingOverridden.getParameterTypes()[p].getErasureSignature().equals(
  547. methodParamsArray[p].getErasureSignature());
  548. UnresolvedType parameterType = methodThatMightBeGettingOverridden.getParameterTypes()[p];
  549. // Collapse to first bound (isn't that the same as erasure!
  550. if (parameterType instanceof UnresolvedTypeVariableReferenceType) {
  551. parameterType = ((UnresolvedTypeVariableReferenceType) parameterType).getTypeVariable().getFirstBound();
  552. }
  553. if (b) { // !parameterType.resolve(w).equals(parameterType2.resolve(w))) {
  554. sameParams = false;
  555. }
  556. }
  557. //
  558. // if (!ut.getErasureSignature().equals(ut2.getErasureSignature()))
  559. // sameParams = false;
  560. }
  561. // If the 'typeToCheck' represents a parameterized type then the method
  562. // will be the parameterized form of the
  563. // generic method in the generic type. So if the method was 'void
  564. // m(List<T> lt, T t)' and the parameterized type here
  565. // is I<String> then the method we are looking at will be 'void
  566. // m(List<String> lt, String t)' which when erased
  567. // is 'void m(List lt,String t)' - so if the parameters *do* match then
  568. // there is a generic method we are
  569. // overriding
  570. // FIXASC Why bother with the return type? If it is incompatible then the code has other problems!
  571. if (sameParams) {
  572. if (typeToCheck.isParameterizedType()) {
  573. return methodThatMightBeGettingOverridden.getBackingGenericMember();
  574. } else if (!methodThatMightBeGettingOverridden.getReturnType().getErasureSignature().equals(mrettype)) {
  575. // addressing the wierd situation from bug 147801
  576. // just check whether these things are in the right relationship
  577. // for covariance...
  578. ResolvedType superReturn = typeToCheck.getWorld().resolve(
  579. UnresolvedType.forSignature(methodThatMightBeGettingOverridden.getReturnType().getErasureSignature()));
  580. ResolvedType subReturn = typeToCheck.getWorld().resolve(UnresolvedType.forSignature(mrettype));
  581. if (superReturn.isAssignableFrom(subReturn)) {
  582. return methodThatMightBeGettingOverridden;
  583. }
  584. // } else if (typeToCheck.isParameterizedType()) {
  585. // return methodThatMightBeGettingOverridden.getBackingGenericMember();
  586. } else {
  587. return methodThatMightBeGettingOverridden;
  588. }
  589. }
  590. return null;
  591. }
  592. /**
  593. * Looks at the visibility modifiers between two methods, and knows whether they are from classes in the same package, and
  594. * decides whether one overrides the other.
  595. *
  596. * @return true if there is an overrides rather than a 'hides' relationship
  597. */
  598. static boolean isVisibilityOverride(int methodMods, ResolvedMember inheritedMethod, boolean inSamePackage) {
  599. int inheritedModifiers = inheritedMethod.getModifiers();
  600. if (Modifier.isStatic(inheritedModifiers)) {
  601. return false;
  602. }
  603. if (methodMods == inheritedModifiers) {
  604. return true;
  605. }
  606. if (Modifier.isPrivate(inheritedModifiers)) {
  607. return false;
  608. }
  609. boolean isPackageVisible = !Modifier.isPrivate(inheritedModifiers) && !Modifier.isProtected(inheritedModifiers)
  610. && !Modifier.isPublic(inheritedModifiers);
  611. if (isPackageVisible && !inSamePackage) {
  612. return false;
  613. }
  614. return true;
  615. }
  616. /**
  617. * This method recurses up a specified type looking for a method that overrides the one passed in.
  618. *
  619. * @return the method being overridden or null if none is found
  620. */
  621. public static void checkForOverride(ResolvedType typeToCheck, String mname, String mparams, String mrettype,
  622. int mmods, String mpkg, UnresolvedType[] methodParamsArray, List<ResolvedMember> overriddenMethodsCollector) {
  623. if (typeToCheck == null) {
  624. return;
  625. }
  626. if (typeToCheck instanceof MissingResolvedTypeWithKnownSignature) {
  627. return; // we just can't tell !
  628. }
  629. if (typeToCheck.getWorld().forDEBUG_bridgingCode) {
  630. System.err.println(" Bridging:checking for override of " + mname + " in " + typeToCheck);
  631. }
  632. String packageName = typeToCheck.getPackageName();
  633. if (packageName == null) {
  634. packageName = "";
  635. }
  636. // used when looking at visibility rules
  637. boolean inSamePackage = packageName.equals(mpkg);
  638. ResolvedMember[] methods = typeToCheck.getDeclaredMethods();
  639. for (int ii = 0; ii < methods.length; ii++) {
  640. // the method we are going to check
  641. ResolvedMember methodThatMightBeGettingOverridden = methods[ii];
  642. ResolvedMember isOverriding = isOverriding(typeToCheck, methodThatMightBeGettingOverridden, mname, mrettype, mmods,
  643. inSamePackage, methodParamsArray);
  644. if (isOverriding != null) {
  645. overriddenMethodsCollector.add(isOverriding);
  646. }
  647. }
  648. // was: List l = typeToCheck.getInterTypeMungers();
  649. List<ConcreteTypeMunger> l = (typeToCheck.isRawType() ? typeToCheck.getGenericType().getInterTypeMungers() : typeToCheck
  650. .getInterTypeMungers());
  651. for (Iterator<ConcreteTypeMunger> iterator = l.iterator(); iterator.hasNext();) {
  652. ConcreteTypeMunger o = iterator.next();
  653. // FIXME asc if its not a BcelTypeMunger then its an
  654. // EclipseTypeMunger ... do I need to worry about that?
  655. if (o instanceof BcelTypeMunger) {
  656. BcelTypeMunger element = (BcelTypeMunger) o;
  657. if (element.getMunger() instanceof NewMethodTypeMunger) {
  658. if (typeToCheck.getWorld().forDEBUG_bridgingCode) {
  659. System.err.println("Possible ITD candidate " + element);
  660. }
  661. ResolvedMember aMethod = element.getSignature();
  662. ResolvedMember isOverriding = isOverriding(typeToCheck, aMethod, mname, mrettype, mmods, inSamePackage,
  663. methodParamsArray);
  664. if (isOverriding != null) {
  665. overriddenMethodsCollector.add(isOverriding);
  666. }
  667. }
  668. }
  669. }
  670. if (typeToCheck.equals(UnresolvedType.OBJECT)) {
  671. return;
  672. }
  673. ResolvedType superclass = typeToCheck.getSuperclass();
  674. checkForOverride(superclass, mname, mparams, mrettype, mmods, mpkg, methodParamsArray,overriddenMethodsCollector);
  675. ResolvedType[] interfaces = typeToCheck.getDeclaredInterfaces();
  676. for (int i = 0; i < interfaces.length; i++) {
  677. ResolvedType anInterface = interfaces[i];
  678. checkForOverride(anInterface, mname, mparams, mrettype, mmods, mpkg, methodParamsArray,overriddenMethodsCollector);
  679. }
  680. }
  681. /**
  682. * We need to determine if any methods in this type require bridge methods - this method should only be called if necessary to
  683. * do this calculation, i.e. we are on a 1.5 VM (where covariance/generics exist) and the type hierarchy for the specified class
  684. * has changed (via decp/itd).
  685. *
  686. * See pr108101
  687. */
  688. public static boolean calculateAnyRequiredBridgeMethods(BcelWorld world, LazyClassGen clazz) {
  689. world.ensureAdvancedConfigurationProcessed();
  690. if (!world.isInJava5Mode()) {
  691. return false; // just double check... the caller should have already
  692. }
  693. if (clazz.isInterface()) {
  694. return false; // dont bother if we are an interface
  695. }
  696. boolean didSomething = false; // set if we build any bridge methods
  697. // So what methods do we have right now in this class?
  698. List<LazyMethodGen> methods = clazz.getMethodGens();
  699. // Keep a set of all methods from this type - it'll help us to check if bridge methods
  700. // have already been created, we don't want to do it twice!
  701. Set<String> methodsSet = new HashSet<String>();
  702. for (int i = 0; i < methods.size(); i++) {
  703. LazyMethodGen aMethod = methods.get(i);
  704. StringBuilder sb = new StringBuilder(aMethod.getName());
  705. sb.append(aMethod.getSignature());
  706. methodsSet.add(sb.toString()); // e.g. "foo(Ljava/lang/String;)V"
  707. }
  708. // Now go through all the methods in this type
  709. for (int i = 0; i < methods.size(); i++) {
  710. // This is the local method that we *might* have to bridge to
  711. LazyMethodGen bridgeToCandidate = methods.get(i);
  712. if (bridgeToCandidate.isBridgeMethod()) {
  713. continue; // Doh!
  714. }
  715. String name = bridgeToCandidate.getName();
  716. String psig = bridgeToCandidate.getParameterSignature();
  717. String rsig = bridgeToCandidate.getReturnType().getSignature();
  718. // if (bridgeToCandidate.isAbstract()) continue;
  719. if (bridgeToCandidate.isStatic()) {
  720. continue; // ignore static methods
  721. }
  722. if (name.endsWith("init>")) {
  723. continue; // Skip constructors and static initializers
  724. }
  725. if (world.forDEBUG_bridgingCode) {
  726. System.err.println("Bridging: Determining if we have to bridge to " + clazz.getName() + "." + name + "" + bridgeToCandidate.getSignature());
  727. }
  728. // Let's take a look at the superclass
  729. ResolvedType theSuperclass = clazz.getSuperClass();
  730. if (world.forDEBUG_bridgingCode) {
  731. System.err.println("Bridging: Checking supertype " + theSuperclass);
  732. }
  733. String pkgName = clazz.getPackageName();
  734. UnresolvedType[] bm = BcelWorld.fromBcel(bridgeToCandidate.getArgumentTypes());
  735. List<ResolvedMember> overriddenMethodsCollector = new ArrayList<ResolvedMember>();
  736. checkForOverride(theSuperclass, name, psig, rsig, bridgeToCandidate.getAccessFlags(), pkgName, bm, overriddenMethodsCollector);
  737. if (overriddenMethodsCollector.size() != 0) {
  738. for (ResolvedMember overriddenMethod: overriddenMethodsCollector) {
  739. String key = new StringBuilder(overriddenMethod.getName()).append(overriddenMethod.getSignatureErased()).toString(); // pr237419
  740. boolean alreadyHaveABridgeMethod = methodsSet.contains(key);
  741. if (!alreadyHaveABridgeMethod) {
  742. if (world.forDEBUG_bridgingCode) {
  743. System.err.println("Bridging:bridging to '" + overriddenMethod + "'");
  744. }
  745. createBridgeMethod(world, bridgeToCandidate, clazz, overriddenMethod);
  746. methodsSet.add(key);
  747. didSomething = true;
  748. }
  749. }
  750. }
  751. // Check superinterfaces
  752. String[] interfaces = clazz.getInterfaceNames();
  753. for (int j = 0; j < interfaces.length; j++) {
  754. if (world.forDEBUG_bridgingCode) {
  755. System.err.println("Bridging:checking superinterface " + interfaces[j]);
  756. }
  757. ResolvedType interfaceType = world.resolve(interfaces[j]);
  758. overriddenMethodsCollector.clear();
  759. checkForOverride(interfaceType, name, psig, rsig, bridgeToCandidate.getAccessFlags(),
  760. clazz.getPackageName(), bm, overriddenMethodsCollector);
  761. for (ResolvedMember overriddenMethod: overriddenMethodsCollector) {
  762. String key = new StringBuffer().append(overriddenMethod.getName()).append(overriddenMethod.getSignatureErased()).toString(); // pr237419
  763. boolean alreadyHaveABridgeMethod = methodsSet.contains(key);
  764. if (!alreadyHaveABridgeMethod) {
  765. createBridgeMethod(world, bridgeToCandidate, clazz, overriddenMethod);
  766. methodsSet.add(key);
  767. didSomething = true;
  768. if (world.forDEBUG_bridgingCode) {
  769. System.err.println("Bridging:bridging to " + overriddenMethod);
  770. }
  771. }
  772. }
  773. }
  774. }
  775. return didSomething;
  776. }
  777. // **************************** end of bridge method creation code *****************
  778. /**
  779. * Weave any declare @method/@ctor statements into the members of the supplied class
  780. */
  781. private boolean weaveDeclareAtMethodCtor(LazyClassGen clazz) {
  782. List<Integer> reportedProblems = new ArrayList<Integer>();
  783. List<DeclareAnnotation> allDecams = world.getDeclareAnnotationOnMethods();
  784. if (allDecams.isEmpty()) {
  785. return false;
  786. }
  787. boolean isChanged = false;
  788. // deal with ITDs
  789. List<ConcreteTypeMunger> itdMethodsCtors = getITDSubset(clazz, ResolvedTypeMunger.Method);
  790. itdMethodsCtors.addAll(getITDSubset(clazz, ResolvedTypeMunger.Constructor));
  791. if (!itdMethodsCtors.isEmpty()) {
  792. // Can't use the subset called 'decaMs' as it won't be right for
  793. // ITDs...
  794. isChanged = weaveAtMethodOnITDSRepeatedly(allDecams, itdMethodsCtors, reportedProblems);
  795. }
  796. List<DeclareAnnotation> decaMs = getMatchingSubset(allDecams, clazz.getType());
  797. if (decaMs.isEmpty()) {
  798. return false; // nothing to do
  799. }
  800. Set<DeclareAnnotation> unusedDecams = new HashSet<DeclareAnnotation>();
  801. unusedDecams.addAll(decaMs);
  802. // These methods may have been targeted with declare annotation. Example: ITD on an interface
  803. // where the top most implementor gets a real method. The top most implementor method
  804. // is an 'addedLazyMethodGen'
  805. if (addedLazyMethodGens!=null) {
  806. for (LazyMethodGen method: addedLazyMethodGens) {
  807. // They have no resolvedmember of their own, conjure one up for matching purposes
  808. ResolvedMember resolvedmember =
  809. new ResolvedMemberImpl(ResolvedMember.METHOD,method.getEnclosingClass().getType(),method.getAccessFlags(),
  810. BcelWorld.fromBcel(method.getReturnType()),method.getName(),
  811. BcelWorld.fromBcel(method.getArgumentTypes()),UnresolvedType.forNames(method.getDeclaredExceptions()));
  812. resolvedmember.setAnnotationTypes(method.getAnnotationTypes());
  813. resolvedmember.setAnnotations(method.getAnnotations());
  814. List<DeclareAnnotation> worthRetrying = new ArrayList<DeclareAnnotation>();
  815. boolean modificationOccured = false;
  816. for (DeclareAnnotation decam: decaMs) {
  817. if (decam.matches(resolvedmember, world)) {
  818. if (doesAlreadyHaveAnnotation(resolvedmember, decam, reportedProblems,false)) {
  819. // remove the declare @method since don't want an error when the annotation is already there
  820. unusedDecams.remove(decam);
  821. continue;
  822. }
  823. AnnotationGen a = ((BcelAnnotation) decam.getAnnotation()).getBcelAnnotation();
  824. // create copy to get the annotation type into the right constant pool
  825. AnnotationAJ aj = new BcelAnnotation(new AnnotationGen(a, clazz.getConstantPool(), true),world);
  826. method.addAnnotation(aj);
  827. resolvedmember.addAnnotation(decam.getAnnotation());
  828. AsmRelationshipProvider.addDeclareAnnotationMethodRelationship(decam.getSourceLocation(),
  829. clazz.getName(), resolvedmember, world.getModelAsAsmManager());
  830. reportMethodCtorWeavingMessage(clazz, resolvedmember, decam, method.getDeclarationLineNumber());
  831. isChanged = true;
  832. modificationOccured = true;
  833. unusedDecams.remove(decam);
  834. } else if (!decam.isStarredAnnotationPattern()) {
  835. // an annotation is specified that might be put on by a subsequent decaf
  836. worthRetrying.add(decam);
  837. }
  838. }
  839. // Multiple secondary passes
  840. while (!worthRetrying.isEmpty() && modificationOccured) {
  841. modificationOccured = false;
  842. // lets have another go
  843. List<DeclareAnnotation> forRemoval = new ArrayList<DeclareAnnotation>();
  844. for (DeclareAnnotation decam : worthRetrying) {
  845. if (decam.matches(resolvedmember, world)) {
  846. if (doesAlreadyHaveAnnotation(resolvedmember, decam, reportedProblems,false)) {
  847. // remove the declare @method since don't
  848. // want an error when
  849. // the annotation is already there
  850. unusedDecams.remove(decam);
  851. continue; // skip this one...
  852. }
  853. AnnotationGen a = ((BcelAnnotation) decam.getAnnotation()).getBcelAnnotation();
  854. // create copy to get the annotation type into the right constant pool
  855. AnnotationAJ aj = new BcelAnnotation(new AnnotationGen(a, clazz.getConstantPool(), true),world);
  856. method.addAnnotation(aj);
  857. resolvedmember.addAnnotation(decam.getAnnotation());
  858. AsmRelationshipProvider.addDeclareAnnotationMethodRelationship(decam.getSourceLocation(),
  859. clazz.getName(), resolvedmember, world.getModelAsAsmManager());// getMethod());
  860. isChanged = true;
  861. modificationOccured = true;
  862. forRemoval.add(decam);
  863. unusedDecams.remove(decam);
  864. }
  865. }
  866. worthRetrying.removeAll(forRemoval);
  867. }
  868. }
  869. }
  870. // deal with all the other methods...
  871. List<LazyMethodGen> members = clazz.getMethodGens();
  872. if (!members.isEmpty()) {
  873. for (int memberCounter = 0; memberCounter < members.size(); memberCounter++) {
  874. LazyMethodGen mg = members.get(memberCounter);
  875. if (!mg.getName().startsWith(NameMangler.PREFIX)) {
  876. // Single first pass
  877. List<DeclareAnnotation> worthRetrying = new ArrayList<DeclareAnnotation>();
  878. boolean modificationOccured = false;
  879. List<AnnotationGen> annotationsToAdd = null;
  880. for (DeclareAnnotation decaM : decaMs) {
  881. if (decaM.matches(mg.getMemberView(), world)) {
  882. if (doesAlreadyHaveAnnotation(mg.getMemberView(), decaM, reportedProblems,true)) {
  883. // remove the declare @method since don't want
  884. // an error when the annotation is already there
  885. unusedDecams.remove(decaM);
  886. continue; // skip this one...
  887. }
  888. if (annotationsToAdd == null) {
  889. annotationsToAdd = new ArrayList<AnnotationGen>();
  890. }
  891. AnnotationGen a = ((BcelAnnotation) decaM.getAnnotation()).getBcelAnnotation();
  892. AnnotationGen ag = new AnnotationGen(a, clazz.getConstantPool(), true);
  893. annotationsToAdd.add(ag);
  894. mg.addAnnotation(decaM.getAnnotation());
  895. AsmRelationshipProvider.addDeclareAnnotationMethodRelationship(decaM.getSourceLocation(),
  896. clazz.getName(), mg.getMemberView(), world.getModelAsAsmManager());// getMethod());
  897. reportMethodCtorWeavingMessage(clazz, mg.getMemberView(), decaM, mg.getDeclarationLineNumber());
  898. isChanged = true;
  899. modificationOccured = true;
  900. // remove the declare @method since have matched
  901. // against it
  902. unusedDecams.remove(decaM);
  903. } else {
  904. if (!decaM.isStarredAnnotationPattern()) {
  905. worthRetrying.add(decaM); // an annotation is
  906. // specified that
  907. // might be put on
  908. // by a subsequent
  909. // decaf
  910. }
  911. }
  912. }
  913. // Multiple secondary passes
  914. while (!worthRetrying.isEmpty() && modificationOccured) {
  915. modificationOccured = false;
  916. // lets have another go
  917. List<DeclareAnnotation> forRemoval = new ArrayList<DeclareAnnotation>();
  918. for (DeclareAnnotation decaM : worthRetrying) {
  919. if (decaM.matches(mg.getMemberView(), world)) {
  920. if (doesAlreadyHaveAnnotation(mg.getMemberView(), decaM, reportedProblems,true)) {
  921. // remove the declare @method since don't
  922. // want an error when
  923. // the annotation is already there
  924. unusedDecams.remove(decaM);
  925. continue; // skip this one...
  926. }
  927. if (annotationsToAdd == null) {
  928. annotationsToAdd = new ArrayList<AnnotationGen>();
  929. }
  930. AnnotationGen a = ((BcelAnnotation) decaM.getAnnotation()).getBcelAnnotation();
  931. // create copy to get the annotation type into the right constant pool
  932. AnnotationGen ag = new AnnotationGen(a, clazz.getConstantPool(), true);
  933. annotationsToAdd.add(ag);
  934. mg.addAnnotation(decaM.getAnnotation());
  935. AsmRelationshipProvider.addDeclareAnnotationMethodRelationship(decaM.getSourceLocation(),
  936. clazz.getName(), mg.getMemberView(), world.getModelAsAsmManager());// getMethod());
  937. isChanged = true;
  938. modificationOccured = true;
  939. forRemoval.add(decaM);
  940. // remove the declare @method since have matched
  941. // against it
  942. unusedDecams.remove(decaM);
  943. }
  944. }
  945. worthRetrying.removeAll(forRemoval);
  946. }
  947. if (annotationsToAdd != null) {
  948. Method oldMethod = mg.getMethod();
  949. MethodGen myGen = new MethodGen(oldMethod, clazz.getClassName(), clazz.getConstantPool(), false);
  950. for (AnnotationGen a : annotationsToAdd) {
  951. myGen.addAnnotation(a);
  952. }
  953. Method newMethod = myGen.getMethod();
  954. members.set(memberCounter, new LazyMethodGen(newMethod, clazz));
  955. }
  956. }
  957. }
  958. checkUnusedDeclareAts(unusedDecams, false);
  959. }
  960. return isChanged;
  961. }
  962. // TAG: WeavingMessage
  963. private void reportMethodCtorWeavingMessage(LazyClassGen clazz, ResolvedMember member, DeclareAnnotation decaM,
  964. int memberLineNumber) {
  965. if (!getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) {
  966. StringBuffer parmString = new StringBuffer("(");
  967. UnresolvedType[] paramTypes = member.getParameterTypes();
  968. for (int i = 0; i < paramTypes.length; i++) {
  969. UnresolvedType type = paramTypes[i];
  970. String s = org.aspectj.apache.bcel.classfile.Utility.signatureToString(type.getSignature());
  971. if (s.lastIndexOf('.') != -1) {
  972. s = s.substring(s.lastIndexOf('.') + 1);
  973. }
  974. parmString.append(s);
  975. if ((i + 1) < paramTypes.length) {
  976. parmString.append(",");
  977. }
  978. }
  979. parmString.append(")");
  980. String methodName = member.getName();
  981. StringBuffer sig = new StringBuffer();
  982. sig.append(org.aspectj.apache.bcel.classfile.Utility.accessToString(member.getModifiers()));
  983. sig.append(" ");
  984. sig.append(member.getReturnType().toString());
  985. sig.append(" ");
  986. sig.append(member.getDeclaringType().toString());
  987. sig.append(".");
  988. sig.append(methodName.equals("<init>") ? "new" : methodName);
  989. sig.append(parmString);
  990. StringBuffer loc = new StringBuffer();
  991. if (clazz.getFileName() == null) {
  992. loc.append("no debug info available");
  993. } else {
  994. loc.append(clazz.getFileName());
  995. if (memberLineNumber != -1) {
  996. loc.append(":" + memberLineNumber);
  997. }
  998. }
  999. getWorld().getMessageHandler().handleMessage(
  1000. WeaveMessage.constructWeavingMessage(
  1001. WeaveMessage.WEAVEMESSAGE_ANNOTATES,
  1002. new String[] { sig.toString(), loc.toString(), decaM.getAnnotationString(),
  1003. methodName.startsWith("<init>") ? "constructor" : "method", decaM.getAspect().toString(),
  1004. Utility.beautifyLocation(decaM.getSourceLocation()) }));
  1005. }
  1006. }
  1007. /**
  1008. * Looks through a list of declare annotation statements and only returns those that could possibly match on a field/method/ctor
  1009. * in type.
  1010. */
  1011. private List<DeclareAnnotation> getMatchingSubset(List<DeclareAnnotation> declareAnnotations, ResolvedType type) {
  1012. List<DeclareAnnotation> subset = new ArrayList<DeclareAnnotation>();
  1013. for (DeclareAnnotation da : declareAnnotations) {
  1014. if (da.couldEverMatch(type)) {
  1015. subset.add(da);
  1016. }
  1017. }
  1018. return subset;
  1019. }
  1020. /**
  1021. * Get a subset of all the type mungers defined on this aspect
  1022. */
  1023. private List<ConcreteTypeMunger> getITDSubset(LazyClassGen clazz, ResolvedTypeMunger.Kind wantedKind) {
  1024. List<ConcreteTypeMunger> subset = new ArrayList<ConcreteTypeMunger>();
  1025. for (ConcreteTypeMunger typeMunger : clazz.getBcelObjectType().getTypeMungers()) {
  1026. if (typeMunger.getMunger().getKind() == wantedKind) {
  1027. subset.add(typeMunger);
  1028. }
  1029. }
  1030. return subset;
  1031. }
  1032. public LazyMethodGen locateAnnotationHolderForFieldMunger(LazyClassGen clazz, ConcreteTypeMunger fieldMunger) {
  1033. NewFieldTypeMunger newFieldMunger = (NewFieldTypeMunger) fieldMunger.getMunger();
  1034. ResolvedMember lookingFor = AjcMemberMaker.interFieldInitializer(newFieldMunger.getSignature(), clazz.getType());
  1035. for (LazyMethodGen method : clazz.getMethodGens()) {
  1036. if (method.getName().equals(lookingFor.getName())) {
  1037. return method;
  1038. }
  1039. }
  1040. return null;
  1041. }
  1042. // FIXME asc refactor this to neaten it up
  1043. public LazyMethodGen locateAnnotationHolderForMethodCtorMunger(LazyClassGen clazz, ConcreteTypeMunger methodCtorMunger) {
  1044. ResolvedTypeMunger rtMunger = methodCtorMunger.getMunger();
  1045. ResolvedMember lookingFor = null;
  1046. if (rtMunger instanceof NewMethodTypeMunger) {
  1047. NewMethodTypeMunger nftm = (NewMethodTypeMunger) rtMunger;
  1048. lookingFor = AjcMemberMaker.interMethodDispatcher(nftm.getSignature(), methodCtorMunger.getAspectType());
  1049. } else if (rtMunger instanceof NewConstructorTypeMunger) {
  1050. NewConstructorTypeMunger nftm = (NewConstructorTypeMunger) rtMunger;
  1051. lookingFor = AjcMemberMaker.postIntroducedConstructor(methodCtorMunger.getAspectType(), nftm.getSignature()
  1052. .getDeclaringType(), nftm.getSignature().getParameterTypes());
  1053. } else {
  1054. throw new BCException("Not sure what this is: " + methodCtorMunger);
  1055. }
  1056. String name = lookingFor.getName();
  1057. String paramSignature = lookingFor.getParameterSignature();
  1058. for (LazyMethodGen member : clazz.getMethodGens()) {
  1059. if (member.getName().equals(name) && member.getParameterSignature().equals(paramSignature)) {
  1060. return member;
  1061. }
  1062. }
  1063. return null;
  1064. }
  1065. /**
  1066. * Applies some set of declare @field constructs (List<DeclareAnnotation>) to some bunch of ITDfields (List<BcelTypeMunger>. It
  1067. * will iterate over the fields repeatedly until everything has been applied.
  1068. *
  1069. */
  1070. private boolean weaveAtFieldRepeatedly(List<DeclareAnnotation> decaFs, List<ConcreteTypeMunger> itdFields,
  1071. List<Integer> reportedErrors) {
  1072. boolean isChanged = false;
  1073. for (Iterator<ConcreteTypeMunger> iter = itdFields.iterator(); iter.hasNext();) {
  1074. BcelTypeMunger fieldMunger = (BcelTypeMunger) iter.next();
  1075. ResolvedMember itdIsActually = fieldMunger.getSignature();
  1076. Set<DeclareAnnotation> worthRetrying = new LinkedHashSet<DeclareAnnotation>();
  1077. boolean modificationOccured = false;
  1078. for (Iterator<DeclareAnnotation> iter2 = decaFs.iterator(); iter2.hasNext();) {
  1079. DeclareAnnotation decaF = iter2.next();
  1080. if (decaF.matches(itdIsActually, world)) {
  1081. if (decaF.isRemover()) {
  1082. LazyMethodGen annotationHolder = locateAnnotationHolderForFieldMunger(clazz, fieldMunger);
  1083. if (annotationHolder.hasAnnotation(decaF.getAnnotationType())) {
  1084. isChanged = true;
  1085. // something to remove
  1086. annotationHolder.removeAnnotation(decaF.getAnnotationType());
  1087. AsmRelationshipProvider.addDeclareAnnotationRelationship(world.getModelAsAsmManager(),
  1088. decaF.getSourceLocation(), itdIsActually.getSourceLocation(), true);
  1089. } else {
  1090. worthRetrying.add(decaF);
  1091. }
  1092. } else {
  1093. LazyMethodGen annotationHolder = locateAnnotationHolderForFieldMunger(clazz, fieldMunger);
  1094. if (doesAlreadyHaveAnnotation(annotationHolder, itdIsActually, decaF, reportedErrors)) {
  1095. continue; // skip this one...
  1096. }
  1097. annotationHolder.addAnnotation(decaF.getAnnotation());
  1098. AsmRelationshipProvider.addDeclareAnnotationRelationship(world.getModelAsAsmManager(),
  1099. decaF.getSourceLocation(), itdIsActually.getSourceLocation(), false);
  1100. isChanged = true;
  1101. modificationOccured = true;
  1102. }
  1103. } else {
  1104. if (!decaF.isStarredAnnotationPattern()) {
  1105. worthRetrying.add(decaF); // an annotation is specified
  1106. // that might be put on by a
  1107. // subsequent decaf
  1108. }
  1109. }
  1110. }
  1111. while (!worthRetrying.isEmpty() && modificationOccured) {
  1112. modificationOccured = false;
  1113. List<DeclareAnnotation> forRemoval = new ArrayList<DeclareAnnotation>();
  1114. for (Iterator<DeclareAnnotation> iter2 = worthRetrying.iterator(); iter2.hasNext();) {
  1115. DeclareAnnotation decaF = iter2.next();
  1116. if (decaF.matches(itdIsActually, world)) {
  1117. if (decaF.isRemover()) {
  1118. LazyMethodGen annotationHolder = locateAnnotationHolderForFieldMunger(clazz, fieldMunger);
  1119. if (annotationHolder.hasAnnotation(decaF.getAnnotationType())) {
  1120. isChanged = true;
  1121. // something to remove
  1122. annotationHolder.removeAnnotation(decaF.getAnnotationType());
  1123. AsmRelationshipProvider.addDeclareAnnotationRelationship(world.getModelAsAsmManager(),
  1124. decaF.getSourceLocation(), itdIsActually.getSourceLocation(), true);
  1125. forRemoval.add(decaF);
  1126. }
  1127. } else {
  1128. LazyMethodGen annotationHolder = locateAnnotationHolderForFieldMunger(clazz, fieldMunger);
  1129. if (doesAlreadyHaveAnnotation(annotationHolder, itdIsActually, decaF, reportedErrors)) {
  1130. continue; // skip this one...
  1131. }
  1132. annotationHolder.addAnnotation(decaF.getAnnotation());
  1133. AsmRelationshipProvider.addDeclareAnnotationRelationship(world.getModelAsAsmManager(),
  1134. decaF.getSourceLocation(), itdIsActually.getSourceLocation(), false);
  1135. isChanged = true;
  1136. modificationOccured = true;
  1137. forRemoval.add(decaF);
  1138. }
  1139. }
  1140. }
  1141. worthRetrying.removeAll(forRemoval);
  1142. }
  1143. }
  1144. return isChanged;
  1145. }
  1146. /**
  1147. * Applies some set of declare @method/@ctor constructs (List<DeclareAnnotation>) to some bunch of ITDmembers
  1148. * (List<BcelTypeMunger>. It will iterate over the fields repeatedly until everything has been applied.
  1149. */
  1150. private boolean weaveAtMethodOnITDSRepeatedly(List<DeclareAnnotation> decaMCs,
  1151. List<ConcreteTypeMunger> itdsForMethodAndConstructor, List<Integer> reportedErrors) {
  1152. boolean isChanged = false;
  1153. AsmManager asmManager = world.getModelAsAsmManager();
  1154. for (ConcreteTypeMunger methodctorMunger : itdsForMethodAndConstructor) {
  1155. // for (Iterator iter = itdsForMethodAndConstructor.iterator(); iter.hasNext();) {
  1156. // BcelTypeMunger methodctorMunger = (BcelTypeMunger) iter.next();
  1157. ResolvedMember unMangledInterMethod = methodctorMunger.getSignature();
  1158. List<DeclareAnnotation> worthRetrying = new ArrayList<DeclareAnnotation>();
  1159. boolean modificationOccured = false;
  1160. for (Iterator<DeclareAnnotation> iter2 = decaMCs.iterator(); iter2.hasNext();) {
  1161. DeclareAnnotation decaMC = iter2.next();
  1162. if (decaMC.matches(unMangledInterMethod, world)) {
  1163. LazyMethodGen annotationHolder = locateAnnotationHolderForMethodCtorMunger(clazz, methodctorMunger);
  1164. if (annotationHolder == null
  1165. || doesAlreadyHaveAnnotation(annotationHolder, unMangledInterMethod, decaMC, reportedErrors)) {
  1166. continue; // skip this one...
  1167. }
  1168. annotationHolder.addAnnotation(decaMC.getAnnotation());
  1169. isChanged = true;
  1170. AsmRelationshipProvider.addDeclareAnnotationRelationship(asmManager, decaMC.getSourceLocation(),
  1171. unMangledInterMethod.getSourceLocation(), false);
  1172. reportMethodCtorWeavingMessage(clazz, unMangledInterMethod, decaMC, -1);
  1173. modificationOccured = true;
  1174. } else {
  1175. // If an annotation is specified, it might be added by one of the other declare annotation statements
  1176. if (!decaMC.isStarredAnnotationPattern()) {
  1177. worthRetrying.add(decaMC);
  1178. }
  1179. }
  1180. }
  1181. while (!worthRetrying.isEmpty() && modificationOccured) {
  1182. modificationOccured = false;
  1183. List<DeclareAnnotation> forRemoval = new ArrayList<DeclareAnnotation>();
  1184. for (Iterator<DeclareAnnotation> iter2 = worthRetrying.iterator(); iter2.hasNext();) {
  1185. DeclareAnnotation decaMC = iter2.next();
  1186. if (decaMC.matches(unMangledInterMethod, world)) {
  1187. LazyMethodGen annotationHolder = locateAnnotationHolderForFieldMunger(clazz, methodctorMunger);
  1188. if (doesAlreadyHaveAnnotation(annotationHolder, unMangledInterMethod, decaMC, reportedErrors)) {
  1189. continue; // skip this one...
  1190. }
  1191. annotationHolder.addAnnotation(decaMC.getAnnotation());
  1192. unMangledInterMethod.addAnnotation(decaMC.getAnnotation());
  1193. AsmRelationshipProvider.addDeclareAnnotationRelationship(asmManager, decaMC.getSourceLocation(),
  1194. unMangledInterMethod.getSourceLocation(), false);
  1195. isChanged = true;
  1196. modificationOccured = true;
  1197. forRemoval.add(decaMC);
  1198. }
  1199. worthRetrying.removeAll(forRemoval);
  1200. }
  1201. }
  1202. }
  1203. return isChanged;
  1204. }
  1205. private boolean dontAddTwice(DeclareAnnotation decaF, AnnotationAJ[] dontAddMeTwice) {
  1206. for (AnnotationAJ ann : dontAddMeTwice) {
  1207. if (ann != null && decaF.getAnnotation().getTypeName().equals(ann.getTypeName())) {
  1208. return true;
  1209. }
  1210. }
  1211. return false;
  1212. }
  1213. /**
  1214. * Remove an annotation from the supplied array, if it is in there.
  1215. */
  1216. private AnnotationAJ[] removeFromAnnotationsArray(AnnotationAJ[] annotations,AnnotationAJ annotation) {
  1217. for (int i=0;i<annotations.length;i++) {
  1218. if (annotations[i] != null && annotation.getTypeName().equals(annotations[i].getTypeName())) {
  1219. // Remove it!
  1220. AnnotationAJ[] newArray = new AnnotationAJ[annotations.length-1];
  1221. int index=0;
  1222. for (int j=0;j<annotations.length;j++) {
  1223. if (j!=i) {
  1224. newArray[index++]=annotations[j];
  1225. }
  1226. }
  1227. return newArray;
  1228. }
  1229. }
  1230. return annotations;
  1231. }
  1232. // BUGWARNING not getting enough warnings out on declare @field ? There is a potential problem here with warnings not
  1233. // coming out - this will occur if they are created on the second iteration round this loop.
  1234. // We currently deactivate error reporting for the second time round. A possible solution is to record what annotations
  1235. // were added by what decafs and check that to see if an error needs to be reported - this would be expensive so lets
  1236. // skip it for now
  1237. /**
  1238. * Weave any declare @field statements into the fields of the supplied class. This will attempt to apply them to the ITDs too.
  1239. *
  1240. * Interesting case relating to public ITDd fields. The annotations are really stored against the interfieldinit method in the
  1241. * aspect, but the public field is placed in the target type and then is processed in the 2nd pass over fields that occurs. I
  1242. * think it would be more expensive to avoid putting the annotation on that inserted public field than just to have it put there
  1243. * as well as on the interfieldinit method.
  1244. */
  1245. private boolean weaveDeclareAtField(LazyClassGen clazz) {
  1246. List<Integer> reportedProblems = new ArrayList<Integer>();
  1247. List<DeclareAnnotation> allDecafs = world.getDeclareAnnotationOnFields();
  1248. if (allDecafs.isEmpty()) {
  1249. return false;
  1250. }
  1251. boolean typeIsChanged = false;
  1252. List<ConcreteTypeMunger> relevantItdFields = getITDSubset(clazz, ResolvedTypeMunger.Field);
  1253. if (relevantItdFields != null) {
  1254. typeIsChanged = weaveAtFieldRepeatedly(allDecafs, relevantItdFields, reportedProblems);
  1255. }
  1256. List<DeclareAnnotation> decafs = getMatchingSubset(allDecafs, clazz.getType());
  1257. if (decafs.isEmpty()) {
  1258. return typeIsChanged;
  1259. }
  1260. List<BcelField> fields = clazz.getFieldGens();
  1261. if (fields != null) {
  1262. Set<DeclareAnnotation> unusedDecafs = new HashSet<DeclareAnnotation>();
  1263. unusedDecafs.addAll(decafs);
  1264. for (BcelField field : fields) {
  1265. if (!field.getName().startsWith(NameMangler.PREFIX)) {
  1266. // Single first pass
  1267. Set<DeclareAnnotation> worthRetrying = new LinkedHashSet<DeclareAnnotation>();
  1268. boolean modificationOccured = false;
  1269. AnnotationAJ[] dontAddMeTwice = field.getAnnotations();
  1270. // go through all the declare @field statements
  1271. for (DeclareAnnotation decaf : decafs) {
  1272. if (decaf.getAnnotation() == null) {
  1273. return false;
  1274. }
  1275. if (decaf.matches(field, world)) {
  1276. if (decaf.isRemover()) {
  1277. AnnotationAJ annotation = decaf.getAnnotation();
  1278. if (field.hasAnnotation(annotation.getType())) {
  1279. // something to remove
  1280. typeIsChanged = true;
  1281. field.removeAnnotation(annotation);
  1282. AsmRelationshipProvider.addDeclareAnnotationFieldRelationship(world.getModelAsAsmManager(),
  1283. decaf.getSourceLocation(), clazz.getName(), field, true);
  1284. reportFieldAnnotationWeavingMessage(clazz, field, decaf, true);
  1285. dontAddMeTwice = removeFromAnnotationsArray(dontAddMeTwice, annotation);
  1286. } else {
  1287. worthRetrying.add(decaf);
  1288. }
  1289. unusedDecafs.remove(decaf);
  1290. } else {
  1291. if (!dontAddTwice(decaf, dontAddMeTwice)) {
  1292. if (doesAlreadyHaveAnnotation(field, decaf, reportedProblems,true )) {
  1293. // remove the declare @field since don't want an error when the annotation is already there
  1294. unusedDecafs.remove(decaf);
  1295. continue;
  1296. }
  1297. field.addAnnotation(decaf.getAnnotation());
  1298. }
  1299. AsmRelationshipProvider.addDeclareAnnotationFieldRelationship(world.getModelAsAsmManager(),
  1300. decaf.getSourceLocation(), clazz.getName(), field, false);
  1301. reportFieldAnnotationWeavingMessage(clazz, field, decaf, false);
  1302. typeIsChanged = true;
  1303. modificationOccured = true;
  1304. unusedDecafs.remove(decaf);
  1305. }
  1306. } else if (!decaf.isStarredAnnotationPattern() || decaf.isRemover()) {
  1307. worthRetrying.add(decaf); // an annotation is specified that might be put on by a subsequent decaf
  1308. }
  1309. }
  1310. // Multiple secondary passes
  1311. while (!worthRetrying.isEmpty() && modificationOccured) {
  1312. modificationOccured = false;
  1313. // lets have another go with any remaining ones
  1314. List<DeclareAnnotation> forRemoval = new ArrayList<DeclareAnnotation>();
  1315. for (Iterator<DeclareAnnotation> iter = worthRetrying.iterator(); iter.hasNext();) {
  1316. DeclareAnnotation decaF = iter.next();
  1317. if (decaF.matches(field, world)) {
  1318. if (decaF.isRemover()) {
  1319. AnnotationAJ annotation = decaF.getAnnotation();
  1320. if (field.hasAnnotation(annotation.getType())) {
  1321. // something to remove
  1322. typeIsChanged = modificationOccured = true;
  1323. forRemoval.add(decaF);
  1324. field.removeAnnotation(annotation);
  1325. AsmRelationshipProvider.addDeclareAnnotationFieldRelationship(world.getModelAsAsmManager(),
  1326. decaF.getSourceLocation(), clazz.getName(), field, true);
  1327. reportFieldAnnotationWeavingMessage(clazz, field, decaF, true);
  1328. }
  1329. } else {
  1330. // below code is for recursive things
  1331. unusedDecafs.remove(decaF);
  1332. if (doesAlreadyHaveAnnotation(field, decaF, reportedProblems,true)) {
  1333. continue;
  1334. }
  1335. field.addAnnotation(decaF.getAnnotation());
  1336. AsmRelationshipProvider.addDeclareAnnotationFieldRelationship(world.getModelAsAsmManager(),
  1337. decaF.getSourceLocation(), clazz.getName(), field, false);
  1338. typeIsChanged = modificationOccured = true;
  1339. forRemoval.add(decaF);
  1340. }
  1341. }
  1342. }
  1343. worthRetrying.removeAll(forRemoval);
  1344. }
  1345. }
  1346. }
  1347. checkUnusedDeclareAts(unusedDecafs, true);
  1348. }
  1349. return typeIsChanged;
  1350. }
  1351. // bug 99191 - put out an error message if the type doesn't exist
  1352. /**
  1353. * Report an error if the reason a "declare @method/ctor/field" was not used was because the member specified does not exist.
  1354. * This method is passed some set of declare statements that didn't match and a flag indicating whether the set contains declare @field
  1355. * or declare @method/ctor entries.
  1356. */
  1357. private void checkUnusedDeclareAts(Set<DeclareAnnotation> unusedDecaTs, boolean isDeclareAtField) {
  1358. for (DeclareAnnotation declA : unusedDecaTs) {
  1359. // Error if an exact type pattern was specified
  1360. boolean shouldCheck = declA.isExactPattern() || declA.getSignaturePattern().getExactDeclaringTypes().size() != 0;
  1361. if (shouldCheck && declA.getKind() != DeclareAnnotation.AT_CONSTRUCTOR) {
  1362. if (declA.getSignaturePattern().isMatchOnAnyName()) {
  1363. shouldCheck = false;
  1364. } else {
  1365. List<ExactTypePattern> declaringTypePatterns = declA.getSignaturePattern().getExactDeclaringTypes();
  1366. if (declaringTypePatterns.size() == 0) {
  1367. shouldCheck = false;
  1368. } else {
  1369. for (ExactTypePattern exactTypePattern : declaringTypePatterns) {
  1370. if (exactTypePattern.isIncludeSubtypes()) {
  1371. shouldCheck = false;
  1372. break;
  1373. }
  1374. }
  1375. }
  1376. }
  1377. }
  1378. if (shouldCheck) {
  1379. // Quickly check if an ITD supplies the 'missing' member
  1380. boolean itdMatch = false;
  1381. List<ConcreteTypeMunger> lst = clazz.getType().getInterTypeMungers();
  1382. for (Iterator<ConcreteTypeMunger> iterator = lst.iterator(); iterator.hasNext() && !itdMatch;) {
  1383. ConcreteTypeMunger element = iterator.next();
  1384. if (element.getMunger() instanceof NewFieldTypeMunger) {
  1385. NewFieldTypeMunger nftm = (NewFieldTypeMunger) element.getMunger();
  1386. itdMatch = declA.matches(nftm.getSignature(), world);
  1387. } else if (element.getMunger() instanceof NewMethodTypeMunger) {
  1388. NewMethodTypeMunger nmtm = (NewMethodTypeMunger) element.getMunger();
  1389. itdMatch = declA.matches(nmtm.getSignature(), world);
  1390. } else if (element.getMunger() instanceof NewConstructorTypeMunger) {
  1391. NewConstructorTypeMunger nctm = (NewConstructorTypeMunger) element.getMunger();
  1392. itdMatch = declA.matches(nctm.getSignature(), world);
  1393. }
  1394. }
  1395. if (!itdMatch) {
  1396. IMessage message = null;
  1397. if (isDeclareAtField) {
  1398. message = new Message("The field '" + declA.getSignaturePattern().toString() + "' does not exist",
  1399. declA.getSourceLocation(), true);
  1400. } else {
  1401. message = new Message("The method '" + declA.getSignaturePattern().toString() + "' does not exist",
  1402. declA.getSourceLocation(), true);
  1403. }
  1404. world.getMessageHandler().handleMessage(message);
  1405. }
  1406. }
  1407. }
  1408. }
  1409. // TAG: WeavingMessage
  1410. private void reportFieldAnnotationWeavingMessage(LazyClassGen clazz, BcelField theField, DeclareAnnotation decaf,
  1411. boolean isRemove) {
  1412. if (!getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) {
  1413. world.getMessageHandler().handleMessage(
  1414. WeaveMessage.constructWeavingMessage(
  1415. isRemove ? WeaveMessage.WEAVEMESSAGE_REMOVES_ANNOTATION : WeaveMessage.WEAVEMESSAGE_ANNOTATES,
  1416. new String[] { theField.getFieldAsIs().toString() + "' of type '" + clazz.getName(),
  1417. clazz.getFileName(), decaf.getAnnotationString(), "field", decaf.getAspect().toString(),
  1418. Utility.beautifyLocation(decaf.getSourceLocation()) }));
  1419. }
  1420. }
  1421. /**
  1422. * Check if a resolved member (field/method/ctor) already has an annotation, if it does then put out a warning and return true
  1423. */
  1424. private boolean doesAlreadyHaveAnnotation(ResolvedMember rm, DeclareAnnotation deca, List<Integer> reportedProblems, boolean reportError) {
  1425. if (rm.hasAnnotation(deca.getAnnotationType())) {
  1426. if (reportError && world.getLint().elementAlreadyAnnotated.isEnabled()) {
  1427. Integer uniqueID = new Integer(rm.hashCode() * deca.hashCode());
  1428. if (!reportedProblems.contains(uniqueID)) {
  1429. reportedProblems.add(uniqueID);
  1430. world.getLint().elementAlreadyAnnotated.signal(new String[] { rm.toString(),
  1431. deca.getAnnotationType().toString() }, rm.getSourceLocation(),
  1432. new ISourceLocation[] { deca.getSourceLocation() });
  1433. }
  1434. }
  1435. return true;
  1436. }
  1437. return false;
  1438. }
  1439. private boolean doesAlreadyHaveAnnotation(LazyMethodGen rm, ResolvedMember itdfieldsig, DeclareAnnotation deca,
  1440. List<Integer> reportedProblems) {
  1441. if (rm != null && rm.hasAnnotation(deca.getAnnotationType())) {
  1442. if (world.getLint().elementAlreadyAnnotated.isEnabled()) {
  1443. Integer uniqueID = new Integer(rm.hashCode() * deca.hashCode());
  1444. if (!reportedProblems.contains(uniqueID)) {
  1445. reportedProblems.add(uniqueID);
  1446. reportedProblems.add(new Integer(itdfieldsig.hashCode() * deca.hashCode()));
  1447. world.getLint().elementAlreadyAnnotated.signal(new String[] { itdfieldsig.toString(),
  1448. deca.getAnnotationType().toString() }, rm.getSourceLocation(),
  1449. new ISourceLocation[] { deca.getSourceLocation() });
  1450. }
  1451. }
  1452. return true;
  1453. }
  1454. return false;
  1455. }
  1456. private Set<String> findAspectsForMungers(LazyMethodGen mg) {
  1457. Set<String> aspectsAffectingType = new HashSet<String>();
  1458. for (BcelShadow shadow : mg.matchedShadows) {
  1459. for (ShadowMunger munger : shadow.getMungers()) {
  1460. if (munger instanceof BcelAdvice) {
  1461. BcelAdvice bcelAdvice = (BcelAdvice) munger;
  1462. if (bcelAdvice.getConcreteAspect() != null) {
  1463. aspectsAffectingType.add(bcelAdvice.getConcreteAspect().getSignature());
  1464. }
  1465. } else {
  1466. // It is a 'Checker' - we don't need to remember aspects
  1467. // that only contributed Checkers...
  1468. }
  1469. }
  1470. }
  1471. return aspectsAffectingType;
  1472. }
  1473. private boolean inlineSelfConstructors(List<LazyMethodGen> methodGens, List<LazyMethodGen> recursiveCtors) {
  1474. boolean inlinedSomething = false;
  1475. List<LazyMethodGen> newRecursiveCtors = new ArrayList<LazyMethodGen>();
  1476. for (LazyMethodGen methodGen : methodGens) {
  1477. if (!methodGen.getName().equals("<init>")) {
  1478. continue;
  1479. }
  1480. InstructionHandle ih = findSuperOrThisCall(methodGen);
  1481. if (ih != null && isThisCall(ih)) {
  1482. LazyMethodGen donor = getCalledMethod(ih);
  1483. if (donor.equals(methodGen)) {
  1484. newRecursiveCtors.add(donor);
  1485. } else {
  1486. if (!recursiveCtors.contains(donor)) {
  1487. inlineMethod(donor, methodGen, ih);
  1488. inlinedSomething = true;
  1489. }
  1490. }
  1491. }
  1492. }
  1493. recursiveCtors.addAll(newRecursiveCtors);
  1494. return inlinedSomething;
  1495. }
  1496. private void positionAndImplement(List<BcelShadow> initializationShadows) {
  1497. for (BcelShadow s : initializationShadows) {
  1498. positionInitializationShadow(s);
  1499. // s.getEnclosingMethod().print();
  1500. s.implement();
  1501. }
  1502. }
  1503. private void positionInitializationShadow(BcelShadow s) {
  1504. LazyMethodGen mg = s.getEnclosingMethod();
  1505. InstructionHandle call = findSuperOrThisCall(mg);
  1506. InstructionList body = mg.getBody();
  1507. ShadowRange r = new ShadowRange(body);
  1508. r.associateWithShadow(s);
  1509. if (s.getKind() == Shadow.PreInitialization) {
  1510. // XXX assert first instruction is an ALOAD_0.
  1511. // a pre shadow goes from AFTER the first instruction (which we
  1512. // believe to
  1513. // be an ALOAD_0) to just before the call to super
  1514. r.associateWithTargets(Range.genStart(body, body.getStart().getNext()), Range.genEnd(body, call.getPrev()));
  1515. } else {
  1516. // assert s.getKind() == Shadow.Initialization
  1517. r.associateWithTargets(Range.genStart(body, call.getNext()), Range.genEnd(body));
  1518. }
  1519. }
  1520. private boolean isThisCall(InstructionHandle ih) {
  1521. InvokeInstruction inst = (InvokeInstruction) ih.getInstruction();
  1522. return inst.getClassName(cpg).equals(clazz.getName());
  1523. }
  1524. /**
  1525. * inline a particular call in bytecode.
  1526. *
  1527. * @param donor the method we want to inline
  1528. * @param recipient the method containing the call we want to inline
  1529. * @param call the instructionHandle in recipient's body holding the call we want to inline.
  1530. */
  1531. public static void inlineMethod(LazyMethodGen donor, LazyMethodGen recipient, InstructionHandle call) {
  1532. // assert recipient.contains(call)
  1533. /*
  1534. * Implementation notes:
  1535. *
  1536. * We allocate two slots for every tempvar so we don't screw up longs and doubles which may share space. This could be
  1537. * conservatively avoided (no reference to a long/double instruction, don't do it) or packed later. Right now we don't
  1538. * bother to pack.
  1539. *
  1540. * Allocate a new var for each formal param of the inlined. Fill with stack contents. Then copy the inlined instructions in
  1541. * with the appropriate remap table. Any framelocs used by locals in inlined are reallocated to top of frame,
  1542. */
  1543. final InstructionFactory fact = recipient.getEnclosingClass().getFactory();
  1544. IntMap frameEnv = new IntMap();
  1545. // this also sets up the initial environment
  1546. InstructionList argumentStores = genArgumentStores(donor, recipient, frameEnv, fact);
  1547. InstructionList inlineInstructions = genInlineInstructions(donor, recipient, frameEnv, fact, false);
  1548. inlineInstructions.insert(argumentStores);
  1549. recipient.getBody().append(call, inlineInstructions);
  1550. Utility.deleteInstruction(call, recipient);
  1551. }
  1552. // public BcelVar genTempVar(UnresolvedType typeX) {
  1553. // return new BcelVar(typeX.resolve(world),
  1554. // genTempVarIndex(typeX.getSize()));
  1555. // }
  1556. //
  1557. // private int genTempVarIndex(int size) {
  1558. // return enclosingMethod.allocateLocal(size);
  1559. // }
  1560. /**
  1561. * Input method is a synchronized method, we remove the bit flag for synchronized and then insert a try..finally block
  1562. *
  1563. * Some jumping through firey hoops required - depending on the input code level (1.5 or not) we may or may not be able to use
  1564. * the LDC instruction that takes a class literal (doesnt on <1.5).
  1565. *
  1566. * FIXME asc Before promoting -Xjoinpoints:synchronization to be a standard option, this needs a bunch of tidying up - there is
  1567. * some duplication that can be removed.
  1568. */
  1569. public static void transformSynchronizedMethod(LazyMethodGen synchronizedMethod) {
  1570. if (trace.isTraceEnabled()) {
  1571. trace.enter("transformSynchronizedMethod", synchronizedMethod);
  1572. }
  1573. // System.err.println("DEBUG: Transforming synchronized method: "+
  1574. // synchronizedMethod.getName());
  1575. final InstructionFactory fact = synchronizedMethod.getEnclosingClass().getFactory();
  1576. InstructionList body = synchronizedMethod.getBody();
  1577. InstructionList prepend = new InstructionList();
  1578. Type enclosingClassType = BcelWorld.makeBcelType(synchronizedMethod.getEnclosingClass().getType());
  1579. // STATIC METHOD TRANSFORMATION
  1580. if (synchronizedMethod.isStatic()) {
  1581. // What to do here depends on the level of the class file!
  1582. // LDC can handle class literals in Java5 and above *sigh*
  1583. if (synchronizedMethod.getEnclosingClass().isAtLeastJava5()) {
  1584. // MONITORENTER logic:
  1585. // 0: ldc #2; //class C
  1586. // 2: dup
  1587. // 3: astore_0
  1588. // 4: monitorenter
  1589. int slotForLockObject = synchronizedMethod.allocateLocal(enclosingClassType);
  1590. prepend.append(fact.createConstant(enclosingClassType));
  1591. prepend.append(InstructionFactory.createDup(1));
  1592. prepend.append(InstructionFactory.createStore(enclosingClassType, slotForLockObject));
  1593. prepend.append(InstructionFactory.MONITORENTER);
  1594. // MONITOREXIT logic:
  1595. // We basically need to wrap the code from the method in a
  1596. // finally block that
  1597. // will ensure monitorexit is called. Content on the finally
  1598. // block seems to
  1599. // be always:
  1600. //
  1601. // E1: ALOAD_1
  1602. // MONITOREXIT
  1603. // ATHROW
  1604. //
  1605. // so lets build that:
  1606. InstructionList finallyBlock = new InstructionList();
  1607. finallyBlock.append(InstructionFactory.createLoad(Type.getType(java.lang.Class.class), slotForLockObject));
  1608. finallyBlock.append(InstructionConstants.MONITOREXIT);
  1609. finallyBlock.append(InstructionConstants.ATHROW);
  1610. // finally -> E1
  1611. // | GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line
  1612. // 21)
  1613. // | LDC "hello"
  1614. // | INVOKEVIRTUAL java.io.PrintStream.println
  1615. // (Ljava/lang/String;)V
  1616. // | ALOAD_1 (line 20)
  1617. // | MONITOREXIT
  1618. // finally -> E1
  1619. // GOTO L0
  1620. // finally -> E1
  1621. // | E1: ALOAD_1
  1622. // | MONITOREXIT
  1623. // finally -> E1
  1624. // ATHROW
  1625. // L0: RETURN (line 23)
  1626. // search for 'returns' and make them jump to the
  1627. // aload_<n>,monitorexit
  1628. InstructionHandle walker = body.getStart();
  1629. List<InstructionHandle> rets = new ArrayList<InstructionHandle>();
  1630. while (walker != null) {
  1631. if (walker.getInstruction().isReturnInstruction()) {
  1632. rets.add(walker);
  1633. }
  1634. walker = walker.getNext();
  1635. }
  1636. if (!rets.isEmpty()) {
  1637. // need to ensure targeters for 'return' now instead target
  1638. // the load instruction
  1639. // (so we never jump over the monitorexit logic)
  1640. for (Iterator<InstructionHandle> iter = rets.iterator(); iter.hasNext();) {
  1641. InstructionHandle element = iter.next();
  1642. InstructionList monitorExitBlock = new InstructionList();
  1643. monitorExitBlock.append(InstructionFactory.createLoad(enclosingClassType, slotForLockObject));
  1644. monitorExitBlock.append(InstructionConstants.MONITOREXIT);
  1645. // monitorExitBlock.append(Utility.copyInstruction(element
  1646. // .getInstruction()));
  1647. // element.setInstruction(InstructionFactory.createLoad(
  1648. // classType,slotForThis));
  1649. InstructionHandle monitorExitBlockStart = body.insert(element, monitorExitBlock);
  1650. // now move the targeters from the RET to the start of
  1651. // the monitorexit block
  1652. for (InstructionTargeter targeter : element.getTargetersCopy()) {
  1653. // what kinds are there?
  1654. if (targeter instanceof LocalVariableTag) {
  1655. // ignore
  1656. } else if (targeter instanceof LineNumberTag) {
  1657. // ignore
  1658. // } else if (targeter instanceof
  1659. // InstructionBranch &&
  1660. // ((InstructionBranch)targeter).isGoto()) {
  1661. // // move it...
  1662. // targeter.updateTarget(element,
  1663. // monitorExitBlockStart);
  1664. } else if (targeter instanceof InstructionBranch) {
  1665. // move it
  1666. targeter.updateTarget(element, monitorExitBlockStart);
  1667. } else {
  1668. throw new BCException("Unexpected targeter encountered during transform: " + targeter);
  1669. }
  1670. }
  1671. }
  1672. }
  1673. // now the magic, putting the finally block around the code
  1674. InstructionHandle finallyStart = finallyBlock.getStart();
  1675. InstructionHandle tryPosition = body.getStart();
  1676. InstructionHandle catchPosition = body.getEnd();
  1677. body.insert(body.getStart(), prepend); // now we can put the
  1678. // monitorenter stuff on
  1679. synchronizedMethod.getBody().append(finallyBlock);
  1680. synchronizedMethod.addExceptionHandler(tryPosition, catchPosition, finallyStart, null/* ==finally */, false);
  1681. synchronizedMethod.addExceptionHandler(finallyStart, finallyStart.getNext(), finallyStart, null, false);
  1682. } else {
  1683. // TRANSFORMING STATIC METHOD ON PRE JAVA5
  1684. // Hideous nightmare, class literal references prior to Java5
  1685. // YIKES! this is just the code for MONITORENTER !
  1686. // 0: getstatic #59; //Field class$1:Ljava/lang/Class;
  1687. // 3: dup
  1688. // 4: ifnonnull 32
  1689. // 7: pop
  1690. // try
  1691. // 8: ldc #61; //String java.lang.String
  1692. // 10: invokestatic #44; //Method
  1693. // java/lang/Class.forName:(Ljava/lang/String;)Ljava/lang/Class;
  1694. // 13: dup
  1695. // catch
  1696. // 14: putstatic #59; //Field class$1:Ljava/lang/Class;
  1697. // 17: goto 32
  1698. // 20: new #46; //class java/lang/NoClassDefFoundError
  1699. // 23: dup_x1
  1700. // 24: swap
  1701. // 25: invokevirtual #52; //Method
  1702. // java/lang/Throwable.getMessage:()Ljava/lang/String;
  1703. // 28: invokespecial #54; //Method
  1704. // java/lang/NoClassDefFoundError."<init>":(Ljava/lang/String;)V
  1705. // 31: athrow
  1706. // 32: dup <-- partTwo (branch target)
  1707. // 33: astore_0
  1708. // 34: monitorenter
  1709. //
  1710. // plus exceptiontable entry!
  1711. // 8 13 20 Class java/lang/ClassNotFoundException
  1712. Type classType = BcelWorld.makeBcelType(synchronizedMethod.getEnclosingClass().getType());
  1713. Type clazzType = Type.getType(Class.class);
  1714. InstructionList parttwo = new InstructionList();
  1715. parttwo.append(InstructionFactory.createDup(1));
  1716. int slotForThis = synchronizedMethod.allocateLocal(classType);
  1717. parttwo.append(InstructionFactory.createStore(clazzType, slotForThis)); // ? should be the real type ? String or
  1718. // something?
  1719. parttwo.append(InstructionFactory.MONITORENTER);
  1720. String fieldname = synchronizedMethod.getEnclosingClass().allocateField("class$");
  1721. FieldGen f = new FieldGen(Modifier.STATIC | Modifier.PRIVATE, Type.getType(Class.class), fieldname,
  1722. synchronizedMethod.getEnclosingClass().getConstantPool());
  1723. synchronizedMethod.getEnclosingClass().addField(f, null);
  1724. // 10: invokestatic #44; //Method
  1725. // java/lang/Class.forName:(Ljava/lang/String;)Ljava/lang/Class;
  1726. // 13: dup
  1727. // 14: putstatic #59; //Field class$1:Ljava/lang/Class;
  1728. // 17: goto 32
  1729. // 20: new #46; //class java/lang/NoClassDefFoundError
  1730. // 23: dup_x1
  1731. // 24: swap
  1732. // 25: invokevirtual #52; //Method
  1733. // java/lang/Throwable.getMessage:()Ljava/lang/String;
  1734. // 28: invokespecial #54; //Method
  1735. // java/lang/NoClassDefFoundError."<init>":(Ljava/lang/String;)V
  1736. // 31: athrow
  1737. String name = synchronizedMethod.getEnclosingClass().getName();
  1738. prepend.append(fact.createGetStatic(name, fieldname, Type.getType(Class.class)));
  1739. prepend.append(InstructionFactory.createDup(1));
  1740. prepend.append(InstructionFactory.createBranchInstruction(Constants.IFNONNULL, parttwo.getStart()));
  1741. prepend.append(InstructionFactory.POP);
  1742. prepend.append(fact.createConstant(name));
  1743. InstructionHandle tryInstruction = prepend.getEnd();
  1744. prepend.append(fact.createInvoke("java.lang.Class", "forName", clazzType,
  1745. new Type[] { Type.getType(String.class) }, Constants.INVOKESTATIC));
  1746. InstructionHandle catchInstruction = prepend.getEnd();
  1747. prepend.append(InstructionFactory.createDup(1));
  1748. prepend.append(fact.createPutStatic(synchronizedMethod.getEnclosingClass().getType().getName(), fieldname,
  1749. Type.getType(Class.class)));
  1750. prepend.append(InstructionFactory.createBranchInstruction(Constants.GOTO, parttwo.getStart()));
  1751. // start of catch block
  1752. InstructionList catchBlockForLiteralLoadingFail = new InstructionList();
  1753. catchBlockForLiteralLoadingFail.append(fact.createNew((ObjectType) Type.getType(NoClassDefFoundError.class)));
  1754. catchBlockForLiteralLoadingFail.append(InstructionFactory.createDup_1(1));
  1755. catchBlockForLiteralLoadingFail.append(InstructionFactory.SWAP);
  1756. catchBlockForLiteralLoadingFail.append(fact.createInvoke("java.lang.Throwable", "getMessage",
  1757. Type.getType(String.class), new Type[] {}, Constants.INVOKEVIRTUAL));
  1758. catchBlockForLiteralLoadingFail.append(fact.createInvoke("java.lang.NoClassDefFoundError", "<init>", Type.VOID,
  1759. new Type[] { Type.getType(String.class) }, Constants.INVOKESPECIAL));
  1760. catchBlockForLiteralLoadingFail.append(InstructionFactory.ATHROW);
  1761. InstructionHandle catchBlockStart = catchBlockForLiteralLoadingFail.getStart();
  1762. prepend.append(catchBlockForLiteralLoadingFail);
  1763. prepend.append(parttwo);
  1764. // MONITORENTER
  1765. // pseudocode: load up 'this' (var0), dup it, store it in a new
  1766. // local var (for use with monitorexit) and call
  1767. // monitorenter:
  1768. // ALOAD_0, DUP, ASTORE_<n>, MONITORENTER
  1769. // prepend.append(InstructionFactory.createLoad(classType,0));
  1770. // prepend.append(InstructionFactory.createDup(1));
  1771. // int slotForThis =
  1772. // synchronizedMethod.allocateLocal(classType);
  1773. // prepend.append(InstructionFactory.createStore(classType,
  1774. // slotForThis));
  1775. // prepend.append(InstructionFactory.MONITORENTER);
  1776. // MONITOREXIT
  1777. // here be dragons
  1778. // We basically need to wrap the code from the method in a
  1779. // finally block that
  1780. // will ensure monitorexit is called. Content on the finally
  1781. // block seems to
  1782. // be always:
  1783. //
  1784. // E1: ALOAD_1
  1785. // MONITOREXIT
  1786. // ATHROW
  1787. //
  1788. // so lets build that:
  1789. InstructionList finallyBlock = new InstructionList();
  1790. finallyBlock.append(InstructionFactory.createLoad(Type.getType(java.lang.Class.class), slotForThis));
  1791. finallyBlock.append(InstructionConstants.MONITOREXIT);
  1792. finallyBlock.append(InstructionConstants.ATHROW);
  1793. // finally -> E1
  1794. // | GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line
  1795. // 21)
  1796. // | LDC "hello"
  1797. // | INVOKEVIRTUAL java.io.PrintStream.println
  1798. // (Ljava/lang/String;)V
  1799. // | ALOAD_1 (line 20)
  1800. // | MONITOREXIT
  1801. // finally -> E1
  1802. // GOTO L0
  1803. // finally -> E1
  1804. // | E1: ALOAD_1
  1805. // | MONITOREXIT
  1806. // finally -> E1
  1807. // ATHROW
  1808. // L0: RETURN (line 23)
  1809. // frameEnv.put(donorFramePos, thisSlot);
  1810. // search for 'returns' and make them to the
  1811. // aload_<n>,monitorexit
  1812. InstructionHandle walker = body.getStart();
  1813. List<InstructionHandle> rets = new ArrayList<InstructionHandle>();
  1814. while (walker != null) { // !walker.equals(body.getEnd())) {
  1815. if (walker.getInstruction().isReturnInstruction()) {
  1816. rets.add(walker);
  1817. }
  1818. walker = walker.getNext();
  1819. }
  1820. if (rets.size() > 0) {
  1821. // need to ensure targeters for 'return' now instead target
  1822. // the load instruction
  1823. // (so we never jump over the monitorexit logic)
  1824. for (InstructionHandle ret : rets) {
  1825. // System.err.println("Adding monitor exit block at "+
  1826. // element);
  1827. InstructionList monitorExitBlock = new InstructionList();
  1828. monitorExitBlock.append(InstructionFactory.createLoad(classType, slotForThis));
  1829. monitorExitBlock.append(InstructionConstants.MONITOREXIT);
  1830. // monitorExitBlock.append(Utility.copyInstruction(element
  1831. // .getInstruction()));
  1832. // element.setInstruction(InstructionFactory.createLoad(
  1833. // classType,slotForThis));
  1834. InstructionHandle monitorExitBlockStart = body.insert(ret, monitorExitBlock);
  1835. // now move the targeters from the RET to the start of
  1836. // the monitorexit block
  1837. for (InstructionTargeter targeter : ret.getTargetersCopy()) {
  1838. // what kinds are there?
  1839. if (targeter instanceof LocalVariableTag) {
  1840. // ignore
  1841. } else if (targeter instanceof LineNumberTag) {
  1842. // ignore
  1843. // } else if (targeter instanceof GOTO ||
  1844. // targeter instanceof GOTO_W) {
  1845. // // move it...
  1846. // targeter.updateTarget(element,
  1847. // monitorExitBlockStart);
  1848. } else if (targeter instanceof InstructionBranch) {
  1849. // move it
  1850. targeter.updateTarget(ret, monitorExitBlockStart);
  1851. } else {
  1852. throw new BCException("Unexpected targeter encountered during transform: " + targeter);
  1853. }
  1854. }
  1855. }
  1856. }
  1857. // body =
  1858. // rewriteWithMonitorExitCalls(body,fact,true,slotForThis,
  1859. // classType);
  1860. // synchronizedMethod.setBody(body);
  1861. // now the magic, putting the finally block around the code
  1862. InstructionHandle finallyStart = finallyBlock.getStart();
  1863. InstructionHandle tryPosition = body.getStart();
  1864. InstructionHandle catchPosition = body.getEnd();
  1865. body.insert(body.getStart(), prepend); // now we can put the
  1866. // monitorenter stuff on
  1867. synchronizedMethod.getBody().append(finallyBlock);
  1868. synchronizedMethod.addExceptionHandler(tryPosition, catchPosition, finallyStart, null/* ==finally */, false);
  1869. synchronizedMethod.addExceptionHandler(tryInstruction, catchInstruction, catchBlockStart,
  1870. (ObjectType) Type.getType(ClassNotFoundException.class), true);
  1871. synchronizedMethod.addExceptionHandler(finallyStart, finallyStart.getNext(), finallyStart, null, false);
  1872. }
  1873. } else {
  1874. // TRANSFORMING NON STATIC METHOD
  1875. Type classType = BcelWorld.makeBcelType(synchronizedMethod.getEnclosingClass().getType());
  1876. // MONITORENTER
  1877. // pseudocode: load up 'this' (var0), dup it, store it in a new
  1878. // local var (for use with monitorexit) and call
  1879. // monitorenter:
  1880. // ALOAD_0, DUP, ASTORE_<n>, MONITORENTER
  1881. prepend.append(InstructionFactory.createLoad(classType, 0));
  1882. prepend.append(InstructionFactory.createDup(1));
  1883. int slotForThis = synchronizedMethod.allocateLocal(classType);
  1884. prepend.append(InstructionFactory.createStore(classType, slotForThis));
  1885. prepend.append(InstructionFactory.MONITORENTER);
  1886. // body.insert(body.getStart(),prepend);
  1887. // MONITOREXIT
  1888. // We basically need to wrap the code from the method in a finally
  1889. // block that
  1890. // will ensure monitorexit is called. Content on the finally block
  1891. // seems to
  1892. // be always:
  1893. //
  1894. // E1: ALOAD_1
  1895. // MONITOREXIT
  1896. // ATHROW
  1897. //
  1898. // so lets build that:
  1899. InstructionList finallyBlock = new InstructionList();
  1900. finallyBlock.append(InstructionFactory.createLoad(classType, slotForThis));
  1901. finallyBlock.append(InstructionConstants.MONITOREXIT);
  1902. finallyBlock.append(InstructionConstants.ATHROW);
  1903. // finally -> E1
  1904. // | GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 21)
  1905. // | LDC "hello"
  1906. // | INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V
  1907. // | ALOAD_1 (line 20)
  1908. // | MONITOREXIT
  1909. // finally -> E1
  1910. // GOTO L0
  1911. // finally -> E1
  1912. // | E1: ALOAD_1
  1913. // | MONITOREXIT
  1914. // finally -> E1
  1915. // ATHROW
  1916. // L0: RETURN (line 23)
  1917. // frameEnv.put(donorFramePos, thisSlot);
  1918. // search for 'returns' and make them to the aload_<n>,monitorexit
  1919. InstructionHandle walker = body.getStart();
  1920. List<InstructionHandle> rets = new ArrayList<InstructionHandle>();
  1921. while (walker != null) { // !walker.equals(body.getEnd())) {
  1922. if (walker.getInstruction().isReturnInstruction()) {
  1923. rets.add(walker);
  1924. }
  1925. walker = walker.getNext();
  1926. }
  1927. if (!rets.isEmpty()) {
  1928. // need to ensure targeters for 'return' now instead target the
  1929. // load instruction
  1930. // (so we never jump over the monitorexit logic)
  1931. for (Iterator<InstructionHandle> iter = rets.iterator(); iter.hasNext();) {
  1932. InstructionHandle element = iter.next();
  1933. // System.err.println("Adding monitor exit block at "+element
  1934. // );
  1935. InstructionList monitorExitBlock = new InstructionList();
  1936. monitorExitBlock.append(InstructionFactory.createLoad(classType, slotForThis));
  1937. monitorExitBlock.append(InstructionConstants.MONITOREXIT);
  1938. // monitorExitBlock.append(Utility.copyInstruction(element.
  1939. // getInstruction()));
  1940. // element.setInstruction(InstructionFactory.createLoad(
  1941. // classType,slotForThis));
  1942. InstructionHandle monitorExitBlockStart = body.insert(element, monitorExitBlock);
  1943. // now move the targeters from the RET to the start of the
  1944. // monitorexit block
  1945. for (InstructionTargeter targeter : element.getTargetersCopy()) {
  1946. // what kinds are there?
  1947. if (targeter instanceof LocalVariableTag) {
  1948. // ignore
  1949. } else if (targeter instanceof LineNumberTag) {
  1950. // ignore
  1951. // } else if (targeter instanceof GOTO ||
  1952. // targeter instanceof GOTO_W) {
  1953. // // move it...
  1954. // targeter.updateTarget(element,
  1955. // monitorExitBlockStart);
  1956. } else if (targeter instanceof InstructionBranch) {
  1957. // move it
  1958. targeter.updateTarget(element, monitorExitBlockStart);
  1959. } else {
  1960. throw new BCException("Unexpected targeter encountered during transform: " + targeter);
  1961. }
  1962. }
  1963. }
  1964. }
  1965. // now the magic, putting the finally block around the code
  1966. InstructionHandle finallyStart = finallyBlock.getStart();
  1967. InstructionHandle tryPosition = body.getStart();
  1968. InstructionHandle catchPosition = body.getEnd();
  1969. body.insert(body.getStart(), prepend); // now we can put the
  1970. // monitorenter stuff on
  1971. synchronizedMethod.getBody().append(finallyBlock);
  1972. synchronizedMethod.addExceptionHandler(tryPosition, catchPosition, finallyStart, null/* ==finally */, false);
  1973. synchronizedMethod.addExceptionHandler(finallyStart, finallyStart.getNext(), finallyStart, null, false);
  1974. // also the exception handling for the finally block jumps to itself
  1975. // max locals will already have been modified in the allocateLocal()
  1976. // call
  1977. // synchronized bit is removed on LazyMethodGen.pack()
  1978. }
  1979. // gonna have to go through and change all aload_0s to load the var from
  1980. // a variable,
  1981. // going to add a new variable for the this var
  1982. if (trace.isTraceEnabled()) {
  1983. trace.exit("transformSynchronizedMethod");
  1984. }
  1985. }
  1986. /**
  1987. * generate the instructions to be inlined.
  1988. *
  1989. * @param donor the method from which we will copy (and adjust frame and jumps) instructions.
  1990. * @param recipient the method the instructions will go into. Used to get the frame size so we can allocate new frame locations
  1991. * for locals in donor.
  1992. * @param frameEnv an environment to map from donor frame to recipient frame, initially populated with argument locations.
  1993. * @param fact an instruction factory for recipient
  1994. */
  1995. static InstructionList genInlineInstructions(LazyMethodGen donor, LazyMethodGen recipient, IntMap frameEnv,
  1996. InstructionFactory fact, boolean keepReturns) {
  1997. InstructionList footer = new InstructionList();
  1998. InstructionHandle end = footer.append(InstructionConstants.NOP);
  1999. InstructionList ret = new InstructionList();
  2000. InstructionList sourceList = donor.getBody();
  2001. Map<InstructionHandle, InstructionHandle> srcToDest = new HashMap<InstructionHandle, InstructionHandle>();
  2002. ConstantPool donorCpg = donor.getEnclosingClass().getConstantPool();
  2003. ConstantPool recipientCpg = recipient.getEnclosingClass().getConstantPool();
  2004. boolean isAcrossClass = donorCpg != recipientCpg;
  2005. BootstrapMethods bootstrapMethods = null;
  2006. // first pass: copy the instructions directly, populate the srcToDest
  2007. // map,
  2008. // fix frame instructions
  2009. for (InstructionHandle src = sourceList.getStart(); src != null; src = src.getNext()) {
  2010. Instruction fresh = Utility.copyInstruction(src.getInstruction());
  2011. InstructionHandle dest;
  2012. // OPTIMIZE optimize this stuff?
  2013. if (fresh.isConstantPoolInstruction()) {
  2014. // need to reset index to go to new constant pool. This is totally
  2015. // a computation leak... we're testing this LOTS of times. Sigh.
  2016. if (isAcrossClass) {
  2017. InstructionCP cpi = (InstructionCP) fresh;
  2018. cpi.setIndex(recipientCpg.addConstant(donorCpg.getConstant(cpi.getIndex()), donorCpg));
  2019. }
  2020. // May need to copy bootstrapmethods across too.
  2021. // if (fresh instanceof InvokeDynamic) {
  2022. // InvokeDynamic id = (InvokeDynamic)fresh;
  2023. // ConstantInvokeDynamic cid = (ConstantInvokeDynamic)donorCpg.getConstant(src.getInstruction().getIndex());
  2024. // int bmaIndex = cid.getBootstrapMethodAttrIndex();
  2025. // if (bootstrapMethods == null) {
  2026. // Collection<Attribute> attributes = donor.getEnclosingClass().getAttributes();
  2027. // if (attributes != null) {
  2028. // for (Attribute attribute: attributes) {
  2029. // if (attribute instanceof BootstrapMethods) {
  2030. // bootstrapMethods = (BootstrapMethods)attribute;
  2031. // }
  2032. // }
  2033. // }
  2034. // BootstrapMethods.BootstrapMethod bootstrapMethod =
  2035. // bootstrapMethods.getBootstrapMethods()[bmaIndex];
  2036. // ConstantMethodHandle methodhandle = (ConstantMethodHandle)donorCpg.getConstant(bootstrapMethod.getBootstrapMethodRef());
  2037. // int bootstrapMethodArguments[] = bootstrapMethod.getBootstrapArguments();
  2038. //
  2039. // // Finally have all we need to build the new one...
  2040. //
  2041. // int newMethodHandleIndex = recipientCpg.addConstant(methodhandle, donorCpg);
  2042. // int[] newMethodArguments = new int[bootstrapMethodArguments.length];
  2043. // for (int a=0; a<bootstrapMethodArguments.length; a++) {
  2044. // newMethodArguments[a] = recipientCpg.addConstant(donorCpg.getConstant(bootstrapMethodArguments[a]),donorCpg);
  2045. // }
  2046. // BootstrapMethods.BootstrapMethod newBootstrapMethod =
  2047. // new BootstrapMethods.BootstrapMethod(newMethodHandleIndex,newMethodArguments);
  2048. //
  2049. // Collection<Attribute> newAttributes = recipient.getEnclosingClass().getAttributes();
  2050. // BootstrapMethods newBootstrapMethods = null;
  2051. // for (Attribute attr: newAttributes) {
  2052. // if (attr instanceof BootstrapMethods) {
  2053. // newBootstrapMethods = (BootstrapMethods)newBootstrapMethods;
  2054. // }
  2055. // }
  2056. // if (newBootstrapMethods == null) {
  2057. // newBootstrapMethods =
  2058. // new BootstrapMethods(recipientCpg.addUtf8("BootstrapMethods"),
  2059. // 2+newBootstrapMethod.getLength(),
  2060. // new BootstrapMethods.BootstrapMethod[] {newBootstrapMethod},
  2061. // recipientCpg);
  2062. // recipient.getEnclosingClass().addAttribute(newBootstrapMethods);
  2063. // }
  2064. // TODO need to copy over lambda$0 support methods too...
  2065. // }
  2066. //
  2067. // }
  2068. }
  2069. if (src.getInstruction() == Range.RANGEINSTRUCTION) {
  2070. dest = ret.append(Range.RANGEINSTRUCTION);
  2071. } else if (fresh.isReturnInstruction()) {
  2072. if (keepReturns) {
  2073. dest = ret.append(fresh);
  2074. } else {
  2075. dest = ret.append(InstructionFactory.createBranchInstruction(Constants.GOTO, end));
  2076. }
  2077. } else if (fresh instanceof InstructionBranch) {
  2078. dest = ret.append((InstructionBranch) fresh);
  2079. } else if (fresh.isLocalVariableInstruction() || fresh instanceof RET) {
  2080. // IndexedInstruction indexed = (IndexedInstruction) fresh;
  2081. int oldIndex = fresh.getIndex();
  2082. int freshIndex;
  2083. if (!frameEnv.hasKey(oldIndex)) {
  2084. freshIndex = recipient.allocateLocal(2);
  2085. frameEnv.put(oldIndex, freshIndex);
  2086. } else {
  2087. freshIndex = frameEnv.get(oldIndex);
  2088. }
  2089. if (fresh instanceof RET) {
  2090. fresh.setIndex(freshIndex);
  2091. } else {
  2092. fresh = ((InstructionLV) fresh).setIndexAndCopyIfNecessary(freshIndex);
  2093. }
  2094. dest = ret.append(fresh);
  2095. } else {
  2096. dest = ret.append(fresh);
  2097. }
  2098. srcToDest.put(src, dest);
  2099. }
  2100. // second pass: retarget branch instructions, copy ranges and tags
  2101. Map<Tag, Tag> tagMap = new HashMap<Tag, Tag>();
  2102. Map<BcelShadow, BcelShadow> shadowMap = new HashMap<BcelShadow, BcelShadow>();
  2103. for (InstructionHandle dest = ret.getStart(), src = sourceList.getStart(); dest != null; dest = dest.getNext(), src = src
  2104. .getNext()) {
  2105. Instruction inst = dest.getInstruction();
  2106. // retarget branches
  2107. if (inst instanceof InstructionBranch) {
  2108. InstructionBranch branch = (InstructionBranch) inst;
  2109. InstructionHandle oldTarget = branch.getTarget();
  2110. InstructionHandle newTarget = srcToDest.get(oldTarget);
  2111. if (newTarget == null) {
  2112. // assert this is a GOTO
  2113. // this was a return instruction we previously replaced
  2114. } else {
  2115. branch.setTarget(newTarget);
  2116. if (branch instanceof InstructionSelect) {
  2117. InstructionSelect select = (InstructionSelect) branch;
  2118. InstructionHandle[] oldTargets = select.getTargets();
  2119. for (int k = oldTargets.length - 1; k >= 0; k--) {
  2120. select.setTarget(k, srcToDest.get(oldTargets[k]));
  2121. }
  2122. }
  2123. }
  2124. }
  2125. // copy over tags and range attributes
  2126. Iterator<InstructionTargeter> tIter = src.getTargeters().iterator();
  2127. while (tIter.hasNext()) {
  2128. InstructionTargeter old = tIter.next();
  2129. if (old instanceof Tag) {
  2130. Tag oldTag = (Tag) old;
  2131. Tag fresh = tagMap.get(oldTag);
  2132. if (fresh == null) {
  2133. fresh = oldTag.copy();
  2134. if (old instanceof LocalVariableTag) {
  2135. // LocalVariable
  2136. LocalVariableTag lvTag = (LocalVariableTag) old;
  2137. LocalVariableTag lvTagFresh = (LocalVariableTag) fresh;
  2138. if (lvTag.getSlot() == 0) {
  2139. fresh = new LocalVariableTag(lvTag.getRealType().getSignature(), "ajc$aspectInstance",
  2140. frameEnv.get(lvTag.getSlot()), 0);
  2141. } else {
  2142. // // Do not move it - when copying the code from the aspect to the affected target, 'this' is
  2143. // // going to change from aspect to affected type. So just fix the type
  2144. // System.out.println("For local variable tag at instruction " + src + " changing slot from "
  2145. // + lvTag.getSlot() + " > " + frameEnv.get(lvTag.getSlot()));
  2146. lvTagFresh.updateSlot(frameEnv.get(lvTag.getSlot()));
  2147. }
  2148. }
  2149. tagMap.put(oldTag, fresh);
  2150. }
  2151. dest.addTargeter(fresh);
  2152. } else if (old instanceof ExceptionRange) {
  2153. ExceptionRange er = (ExceptionRange) old;
  2154. if (er.getStart() == src) {
  2155. ExceptionRange freshEr = new ExceptionRange(recipient.getBody(), er.getCatchType(), er.getPriority());
  2156. freshEr.associateWithTargets(dest, srcToDest.get(er.getEnd()), srcToDest.get(er.getHandler()));
  2157. }
  2158. } else if (old instanceof ShadowRange) {
  2159. ShadowRange oldRange = (ShadowRange) old;
  2160. if (oldRange.getStart() == src) {
  2161. BcelShadow oldShadow = oldRange.getShadow();
  2162. BcelShadow freshEnclosing = oldShadow.getEnclosingShadow() == null ? null : (BcelShadow) shadowMap
  2163. .get(oldShadow.getEnclosingShadow());
  2164. BcelShadow freshShadow = oldShadow.copyInto(recipient, freshEnclosing);
  2165. ShadowRange freshRange = new ShadowRange(recipient.getBody());
  2166. freshRange.associateWithShadow(freshShadow);
  2167. freshRange.associateWithTargets(dest, srcToDest.get(oldRange.getEnd()));
  2168. shadowMap.put(oldShadow, freshShadow); // oldRange, freshRange
  2169. // recipient.matchedShadows.add(freshShadow);
  2170. // XXX should go through the NEW copied shadow and
  2171. // update
  2172. // the thisVar, targetVar, and argsVar
  2173. // ??? Might want to also go through at this time and
  2174. // add
  2175. // "extra" vars to the shadow.
  2176. }
  2177. }
  2178. }
  2179. }
  2180. if (!keepReturns) {
  2181. ret.append(footer);
  2182. }
  2183. return ret;
  2184. }
  2185. // static InstructionList rewriteWithMonitorExitCalls(InstructionList
  2186. // sourceList,InstructionFactory fact,boolean keepReturns,int
  2187. // monitorVarSlot,Type monitorVarType)
  2188. // {
  2189. // InstructionList footer = new InstructionList();
  2190. // InstructionHandle end = footer.append(InstructionConstants.NOP);
  2191. //
  2192. // InstructionList newList = new InstructionList();
  2193. //
  2194. // Map srcToDest = new HashMap();
  2195. //
  2196. // // first pass: copy the instructions directly, populate the srcToDest
  2197. // map,
  2198. // // fix frame instructions
  2199. // for (InstructionHandle src = sourceList.getStart(); src != null; src =
  2200. // src.getNext()) {
  2201. // Instruction fresh = Utility.copyInstruction(src.getInstruction());
  2202. // InstructionHandle dest;
  2203. // if (src.getInstruction() == Range.RANGEINSTRUCTION) {
  2204. // dest = newList.append(Range.RANGEINSTRUCTION);
  2205. // } else if (fresh.isReturnInstruction()) {
  2206. // if (keepReturns) {
  2207. // newList.append(InstructionFactory.createLoad(monitorVarType,monitorVarSlot
  2208. // ));
  2209. // newList.append(InstructionConstants.MONITOREXIT);
  2210. // dest = newList.append(fresh);
  2211. // } else {
  2212. // dest =
  2213. // newList.append(InstructionFactory.createBranchInstruction(Constants.GOTO,
  2214. // end));
  2215. // }
  2216. // } else if (fresh instanceof InstructionBranch) {
  2217. // dest = newList.append((InstructionBranch) fresh);
  2218. // } else if (
  2219. // fresh.isLocalVariableInstruction() || fresh instanceof RET) {
  2220. // //IndexedInstruction indexed = (IndexedInstruction) fresh;
  2221. // int oldIndex = fresh.getIndex();
  2222. // int freshIndex;
  2223. // // if (!frameEnv.hasKey(oldIndex)) {
  2224. // // freshIndex = recipient.allocateLocal(2);
  2225. // // frameEnv.put(oldIndex, freshIndex);
  2226. // // } else {
  2227. // freshIndex = oldIndex;//frameEnv.get(oldIndex);
  2228. // // }
  2229. // if (fresh instanceof RET) {
  2230. // fresh.setIndex(freshIndex);
  2231. // } else {
  2232. // fresh = ((InstructionLV)fresh).setIndexAndCopyIfNecessary(freshIndex);
  2233. // }
  2234. // dest = newList.append(fresh);
  2235. // } else {
  2236. // dest = newList.append(fresh);
  2237. // }
  2238. // srcToDest.put(src, dest);
  2239. // }
  2240. //
  2241. // // second pass: retarget branch instructions, copy ranges and tags
  2242. // Map tagMap = new HashMap();
  2243. // for (InstructionHandle dest = newList.getStart(), src =
  2244. // sourceList.getStart();
  2245. // dest != null;
  2246. // dest = dest.getNext(), src = src.getNext()) {
  2247. // Instruction inst = dest.getInstruction();
  2248. //
  2249. // // retarget branches
  2250. // if (inst instanceof InstructionBranch) {
  2251. // InstructionBranch branch = (InstructionBranch) inst;
  2252. // InstructionHandle oldTarget = branch.getTarget();
  2253. // InstructionHandle newTarget =
  2254. // (InstructionHandle) srcToDest.get(oldTarget);
  2255. // if (newTarget == null) {
  2256. // // assert this is a GOTO
  2257. // // this was a return instruction we previously replaced
  2258. // } else {
  2259. // branch.setTarget(newTarget);
  2260. // if (branch instanceof InstructionSelect) {
  2261. // InstructionSelect select = (InstructionSelect) branch;
  2262. // InstructionHandle[] oldTargets = select.getTargets();
  2263. // for (int k = oldTargets.length - 1; k >= 0; k--) {
  2264. // select.setTarget(
  2265. // k,
  2266. // (InstructionHandle) srcToDest.get(oldTargets[k]));
  2267. // }
  2268. // }
  2269. // }
  2270. // }
  2271. //
  2272. // //copy over tags and range attributes
  2273. // Iterator tIter = src.getTargeters().iterator();
  2274. //
  2275. // while (tIter.hasNext()) {
  2276. // InstructionTargeter old = (InstructionTargeter)tIter.next();
  2277. // if (old instanceof Tag) {
  2278. // Tag oldTag = (Tag) old;
  2279. // Tag fresh = (Tag) tagMap.get(oldTag);
  2280. // if (fresh == null) {
  2281. // fresh = oldTag.copy();
  2282. // tagMap.put(oldTag, fresh);
  2283. // }
  2284. // dest.addTargeter(fresh);
  2285. // } else if (old instanceof ExceptionRange) {
  2286. // ExceptionRange er = (ExceptionRange) old;
  2287. // if (er.getStart() == src) {
  2288. // ExceptionRange freshEr =
  2289. // new ExceptionRange(newList/*recipient.getBody()*/,er.getCatchType(),er.
  2290. // getPriority());
  2291. // freshEr.associateWithTargets(
  2292. // dest,
  2293. // (InstructionHandle)srcToDest.get(er.getEnd()),
  2294. // (InstructionHandle)srcToDest.get(er.getHandler()));
  2295. // }
  2296. // }
  2297. // /*else if (old instanceof ShadowRange) {
  2298. // ShadowRange oldRange = (ShadowRange) old;
  2299. // if (oldRange.getStart() == src) {
  2300. // BcelShadow oldShadow = oldRange.getShadow();
  2301. // BcelShadow freshEnclosing =
  2302. // oldShadow.getEnclosingShadow() == null
  2303. // ? null
  2304. // : (BcelShadow) shadowMap.get(oldShadow.getEnclosingShadow());
  2305. // BcelShadow freshShadow =
  2306. // oldShadow.copyInto(recipient, freshEnclosing);
  2307. // ShadowRange freshRange = new ShadowRange(recipient.getBody());
  2308. // freshRange.associateWithShadow(freshShadow);
  2309. // freshRange.associateWithTargets(
  2310. // dest,
  2311. // (InstructionHandle) srcToDest.get(oldRange.getEnd()));
  2312. // shadowMap.put(oldRange, freshRange);
  2313. // //recipient.matchedShadows.add(freshShadow);
  2314. // // XXX should go through the NEW copied shadow and update
  2315. // // the thisVar, targetVar, and argsVar
  2316. // // ??? Might want to also go through at this time and add
  2317. // // "extra" vars to the shadow.
  2318. // }
  2319. // }*/
  2320. // }
  2321. // }
  2322. // if (!keepReturns) newList.append(footer);
  2323. // return newList;
  2324. // }
  2325. /**
  2326. * generate the argument stores in preparation for inlining.
  2327. *
  2328. * @param donor the method we will inline from. Used to get the signature.
  2329. * @param recipient the method we will inline into. Used to get the frame size so we can allocate fresh locations.
  2330. * @param frameEnv an empty environment we populate with a map from donor frame to recipient frame.
  2331. * @param fact an instruction factory for recipient
  2332. */
  2333. private static InstructionList genArgumentStores(LazyMethodGen donor, LazyMethodGen recipient, IntMap frameEnv,
  2334. InstructionFactory fact) {
  2335. InstructionList ret = new InstructionList();
  2336. int donorFramePos = 0;
  2337. // writing ret back to front because we're popping.
  2338. if (!donor.isStatic()) {
  2339. int targetSlot = recipient.allocateLocal(Type.OBJECT);
  2340. ret.insert(InstructionFactory.createStore(Type.OBJECT, targetSlot));
  2341. frameEnv.put(donorFramePos, targetSlot);
  2342. donorFramePos += 1;
  2343. }
  2344. Type[] argTypes = donor.getArgumentTypes();
  2345. for (int i = 0, len = argTypes.length; i < len; i++) {
  2346. Type argType = argTypes[i];
  2347. int argSlot = recipient.allocateLocal(argType);
  2348. ret.insert(InstructionFactory.createStore(argType, argSlot));
  2349. frameEnv.put(donorFramePos, argSlot);
  2350. donorFramePos += argType.getSize();
  2351. }
  2352. return ret;
  2353. }
  2354. /**
  2355. * get a called method: Assumes the called method is in this class, and the reference to it is exact (a la INVOKESPECIAL).
  2356. *
  2357. * @param ih The InvokeInstruction instructionHandle pointing to the called method.
  2358. */
  2359. private LazyMethodGen getCalledMethod(InstructionHandle ih) {
  2360. InvokeInstruction inst = (InvokeInstruction) ih.getInstruction();
  2361. String methodName = inst.getName(cpg);
  2362. String signature = inst.getSignature(cpg);
  2363. return clazz.getLazyMethodGen(methodName, signature);
  2364. }
  2365. private void weaveInAddedMethods() {
  2366. Collections.sort(addedLazyMethodGens, new Comparator<LazyMethodGen>() {
  2367. public int compare(LazyMethodGen aa, LazyMethodGen bb) {
  2368. int i = aa.getName().compareTo(bb.getName());
  2369. if (i != 0) {
  2370. return i;
  2371. }
  2372. return aa.getSignature().compareTo(bb.getSignature());
  2373. }
  2374. });
  2375. for (LazyMethodGen addedMember : addedLazyMethodGens) {
  2376. clazz.addMethodGen(addedMember);
  2377. }
  2378. }
  2379. // void addPerSingletonField(Member field) {
  2380. // ObjectType aspectType = (ObjectType)
  2381. // BcelWorld.makeBcelType(field.getReturnType());
  2382. // String aspectName = field.getReturnType().getName();
  2383. //
  2384. // LazyMethodGen clinit = clazz.getStaticInitializer();
  2385. // InstructionList setup = new InstructionList();
  2386. // InstructionFactory fact = clazz.getFactory();
  2387. //
  2388. // setup.append(fact.createNew(aspectType));
  2389. // setup.append(InstructionFactory.createDup(1));
  2390. // setup.append(fact.createInvoke(aspectName, "<init>", Type.VOID, new
  2391. // Type[0], Constants.INVOKESPECIAL));
  2392. // setup.append(fact.createFieldAccess(aspectName, field.getName(),
  2393. // aspectType, Constants.PUTSTATIC));
  2394. // clinit.getBody().insert(setup);
  2395. // }
  2396. /**
  2397. * Returns null if this is not a Java constructor, and then we won't weave into it at all
  2398. */
  2399. private InstructionHandle findSuperOrThisCall(LazyMethodGen mg) {
  2400. int depth = 1;
  2401. InstructionHandle start = mg.getBody().getStart();
  2402. while (true) {
  2403. if (start == null) {
  2404. return null;
  2405. }
  2406. Instruction inst = start.getInstruction();
  2407. if (inst.opcode == Constants.INVOKESPECIAL && ((InvokeInstruction) inst).getName(cpg).equals("<init>")) {
  2408. depth--;
  2409. if (depth == 0) {
  2410. return start;
  2411. }
  2412. } else if (inst.opcode == Constants.NEW) {
  2413. depth++;
  2414. }
  2415. start = start.getNext();
  2416. }
  2417. }
  2418. // ----
  2419. private boolean match(LazyMethodGen mg) {
  2420. BcelShadow enclosingShadow;
  2421. List<BcelShadow> shadowAccumulator = new ArrayList<BcelShadow>();
  2422. boolean isOverweaving = world.isOverWeaving();
  2423. boolean startsAngly = mg.getName().charAt(0) == '<';
  2424. // we want to match ajsynthetic constructors...
  2425. if (startsAngly && mg.getName().equals("<init>")) {
  2426. return matchInit(mg, shadowAccumulator);
  2427. } else if (!shouldWeaveBody(mg)) {
  2428. return false;
  2429. } else {
  2430. if (startsAngly && mg.getName().equals("<clinit>")) {
  2431. // clinitShadow =
  2432. enclosingShadow = BcelShadow.makeStaticInitialization(world, mg);
  2433. // System.err.println(enclosingShadow);
  2434. } else if (mg.isAdviceMethod()) {
  2435. enclosingShadow = BcelShadow.makeAdviceExecution(world, mg);
  2436. } else {
  2437. AjAttribute.EffectiveSignatureAttribute effective = mg.getEffectiveSignature();
  2438. if (effective == null) {
  2439. // Don't want ajc$preClinit to be considered for matching
  2440. if (isOverweaving && mg.getName().startsWith(NameMangler.PREFIX)) {
  2441. return false;
  2442. }
  2443. enclosingShadow = BcelShadow.makeMethodExecution(world, mg, !canMatchBodyShadows);
  2444. } else if (effective.isWeaveBody()) {
  2445. ResolvedMember rm = effective.getEffectiveSignature();
  2446. // Annotations for things with effective signatures are
  2447. // never stored in the effective
  2448. // signature itself - we have to hunt for them. Storing them
  2449. // in the effective signature
  2450. // would mean keeping two sets up to date (no way!!)
  2451. fixParameterNamesForResolvedMember(rm, mg.getMemberView());
  2452. fixAnnotationsForResolvedMember(rm, mg.getMemberView());
  2453. enclosingShadow = BcelShadow.makeShadowForMethod(world, mg, effective.getShadowKind(), rm);
  2454. } else {
  2455. return false;
  2456. }
  2457. }
  2458. if (canMatchBodyShadows) {
  2459. for (InstructionHandle h = mg.getBody().getStart(); h != null; h = h.getNext()) {
  2460. match(mg, h, enclosingShadow, shadowAccumulator);
  2461. }
  2462. }
  2463. // FIXME asc change from string match if we can, rather brittle.
  2464. // this check actually prevents field-exec jps
  2465. if (canMatch(enclosingShadow.getKind())
  2466. && !(mg.getName().charAt(0) == 'a' && mg.getName().startsWith("ajc$interFieldInit"))) {
  2467. if (match(enclosingShadow, shadowAccumulator)) {
  2468. enclosingShadow.init();
  2469. }
  2470. }
  2471. mg.matchedShadows = shadowAccumulator;
  2472. return !shadowAccumulator.isEmpty();
  2473. }
  2474. }
  2475. private boolean matchInit(LazyMethodGen mg, List<BcelShadow> shadowAccumulator) {
  2476. BcelShadow enclosingShadow;
  2477. // XXX the enclosing join point is wrong for things before ignoreMe.
  2478. InstructionHandle superOrThisCall = findSuperOrThisCall(mg);
  2479. // we don't walk bodies of things where it's a wrong constructor thingie
  2480. if (superOrThisCall == null) {
  2481. return false;
  2482. }
  2483. enclosingShadow = BcelShadow.makeConstructorExecution(world, mg, superOrThisCall);
  2484. if (mg.getEffectiveSignature() != null) {
  2485. enclosingShadow.setMatchingSignature(mg.getEffectiveSignature().getEffectiveSignature());
  2486. }
  2487. // walk the body
  2488. boolean beforeSuperOrThisCall = true;
  2489. if (shouldWeaveBody(mg)) {
  2490. if (canMatchBodyShadows) {
  2491. for (InstructionHandle h = mg.getBody().getStart(); h != null; h = h.getNext()) {
  2492. if (h == superOrThisCall) {
  2493. beforeSuperOrThisCall = false;
  2494. continue;
  2495. }
  2496. match(mg, h, beforeSuperOrThisCall ? null : enclosingShadow, shadowAccumulator);
  2497. }
  2498. }
  2499. if (canMatch(Shadow.ConstructorExecution)) {
  2500. match(enclosingShadow, shadowAccumulator);
  2501. }
  2502. }
  2503. // XXX we don't do pre-inits of interfaces
  2504. // now add interface inits
  2505. if (!isThisCall(superOrThisCall)) {
  2506. InstructionHandle curr = enclosingShadow.getRange().getStart();
  2507. for (Iterator<IfaceInitList> i = addedSuperInitializersAsList.iterator(); i.hasNext();) {
  2508. IfaceInitList l = i.next();
  2509. Member ifaceInitSig = AjcMemberMaker.interfaceConstructor(l.onType);
  2510. BcelShadow initShadow = BcelShadow.makeIfaceInitialization(world, mg, ifaceInitSig);
  2511. // insert code in place
  2512. InstructionList inits = genInitInstructions(l.list, false);
  2513. if (match(initShadow, shadowAccumulator) || !inits.isEmpty()) {
  2514. initShadow.initIfaceInitializer(curr);
  2515. initShadow.getRange().insert(inits, Range.OutsideBefore);
  2516. }
  2517. }
  2518. // now we add our initialization code
  2519. InstructionList inits = genInitInstructions(addedThisInitializers, false);
  2520. enclosingShadow.getRange().insert(inits, Range.OutsideBefore);
  2521. }
  2522. // actually, you only need to inline the self constructors that are
  2523. // in a particular group (partition the constructors into groups where
  2524. // members
  2525. // call or are called only by those in the group). Then only inline
  2526. // constructors
  2527. // in groups where at least one initialization jp matched. Future work.
  2528. boolean addedInitialization = match(BcelShadow.makeUnfinishedInitialization(world, mg), initializationShadows);
  2529. addedInitialization |= match(BcelShadow.makeUnfinishedPreinitialization(world, mg), initializationShadows);
  2530. mg.matchedShadows = shadowAccumulator;
  2531. return addedInitialization || !shadowAccumulator.isEmpty();
  2532. }
  2533. private boolean shouldWeaveBody(LazyMethodGen mg) {
  2534. if (mg.isBridgeMethod()) {
  2535. return false;
  2536. }
  2537. if (mg.isAjSynthetic()) {
  2538. return mg.getName().equals("<clinit>");
  2539. }
  2540. AjAttribute.EffectiveSignatureAttribute a = mg.getEffectiveSignature();
  2541. if (a != null) {
  2542. return a.isWeaveBody();
  2543. }
  2544. return true;
  2545. }
  2546. /**
  2547. * first sorts the mungers, then gens the initializers in the right order
  2548. */
  2549. private InstructionList genInitInstructions(List<ConcreteTypeMunger> list, boolean isStatic) {
  2550. list = PartialOrder.sort(list);
  2551. if (list == null) {
  2552. throw new BCException("circularity in inter-types");
  2553. }
  2554. InstructionList ret = new InstructionList();
  2555. for (ConcreteTypeMunger cmunger : list) {
  2556. NewFieldTypeMunger munger = (NewFieldTypeMunger) cmunger.getMunger();
  2557. ResolvedMember initMethod = munger.getInitMethod(cmunger.getAspectType());
  2558. if (!isStatic) {
  2559. ret.append(InstructionConstants.ALOAD_0);
  2560. }
  2561. ret.append(Utility.createInvoke(fact, world, initMethod));
  2562. }
  2563. return ret;
  2564. }
  2565. private void match(LazyMethodGen mg, InstructionHandle ih, BcelShadow enclosingShadow, List<BcelShadow> shadowAccumulator) {
  2566. Instruction i = ih.getInstruction();
  2567. // Exception handlers (pr230817)
  2568. if (canMatch(Shadow.ExceptionHandler) && !Range.isRangeHandle(ih)) {
  2569. Set<InstructionTargeter> targeters = ih.getTargetersCopy();
  2570. // If in Java7 there may be overlapping exception ranges for multi catch - we should recognize that
  2571. for (InstructionTargeter t : targeters) {
  2572. if (t instanceof ExceptionRange) {
  2573. // assert t.getHandler() == ih
  2574. ExceptionRange er = (ExceptionRange) t;
  2575. if (er.getCatchType() == null) {
  2576. continue;
  2577. }
  2578. if (isInitFailureHandler(ih)) {
  2579. return;
  2580. }
  2581. if (!ih.getInstruction().isStoreInstruction() && ih.getInstruction().getOpcode() != Constants.NOP) {
  2582. // If using cobertura, the catch block stats with
  2583. // INVOKESTATIC rather than ASTORE, in order that the ranges
  2584. // for the methodcall and exceptionhandler shadows
  2585. // that occur at this same
  2586. // line, we need to modify the instruction list to
  2587. // split them - adding a
  2588. // NOP before the invokestatic that gets all the targeters
  2589. // that were aimed at the INVOKESTATIC
  2590. mg.getBody().insert(ih, InstructionConstants.NOP);
  2591. InstructionHandle newNOP = ih.getPrev();
  2592. // what about a try..catch that starts at the start
  2593. // of the exception handler? need to only include
  2594. // certain targeters really.
  2595. er.updateTarget(ih, newNOP, mg.getBody());
  2596. for (InstructionTargeter t2 : targeters) {
  2597. newNOP.addTargeter(t2);
  2598. }
  2599. ih.removeAllTargeters();
  2600. match(BcelShadow.makeExceptionHandler(world, er, mg, newNOP, enclosingShadow), shadowAccumulator);
  2601. } else {
  2602. match(BcelShadow.makeExceptionHandler(world, er, mg, ih, enclosingShadow), shadowAccumulator);
  2603. }
  2604. }
  2605. }
  2606. }
  2607. if ((i instanceof FieldInstruction) && (canMatch(Shadow.FieldGet) || canMatch(Shadow.FieldSet))) {
  2608. FieldInstruction fi = (FieldInstruction) i;
  2609. if (fi.opcode == Constants.PUTFIELD || fi.opcode == Constants.PUTSTATIC) {
  2610. // check for sets of constant fields. We first check the
  2611. // previous
  2612. // instruction. If the previous instruction is a LD_WHATEVER
  2613. // (push
  2614. // constant on the stack) then we must resolve the field to
  2615. // determine
  2616. // if it's final. If it is final, then we don't generate a
  2617. // shadow.
  2618. InstructionHandle prevHandle = ih.getPrev();
  2619. Instruction prevI = prevHandle.getInstruction();
  2620. if (Utility.isConstantPushInstruction(prevI)) {
  2621. Member field = BcelWorld.makeFieldJoinPointSignature(clazz, (FieldInstruction) i);
  2622. ResolvedMember resolvedField = field.resolve(world);
  2623. if (resolvedField == null) {
  2624. // we can't find the field, so it's not a join point.
  2625. } else if (Modifier.isFinal(resolvedField.getModifiers())) {
  2626. // it's final, so it's the set of a final constant, so
  2627. // it's
  2628. // not a join point according to 1.0.6 and 1.1.
  2629. } else {
  2630. if (canMatch(Shadow.FieldSet)) {
  2631. matchSetInstruction(mg, ih, enclosingShadow, shadowAccumulator);
  2632. }
  2633. }
  2634. } else {
  2635. if (canMatch(Shadow.FieldSet)) {
  2636. matchSetInstruction(mg, ih, enclosingShadow, shadowAccumulator);
  2637. }
  2638. }
  2639. } else {
  2640. if (canMatch(Shadow.FieldGet)) {
  2641. matchGetInstruction(mg, ih, enclosingShadow, shadowAccumulator);
  2642. }
  2643. }
  2644. } else if (i instanceof InvokeInstruction) {
  2645. InvokeInstruction ii = (InvokeInstruction) i;
  2646. if (ii.getMethodName(clazz.getConstantPool()).equals("<init>")) {
  2647. if (canMatch(Shadow.ConstructorCall)) {
  2648. match(BcelShadow.makeConstructorCall(world, mg, ih, enclosingShadow), shadowAccumulator);
  2649. }
  2650. } else if (ii.opcode == Constants.INVOKESPECIAL) {
  2651. String onTypeName = ii.getClassName(cpg);
  2652. if (onTypeName.equals(mg.getEnclosingClass().getName())) {
  2653. // we are private
  2654. matchInvokeInstruction(mg, ih, ii, enclosingShadow, shadowAccumulator);
  2655. } else {
  2656. // we are a super call, and this is not a join point in
  2657. // AspectJ-1.{0,1}
  2658. }
  2659. } else {
  2660. if (ii.getOpcode()!=Constants.INVOKEDYNAMIC) {
  2661. matchInvokeInstruction(mg, ih, ii, enclosingShadow, shadowAccumulator);
  2662. }
  2663. }
  2664. } else if (world.isJoinpointArrayConstructionEnabled() && i.isArrayCreationInstruction()) {
  2665. if (canMatch(Shadow.ConstructorCall)) {
  2666. if (i.opcode == Constants.ANEWARRAY) {
  2667. // ANEWARRAY arrayInstruction = (ANEWARRAY)i;
  2668. // ObjectType arrayType = i.getLoadClassType(clazz.getConstantPool());
  2669. BcelShadow ctorCallShadow = BcelShadow.makeArrayConstructorCall(world, mg, ih, enclosingShadow);
  2670. match(ctorCallShadow, shadowAccumulator);
  2671. } else if (i.opcode == Constants.NEWARRAY) {
  2672. // NEWARRAY arrayInstruction = (NEWARRAY)i;
  2673. // Type arrayType = i.getType();
  2674. BcelShadow ctorCallShadow = BcelShadow.makeArrayConstructorCall(world, mg, ih, enclosingShadow);
  2675. match(ctorCallShadow, shadowAccumulator);
  2676. } else if (i instanceof MULTIANEWARRAY) {
  2677. // MULTIANEWARRAY arrayInstruction = (MULTIANEWARRAY) i;
  2678. // ObjectType arrayType = arrayInstruction.getLoadClassType(clazz.getConstantPool());
  2679. BcelShadow ctorCallShadow = BcelShadow.makeArrayConstructorCall(world, mg, ih, enclosingShadow);
  2680. match(ctorCallShadow, shadowAccumulator);
  2681. }
  2682. }
  2683. // see pr77166 if you are thinking about implementing this
  2684. // } else if (i instanceof AALOAD ) {
  2685. // AALOAD arrayLoad = (AALOAD)i;
  2686. // Type arrayType = arrayLoad.getType(clazz.getConstantPoolGen());
  2687. // BcelShadow arrayLoadShadow =
  2688. // BcelShadow.makeArrayLoadCall(world,mg,ih,enclosingShadow);
  2689. // match(arrayLoadShadow,shadowAccumulator);
  2690. // } else if (i instanceof AASTORE) {
  2691. // // ... magic required
  2692. } else if (world.isJoinpointSynchronizationEnabled()
  2693. && ((i.getOpcode() == Constants.MONITORENTER) || (i.getOpcode() == Constants.MONITOREXIT))) {
  2694. // if (canMatch(Shadow.Monitoring)) {
  2695. if (i.getOpcode() == Constants.MONITORENTER) {
  2696. BcelShadow monitorEntryShadow = BcelShadow.makeMonitorEnter(world, mg, ih, enclosingShadow);
  2697. match(monitorEntryShadow, shadowAccumulator);
  2698. } else {
  2699. BcelShadow monitorExitShadow = BcelShadow.makeMonitorExit(world, mg, ih, enclosingShadow);
  2700. match(monitorExitShadow, shadowAccumulator);
  2701. }
  2702. // }
  2703. }
  2704. }
  2705. private boolean isInitFailureHandler(InstructionHandle ih) {
  2706. // Skip the astore_0 and aload_0 at the start of the handler and
  2707. // then check if the instruction following these is
  2708. // 'putstatic ajc$initFailureCause'. If it is then we are
  2709. // in the handler we created in AspectClinit.generatePostSyntheticCode()
  2710. InstructionHandle twoInstructionsAway = ih.getNext().getNext();
  2711. if (twoInstructionsAway.getInstruction().opcode == Constants.PUTSTATIC) {
  2712. String name = ((FieldInstruction) twoInstructionsAway.getInstruction()).getFieldName(cpg);
  2713. if (name.equals(NameMangler.INITFAILURECAUSE_FIELD_NAME)) {
  2714. return true;
  2715. }
  2716. }
  2717. return false;
  2718. }
  2719. private void matchSetInstruction(LazyMethodGen mg, InstructionHandle ih, BcelShadow enclosingShadow,
  2720. List<BcelShadow> shadowAccumulator) {
  2721. FieldInstruction fi = (FieldInstruction) ih.getInstruction();
  2722. Member field = BcelWorld.makeFieldJoinPointSignature(clazz, fi);
  2723. // synthetic fields are never join points
  2724. if (field.getName().startsWith(NameMangler.PREFIX)) {
  2725. return;
  2726. }
  2727. ResolvedMember resolvedField = field.resolve(world);
  2728. if (resolvedField == null) {
  2729. // we can't find the field, so it's not a join point.
  2730. return;
  2731. } else if (Modifier.isFinal(resolvedField.getModifiers())
  2732. && Utility.isConstantPushInstruction(ih.getPrev().getInstruction())) {
  2733. // it's the set of a final constant, so it's
  2734. // not a join point according to 1.0.6 and 1.1.
  2735. return;
  2736. } else if (resolvedField.isSynthetic()) {
  2737. // sets of synthetics aren't join points in 1.1
  2738. return;
  2739. } else {
  2740. // Fix for bug 172107 (similar the "get" fix for bug 109728)
  2741. BcelShadow bs = BcelShadow.makeFieldSet(world, resolvedField, mg, ih, enclosingShadow);
  2742. String cname = fi.getClassName(cpg);
  2743. if (!resolvedField.getDeclaringType().getName().equals(cname)) {
  2744. bs.setActualTargetType(cname);
  2745. }
  2746. match(bs, shadowAccumulator);
  2747. }
  2748. }
  2749. private void matchGetInstruction(LazyMethodGen mg, InstructionHandle ih, BcelShadow enclosingShadow,
  2750. List<BcelShadow> shadowAccumulator) {
  2751. FieldInstruction fi = (FieldInstruction) ih.getInstruction();
  2752. Member field = BcelWorld.makeFieldJoinPointSignature(clazz, fi);
  2753. // synthetic fields are never join points
  2754. if (field.getName().startsWith(NameMangler.PREFIX)) {
  2755. return;
  2756. }
  2757. ResolvedMember resolvedField = field.resolve(world);
  2758. if (resolvedField == null) {
  2759. // we can't find the field, so it's not a join point.
  2760. return;
  2761. } else if (resolvedField.isSynthetic()) {
  2762. // sets of synthetics aren't join points in 1.1
  2763. return;
  2764. } else {
  2765. BcelShadow bs = BcelShadow.makeFieldGet(world, resolvedField, mg, ih, enclosingShadow);
  2766. String cname = fi.getClassName(cpg);
  2767. if (!resolvedField.getDeclaringType().getName().equals(cname)) {
  2768. bs.setActualTargetType(cname);
  2769. }
  2770. match(bs, shadowAccumulator);
  2771. }
  2772. }
  2773. /**
  2774. * For some named resolved type, this method looks for a member with a particular name - it should only be used when you truly
  2775. * believe there is only one member with that name in the type as it returns the first one it finds.
  2776. */
  2777. private ResolvedMember findResolvedMemberNamed(ResolvedType type, String methodName) {
  2778. ResolvedMember[] allMethods = type.getDeclaredMethods();
  2779. for (int i = 0; i < allMethods.length; i++) {
  2780. ResolvedMember member = allMethods[i];
  2781. if (member.getName().equals(methodName)) {
  2782. return member;
  2783. }
  2784. }
  2785. return null;
  2786. }
  2787. /**
  2788. * Find the specified member in the specified type.
  2789. *
  2790. * @param type the type to search for the member
  2791. * @param methodName the name of the method to find
  2792. * @param params the method parameters that the discovered method should have
  2793. */
  2794. private ResolvedMember findResolvedMemberNamed(ResolvedType type, String methodName, UnresolvedType[] params) {
  2795. ResolvedMember[] allMethods = type.getDeclaredMethods();
  2796. List<ResolvedMember> candidates = new ArrayList<ResolvedMember>();
  2797. for (int i = 0; i < allMethods.length; i++) {
  2798. ResolvedMember candidate = allMethods[i];
  2799. if (candidate.getName().equals(methodName)) {
  2800. if (candidate.getArity() == params.length) {
  2801. candidates.add(candidate);
  2802. }
  2803. }
  2804. }
  2805. if (candidates.size() == 0) {
  2806. return null;
  2807. } else if (candidates.size() == 1) {
  2808. return candidates.get(0);
  2809. } else {
  2810. // multiple candidates
  2811. for (ResolvedMember candidate : candidates) {
  2812. // These checks will break down with generics... but that would need two ITDs with the same name, same arity and
  2813. // generics
  2814. boolean allOK = true;
  2815. UnresolvedType[] candidateParams = candidate.getParameterTypes();
  2816. for (int p = 0; p < candidateParams.length; p++) {
  2817. if (!candidateParams[p].getErasureSignature().equals(params[p].getErasureSignature())) {
  2818. allOK = false;
  2819. break;
  2820. }
  2821. }
  2822. if (allOK) {
  2823. return candidate;
  2824. }
  2825. }
  2826. }
  2827. return null;
  2828. }
  2829. /**
  2830. * For a given resolvedmember, this will discover the real annotations for it. <b>Should only be used when the resolvedmember is
  2831. * the contents of an effective signature attribute, as thats the only time when the annotations aren't stored directly in the
  2832. * resolvedMember</b>
  2833. *
  2834. * @param rm the sig we want it to pretend to be 'int A.m()' or somesuch ITD like thing
  2835. * @param declaredSig the real sig 'blah.ajc$xxx'
  2836. */
  2837. private void fixParameterNamesForResolvedMember(ResolvedMember rm, ResolvedMember declaredSig) {
  2838. UnresolvedType memberHostType = declaredSig.getDeclaringType();
  2839. String methodName = declaredSig.getName();
  2840. String[] pnames = null;
  2841. if (rm.getKind() == Member.METHOD && !rm.isAbstract()) {
  2842. if (methodName.startsWith("ajc$inlineAccessMethod") || methodName.startsWith("ajc$superDispatch")) {
  2843. ResolvedMember resolvedDooberry = world.resolve(declaredSig);
  2844. pnames = resolvedDooberry.getParameterNames();
  2845. } else {
  2846. ResolvedMember realthing = AjcMemberMaker.interMethodDispatcher(rm.resolve(world), memberHostType).resolve(world);
  2847. ResolvedMember theRealMember = findResolvedMemberNamed(memberHostType.resolve(world), realthing.getName());
  2848. if (theRealMember != null) {
  2849. pnames = theRealMember.getParameterNames();
  2850. // static ITDs don't need any parameter shifting
  2851. if (pnames.length > 0 && pnames[0].equals("ajc$this_")) {
  2852. String[] pnames2 = new String[pnames.length - 1];
  2853. System.arraycopy(pnames, 1, pnames2, 0, pnames2.length);
  2854. pnames = pnames2;
  2855. }
  2856. }
  2857. }
  2858. // i think ctors are missing from here... copy code from below...
  2859. }
  2860. rm.setParameterNames(pnames);
  2861. }
  2862. /**
  2863. * For a given resolvedmember, this will discover the real annotations for it. <b>Should only be used when the resolvedmember is
  2864. * the contents of an effective signature attribute, as thats the only time when the annotations aren't stored directly in the
  2865. * resolvedMember</b>
  2866. *
  2867. * @param rm the sig we want it to pretend to be 'int A.m()' or somesuch ITD like thing
  2868. * @param declaredSig the real sig 'blah.ajc$xxx'
  2869. */
  2870. private void fixAnnotationsForResolvedMember(ResolvedMember rm, ResolvedMember declaredSig) {
  2871. try {
  2872. UnresolvedType memberHostType = declaredSig.getDeclaringType();
  2873. boolean containsKey = mapToAnnotationHolder.containsKey(rm);
  2874. ResolvedMember realAnnotationHolder = mapToAnnotationHolder.get(rm);
  2875. String methodName = declaredSig.getName();
  2876. // FIXME asc shouldnt really rely on string names !
  2877. if (!containsKey) {
  2878. if (rm.getKind() == Member.FIELD) {
  2879. if (methodName.startsWith("ajc$inlineAccessField")) {
  2880. realAnnotationHolder = world.resolve(rm);
  2881. } else {
  2882. ResolvedMember realthing = AjcMemberMaker.interFieldInitializer(rm, memberHostType);
  2883. realAnnotationHolder = world.resolve(realthing);
  2884. }
  2885. } else if (rm.getKind() == Member.METHOD && !rm.isAbstract()) {
  2886. if (methodName.startsWith("ajc$inlineAccessMethod") || methodName.startsWith("ajc$superDispatch")) {
  2887. realAnnotationHolder = world.resolve(declaredSig);
  2888. } else {
  2889. ResolvedMember realthing = AjcMemberMaker.interMethodDispatcher(rm.resolve(world), memberHostType).resolve(world);
  2890. realAnnotationHolder = findResolvedMemberNamed(memberHostType.resolve(world), realthing.getName(),realthing.getParameterTypes());
  2891. if (realAnnotationHolder == null) {
  2892. throw new UnsupportedOperationException(
  2893. "Known limitation in M4 - can't find ITD members when type variable is used as an argument and has upper bound specified");
  2894. }
  2895. }
  2896. } else if (rm.getKind() == Member.CONSTRUCTOR) {
  2897. ResolvedMember realThing = AjcMemberMaker.postIntroducedConstructor(memberHostType.resolve(world),rm.getDeclaringType(), rm.getParameterTypes());
  2898. realAnnotationHolder = world.resolve(realThing);
  2899. // AMC temp guard for M4
  2900. if (realAnnotationHolder == null) {
  2901. throw new UnsupportedOperationException("Known limitation in M4 - can't find ITD members when type variable is used as an argument and has upper bound specified");
  2902. }
  2903. }
  2904. mapToAnnotationHolder.put(rm, realAnnotationHolder);
  2905. }
  2906. ResolvedType[] annotationTypes;
  2907. AnnotationAJ[] annotations;
  2908. if (realAnnotationHolder!=null) {
  2909. annotationTypes = realAnnotationHolder.getAnnotationTypes();
  2910. annotations = realAnnotationHolder.getAnnotations();
  2911. if (annotationTypes==null) {
  2912. annotationTypes = ResolvedType.EMPTY_ARRAY;
  2913. }
  2914. if (annotations==null) {
  2915. annotations = AnnotationAJ.EMPTY_ARRAY;
  2916. }
  2917. } else {
  2918. annotations = AnnotationAJ.EMPTY_ARRAY;
  2919. annotationTypes = ResolvedType.EMPTY_ARRAY;
  2920. }
  2921. rm.setAnnotations(annotations);
  2922. rm.setAnnotationTypes(annotationTypes);
  2923. } catch (UnsupportedOperationException ex) {
  2924. throw ex;
  2925. } catch (Throwable t) {
  2926. // FIXME asc remove this catch after more testing has confirmed the
  2927. // above stuff is OK
  2928. throw new BCException("Unexpectedly went bang when searching for annotations on " + rm, t);
  2929. }
  2930. }
  2931. private void matchInvokeInstruction(LazyMethodGen mg, InstructionHandle ih, InvokeInstruction invoke,
  2932. BcelShadow enclosingShadow, List<BcelShadow> shadowAccumulator) {
  2933. String methodName = invoke.getName(cpg);
  2934. if (methodName.startsWith(NameMangler.PREFIX)) {
  2935. Member jpSig = world.makeJoinPointSignatureForMethodInvocation(clazz, invoke);
  2936. ResolvedMember declaredSig = jpSig.resolve(world);
  2937. // System.err.println(method + ", declaredSig: " +declaredSig);
  2938. if (declaredSig == null) {
  2939. return;
  2940. }
  2941. if (declaredSig.getKind() == Member.FIELD) {
  2942. Shadow.Kind kind;
  2943. if (jpSig.getReturnType().equals(UnresolvedType.VOID)) {
  2944. kind = Shadow.FieldSet;
  2945. } else {
  2946. kind = Shadow.FieldGet;
  2947. }
  2948. if (canMatch(Shadow.FieldGet) || canMatch(Shadow.FieldSet)) {
  2949. match(BcelShadow.makeShadowForMethodCall(world, mg, ih, enclosingShadow, kind, declaredSig), shadowAccumulator);
  2950. }
  2951. } else {
  2952. AjAttribute.EffectiveSignatureAttribute effectiveSig = declaredSig.getEffectiveSignature();
  2953. if (effectiveSig == null) {
  2954. return;
  2955. }
  2956. // System.err.println("call to inter-type member: " +
  2957. // effectiveSig);
  2958. if (effectiveSig.isWeaveBody()) {
  2959. return;
  2960. }
  2961. ResolvedMember rm = effectiveSig.getEffectiveSignature();
  2962. fixParameterNamesForResolvedMember(rm, declaredSig);
  2963. fixAnnotationsForResolvedMember(rm, declaredSig); // abracadabra
  2964. if (canMatch(effectiveSig.getShadowKind())) {
  2965. match(BcelShadow.makeShadowForMethodCall(world, mg, ih, enclosingShadow, effectiveSig.getShadowKind(), rm),
  2966. shadowAccumulator);
  2967. }
  2968. }
  2969. } else {
  2970. if (canMatch(Shadow.MethodCall)) {
  2971. boolean proceed = true;
  2972. // overweaving needs to ignore some calls added by the previous weave
  2973. if (world.isOverWeaving()) {
  2974. String s = invoke.getClassName(mg.getConstantPool());
  2975. // skip all the inc/dec/isValid/etc
  2976. if (s.length() > 4
  2977. && s.charAt(4) == 'a'
  2978. && (s.equals("org.aspectj.runtime.internal.CFlowCounter")
  2979. || s.equals("org.aspectj.runtime.internal.CFlowStack") || s
  2980. .equals("org.aspectj.runtime.reflect.Factory"))) {
  2981. proceed = false;
  2982. } else {
  2983. if (methodName.equals("aspectOf")) {
  2984. proceed = false;
  2985. }
  2986. }
  2987. }
  2988. if (proceed) {
  2989. match(BcelShadow.makeMethodCall(world, mg, ih, enclosingShadow), shadowAccumulator);
  2990. }
  2991. }
  2992. }
  2993. }
  2994. // static ... so all worlds will share the config for the first one
  2995. // created...
  2996. private static boolean checkedXsetForLowLevelContextCapturing = false;
  2997. private static boolean captureLowLevelContext = false;
  2998. private boolean match(BcelShadow shadow, List<BcelShadow> shadowAccumulator) {
  2999. // Duplicate blocks - one with context one without, seems faster than multiple 'ifs'
  3000. if (captureLowLevelContext) {
  3001. ContextToken shadowMatchToken = CompilationAndWeavingContext.enteringPhase(
  3002. CompilationAndWeavingContext.MATCHING_SHADOW, shadow);
  3003. boolean isMatched = false;
  3004. Shadow.Kind shadowKind = shadow.getKind();
  3005. List<ShadowMunger> candidateMungers = indexedShadowMungers[shadowKind.getKey()];
  3006. // System.out.println("Candidates " + candidateMungers);
  3007. if (candidateMungers != null) {
  3008. for (ShadowMunger munger : candidateMungers) {
  3009. ContextToken mungerMatchToken = CompilationAndWeavingContext.enteringPhase(
  3010. CompilationAndWeavingContext.MATCHING_POINTCUT, munger.getPointcut());
  3011. if (munger.match(shadow, world)) {
  3012. shadow.addMunger(munger);
  3013. isMatched = true;
  3014. if (shadow.getKind() == Shadow.StaticInitialization) {
  3015. clazz.warnOnAddedStaticInitializer(shadow, munger.getSourceLocation());
  3016. }
  3017. }
  3018. CompilationAndWeavingContext.leavingPhase(mungerMatchToken);
  3019. }
  3020. if (isMatched) {
  3021. shadowAccumulator.add(shadow);
  3022. }
  3023. }
  3024. CompilationAndWeavingContext.leavingPhase(shadowMatchToken);
  3025. return isMatched;
  3026. } else {
  3027. boolean isMatched = false;
  3028. Shadow.Kind shadowKind = shadow.getKind();
  3029. List<ShadowMunger> candidateMungers = indexedShadowMungers[shadowKind.getKey()];
  3030. // System.out.println("Candidates at " + shadowKind + " are " + candidateMungers);
  3031. if (candidateMungers != null) {
  3032. for (ShadowMunger munger : candidateMungers) {
  3033. if (munger.match(shadow, world)) {
  3034. shadow.addMunger(munger);
  3035. isMatched = true;
  3036. if (shadow.getKind() == Shadow.StaticInitialization) {
  3037. clazz.warnOnAddedStaticInitializer(shadow, munger.getSourceLocation());
  3038. }
  3039. }
  3040. }
  3041. if (isMatched) {
  3042. shadowAccumulator.add(shadow);
  3043. }
  3044. }
  3045. return isMatched;
  3046. }
  3047. }
  3048. // ----
  3049. private void implement(LazyMethodGen mg) {
  3050. List<BcelShadow> shadows = mg.matchedShadows;
  3051. if (shadows == null) {
  3052. return;
  3053. }
  3054. // We depend on a partial order such that inner shadows are earlier on
  3055. // the list than outer shadows. That's fine. This order is preserved if:
  3056. // A preceeds B iff B.getStart() is LATER THAN A.getStart().
  3057. for (BcelShadow shadow : shadows) {
  3058. ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.IMPLEMENTING_ON_SHADOW,
  3059. shadow);
  3060. shadow.implement();
  3061. CompilationAndWeavingContext.leavingPhase(tok);
  3062. }
  3063. // int ii =
  3064. mg.getMaxLocals();
  3065. mg.matchedShadows = null;
  3066. }
  3067. // ----
  3068. public LazyClassGen getLazyClassGen() {
  3069. return clazz;
  3070. }
  3071. public BcelWorld getWorld() {
  3072. return world;
  3073. }
  3074. public void setReweavableMode(boolean mode) {
  3075. inReweavableMode = mode;
  3076. }
  3077. public boolean getReweavableMode() {
  3078. return inReweavableMode;
  3079. }
  3080. @Override
  3081. public String toString() {
  3082. return "BcelClassWeaver instance for : " + clazz;
  3083. }
  3084. }