You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

BcelClassWeaver.java 132KB

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