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.

BcelShadow.java 137KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465
  1. /* *******************************************************************
  2. * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
  3. * All rights reserved.
  4. * This program and the accompanying materials are made available
  5. * under the terms of the Eclipse Public License v 2.0
  6. * which accompanies this distribution and is available at
  7. * https://www.eclipse.org/org/documents/epl-2.0/EPL-2.0.txt
  8. *
  9. * Contributors:
  10. * PARC initial implementation
  11. * Alexandre Vasseur support for @AJ aspects
  12. * ******************************************************************/
  13. package org.aspectj.weaver.bcel;
  14. import java.lang.reflect.Modifier;
  15. import java.util.ArrayList;
  16. import java.util.Collections;
  17. import java.util.HashMap;
  18. import java.util.List;
  19. import java.util.Map;
  20. import org.aspectj.apache.bcel.Constants;
  21. import org.aspectj.apache.bcel.classfile.ConstantPool;
  22. import org.aspectj.apache.bcel.classfile.Field;
  23. import org.aspectj.apache.bcel.generic.ArrayType;
  24. import org.aspectj.apache.bcel.generic.BranchHandle;
  25. import org.aspectj.apache.bcel.generic.FieldInstruction;
  26. import org.aspectj.apache.bcel.generic.INVOKEINTERFACE;
  27. import org.aspectj.apache.bcel.generic.Instruction;
  28. import org.aspectj.apache.bcel.generic.InstructionBranch;
  29. import org.aspectj.apache.bcel.generic.InstructionConstants;
  30. import org.aspectj.apache.bcel.generic.InstructionFactory;
  31. import org.aspectj.apache.bcel.generic.InstructionHandle;
  32. import org.aspectj.apache.bcel.generic.InstructionLV;
  33. import org.aspectj.apache.bcel.generic.InstructionList;
  34. import org.aspectj.apache.bcel.generic.InstructionTargeter;
  35. import org.aspectj.apache.bcel.generic.InvokeInstruction;
  36. import org.aspectj.apache.bcel.generic.LineNumberTag;
  37. import org.aspectj.apache.bcel.generic.LocalVariableTag;
  38. import org.aspectj.apache.bcel.generic.MULTIANEWARRAY;
  39. import org.aspectj.apache.bcel.generic.ObjectType;
  40. import org.aspectj.apache.bcel.generic.TargetLostException;
  41. import org.aspectj.apache.bcel.generic.Type;
  42. import org.aspectj.bridge.ISourceLocation;
  43. import org.aspectj.weaver.Advice;
  44. import org.aspectj.weaver.AdviceKind;
  45. import org.aspectj.weaver.AjcMemberMaker;
  46. import org.aspectj.weaver.BCException;
  47. import org.aspectj.weaver.ConcreteTypeMunger;
  48. import org.aspectj.weaver.IntMap;
  49. import org.aspectj.weaver.Member;
  50. import org.aspectj.weaver.MemberImpl;
  51. import org.aspectj.weaver.NameMangler;
  52. import org.aspectj.weaver.NewConstructorTypeMunger;
  53. import org.aspectj.weaver.NewFieldTypeMunger;
  54. import org.aspectj.weaver.NewMethodTypeMunger;
  55. import org.aspectj.weaver.ResolvedMember;
  56. import org.aspectj.weaver.ResolvedMemberImpl;
  57. import org.aspectj.weaver.ResolvedType;
  58. import org.aspectj.weaver.Shadow;
  59. import org.aspectj.weaver.ShadowMunger;
  60. import org.aspectj.weaver.UnresolvedType;
  61. import org.aspectj.weaver.WeaverMessages;
  62. import org.aspectj.weaver.World;
  63. import org.aspectj.weaver.ast.Var;
  64. import org.aspectj.weaver.patterns.AbstractPatternNodeVisitor;
  65. import org.aspectj.weaver.patterns.AndPointcut;
  66. import org.aspectj.weaver.patterns.NotPointcut;
  67. import org.aspectj.weaver.patterns.OrPointcut;
  68. import org.aspectj.weaver.patterns.ThisOrTargetPointcut;
  69. /*
  70. * Some fun implementation stuff:
  71. *
  72. * * expressionKind advice is non-execution advice
  73. * * may have a target.
  74. * * if the body is extracted, it will be extracted into
  75. * a static method. The first argument to the static
  76. * method is the target
  77. * * advice may expose a this object, but that's the advice's
  78. * consideration, not ours. This object will NOT be cached in another
  79. * local, but will always come from frame zero.
  80. *
  81. * * non-expressionKind advice is execution advice
  82. * * may have a this.
  83. * * target is same as this, and is exposed that way to advice
  84. * (i.e., target will not be cached, will always come from frame zero)
  85. * * if the body is extracted, it will be extracted into a method
  86. * with same static/dynamic modifier as enclosing method. If non-static,
  87. * target of callback call will be this.
  88. *
  89. * * because of these two facts, the setup of the actual arguments (including
  90. * possible target) callback method is the same for both kinds of advice:
  91. * push the targetVar, if it exists (it will not exist for advice on static
  92. * things), then push all the argVars.
  93. *
  94. * Protected things:
  95. *
  96. * * the above is sufficient for non-expressionKind advice for protected things,
  97. * since the target will always be this.
  98. *
  99. * * For expressionKind things, we have to modify the signature of the callback
  100. * method slightly. For non-static expressionKind things, we modify
  101. * the first argument of the callback method NOT to be the type specified
  102. * by the method/field signature (the owner), but rather we type it to
  103. * the currentlyEnclosing type. We are guaranteed this will be fine,
  104. * since the verifier verifies that the target is a subtype of the currently
  105. * enclosingType.
  106. *
  107. * Worries:
  108. *
  109. * * ConstructorCalls will be weirder than all of these, since they
  110. * supposedly don't have a target (according to AspectJ), but they clearly
  111. * do have a target of sorts, just one that needs to be pushed on the stack,
  112. * dupped, and not touched otherwise until the constructor runs.
  113. *
  114. * @author Jim Hugunin
  115. * @author Erik Hilsdale
  116. *
  117. */
  118. public class BcelShadow extends Shadow {
  119. private static final String[] NoDeclaredExceptions = new String[0];
  120. private ShadowRange range;
  121. private final BcelWorld world;
  122. private final LazyMethodGen enclosingMethod;
  123. // TESTING this will tell us if the optimisation succeeded *on the last shadow processed*
  124. public static boolean appliedLazyTjpOptimization;
  125. // Some instructions have a target type that will vary
  126. // from the signature (pr109728) (1.4 declaring type issue)
  127. private String actualInstructionTargetType;
  128. /**
  129. * This generates an unassociated shadow, rooted in a particular method but not rooted to any particular point in the code. It
  130. * should be given to a rooted ShadowRange in the {@link ShadowRange#associateWithShadow(BcelShadow)} method.
  131. */
  132. public BcelShadow(BcelWorld world, Kind kind, Member signature, LazyMethodGen enclosingMethod, BcelShadow enclosingShadow) {
  133. super(kind, signature, enclosingShadow);
  134. this.world = world;
  135. this.enclosingMethod = enclosingMethod;
  136. }
  137. // ---- copies all state, including Shadow's mungers...
  138. public BcelShadow copyInto(LazyMethodGen recipient, BcelShadow enclosing) {
  139. BcelShadow s = new BcelShadow(world, getKind(), getSignature(), recipient, enclosing);
  140. if (mungers.size() > 0) {
  141. List<ShadowMunger> src = mungers;
  142. if (s.mungers == Collections.EMPTY_LIST) {
  143. s.mungers = new ArrayList<>();
  144. }
  145. List<ShadowMunger> dest = s.mungers;
  146. for (ShadowMunger shadowMunger : src) {
  147. dest.add(shadowMunger);
  148. }
  149. }
  150. return s;
  151. }
  152. // ---- overridden behaviour
  153. @Override
  154. public World getIWorld() {
  155. return world;
  156. }
  157. // see comment in deleteNewAndDup
  158. // } else if (inst.opcode == Constants.DUP_X2) {
  159. // // This code seen in the wild (by Brad):
  160. // // 40: new #12; //class java/lang/StringBuffer
  161. // // STACK: STRINGBUFFER
  162. // // 43: dup
  163. // // STACK: STRINGBUFFER/STRINGBUFFER
  164. // // 44: aload_0
  165. // // STACK: STRINGBUFFER/STRINGBUFFER/THIS
  166. // // 45: dup_x2
  167. // // STACK: THIS/STRINGBUFFER/STRINGBUFFER/THIS
  168. // // 46: getfield #36; //Field value:Ljava/lang/String;
  169. // // STACK: THIS/STRINGBUFFER/STRINGBUFFER/STRING<value>
  170. // // 49: invokestatic #37; //Method java/lang/String.valueOf:(Ljava/lang/Object;)Ljava/lang/String;
  171. // // STACK: THIS/STRINGBUFFER/STRINGBUFFER/STRING
  172. // // 52: invokespecial #19; //Method java/lang/StringBuffer."<init>":(Ljava/lang/String;)V
  173. // // STACK: THIS/STRINGBUFFER
  174. // // 55: aload_1
  175. // // STACK: THIS/STRINGBUFFER/LOCAL1
  176. // // 56: invokevirtual #22; //Method java/lang/StringBuffer.append:(Ljava/lang/String;)Ljava/lang/StringBuffer;
  177. // // STACK: THIS/STRINGBUFFER
  178. // // 59: invokevirtual #34; //Method java/lang/StringBuffer.toString:()Ljava/lang/String;
  179. // // STACK: THIS/STRING
  180. // // 62: putfield #36; //Field value:Ljava/lang/String;
  181. // // STACK: <empty>
  182. // // 65: return
  183. //
  184. // // if we attempt to match on the ctor call to StringBuffer.<init> then we get into trouble.
  185. // // if we simply delete the new/dup pair without fixing up the dup_x2 then the dup_x2 will fail due to there
  186. // // not being 3 elements on the stack for it to work with. The fix *in this situation* is to change it to
  187. // // a simple 'dup'
  188. //
  189. // // this fix is *not* very clean - but a general purpose decent solution will take much longer and this
  190. // // bytecode sequence has only been seen once in the wild.
  191. // ih.setInstruction(InstructionConstants.DUP);
  192. /**
  193. * The new/dup (or new/dup_x1/swap) are removed and will be readded later (after the advice call) by the caller of this method.
  194. * The groovy compiler produces unusual code where the new/dup isn't visible (when making a this() call from an existing ctor),
  195. * an aload_0 is used to load the uninitialized object (as an example see the ctors in grails.util.BuildSettings).
  196. *
  197. * @return true if managed to remove them
  198. */
  199. private boolean deleteNewAndDup() {
  200. final ConstantPool cpool = getEnclosingClass().getConstantPool();
  201. int depth = 1;
  202. InstructionHandle ih = range.getStart();
  203. // Go back from where we are looking for 'NEW' that takes us to a stack depth of 0. INVOKESPECIAL <init>
  204. while (ih != null) {
  205. Instruction inst = ih.getInstruction();
  206. if (inst.opcode == Constants.INVOKESPECIAL && ((InvokeInstruction) inst).getName(cpool).equals("<init>")) {
  207. depth++;
  208. } else if (inst.opcode == Constants.NEW) {
  209. depth--;
  210. if (depth == 0) {
  211. break;
  212. }
  213. // need a testcase to show this can really happen in a modern compiler - removed due to 315398 - moved this out to
  214. // comment proceeding this method:
  215. }
  216. ih = ih.getPrev();
  217. }
  218. if (ih == null) {
  219. return false;
  220. }
  221. // now IH points to the NEW. We're followed by the DUP, and that is followed
  222. // by the actual instruction we care about.
  223. InstructionHandle newHandle = ih;
  224. InstructionHandle endHandle = newHandle.getNext();
  225. InstructionHandle nextHandle;
  226. if (endHandle.getInstruction().opcode == Constants.DUP) {
  227. nextHandle = endHandle.getNext();
  228. retargetFrom(newHandle, nextHandle);
  229. retargetFrom(endHandle, nextHandle);
  230. } else if (endHandle.getInstruction().opcode == Constants.DUP_X1) {
  231. InstructionHandle dupHandle = endHandle;
  232. endHandle = endHandle.getNext();
  233. nextHandle = endHandle.getNext();
  234. boolean skipEndRepositioning = false;
  235. if (endHandle.getInstruction().opcode == Constants.SWAP) {
  236. } else if (endHandle.getInstruction().opcode == Constants.IMPDEP1) {
  237. skipEndRepositioning = true; // pr186884
  238. } else {
  239. // XXX see next XXX comment
  240. throw new RuntimeException("Unhandled kind of new " + endHandle);
  241. }
  242. // Now make any jumps to the 'new', the 'dup' or the 'end' now target the nextHandle
  243. retargetFrom(newHandle, nextHandle);
  244. retargetFrom(dupHandle, nextHandle);
  245. if (!skipEndRepositioning) {
  246. retargetFrom(endHandle, nextHandle);
  247. }
  248. } else {
  249. endHandle = newHandle;
  250. nextHandle = endHandle.getNext();
  251. retargetFrom(newHandle, nextHandle);
  252. // add a POP here... we found a NEW w/o a dup or anything else, so
  253. // we must be in statement context.
  254. getRange().insert(InstructionConstants.POP, Range.OutsideAfter);
  255. }
  256. // assert (dupHandle.getInstruction() instanceof DUP);
  257. try {
  258. range.getBody().delete(newHandle, endHandle);
  259. } catch (TargetLostException e) {
  260. throw new BCException("shouldn't happen");
  261. }
  262. return true;
  263. }
  264. private void retargetFrom(InstructionHandle old, InstructionHandle fresh) {
  265. for (InstructionTargeter targeter : old.getTargetersCopy()) {
  266. if (targeter instanceof ExceptionRange) {
  267. ExceptionRange it = (ExceptionRange) targeter;
  268. it.updateTarget(old, fresh, it.getBody());
  269. } else {
  270. targeter.updateTarget(old, fresh);
  271. }
  272. }
  273. }
  274. // records advice that is stopping us doing the lazyTjp optimization
  275. private List<BcelAdvice> badAdvice = null;
  276. public void addAdvicePreventingLazyTjp(BcelAdvice advice) {
  277. if (badAdvice == null) {
  278. badAdvice = new ArrayList<>();
  279. }
  280. badAdvice.add(advice);
  281. }
  282. @Override
  283. protected void prepareForMungers() {
  284. // if we're a constructor call, we need to remove the new:dup or the new:dup_x1:swap,
  285. // and store all our arguments on the frame.
  286. // ??? This is a bit of a hack (for the Java langauge). We do this because
  287. // we sometime add code "outsideBefore" when dealing with weaving join points. We only
  288. // do this for exposing state that is on the stack. It turns out to just work for
  289. // everything except for constructor calls and exception handlers. If we were to clean
  290. // this up, every ShadowRange would have three instructionHandle points, the start of
  291. // the arg-setup code, the start of the running code, and the end of the running code.
  292. boolean deletedNewAndDup = true;
  293. if (getKind() == ConstructorCall) {
  294. if (!world.isJoinpointArrayConstructionEnabled() || !this.getSignature().getDeclaringType().isArray()) {
  295. deletedNewAndDup = deleteNewAndDup(); // no new/dup for new array construction
  296. }
  297. initializeArgVars();
  298. } else if (getKind() == PreInitialization) { // pr74952
  299. ShadowRange range = getRange();
  300. range.insert(InstructionConstants.NOP, Range.InsideAfter);
  301. } else if (getKind() == ExceptionHandler) {
  302. ShadowRange range = getRange();
  303. InstructionList body = range.getBody();
  304. InstructionHandle start = range.getStart();
  305. // Create a store instruction to put the value from the top of the
  306. // stack into a local variable slot. This is a trimmed version of
  307. // what is in initializeArgVars() (since there is only one argument
  308. // at a handler jp and only before advice is supported) (pr46298)
  309. argVars = new BcelVar[1];
  310. // int positionOffset = (hasTarget() ? 1 : 0) + ((hasThis() && !getKind().isTargetSameAsThis()) ? 1 : 0);
  311. UnresolvedType tx = getArgType(0);
  312. argVars[0] = genTempVar(tx, "ajc$arg0");
  313. InstructionHandle insertedInstruction = range.insert(argVars[0].createStore(getFactory()), Range.OutsideBefore);
  314. // Now the exception range starts just after our new instruction.
  315. // The next bit of code changes the exception range to point at
  316. // the store instruction
  317. for (InstructionTargeter t : start.getTargetersCopy()) {
  318. if (t instanceof ExceptionRange) {
  319. ExceptionRange er = (ExceptionRange) t;
  320. er.updateTarget(start, insertedInstruction, body);
  321. }
  322. }
  323. }
  324. // now we ask each munger to request our state
  325. isThisJoinPointLazy = true;// world.isXlazyTjp(); // lazy is default now
  326. badAdvice = null;
  327. for (ShadowMunger munger : mungers) {
  328. munger.specializeOn(this);
  329. }
  330. initializeThisJoinPoint();
  331. if (thisJoinPointVar != null && !isThisJoinPointLazy && badAdvice != null && badAdvice.size() > 1) {
  332. // something stopped us making it a lazy tjp
  333. // can't build tjp lazily, no suitable test...
  334. int valid = 0;
  335. for (BcelAdvice element : badAdvice) {
  336. ISourceLocation sLoc = element.getSourceLocation();
  337. if (sLoc != null && sLoc.getLine() > 0) {
  338. valid++;
  339. }
  340. }
  341. if (valid != 0) {
  342. ISourceLocation[] badLocs = new ISourceLocation[valid];
  343. int i = 0;
  344. for (BcelAdvice element : badAdvice) {
  345. ISourceLocation sLoc = element.getSourceLocation();
  346. if (sLoc != null) {
  347. badLocs[i++] = sLoc;
  348. }
  349. }
  350. world.getLint().multipleAdviceStoppingLazyTjp
  351. .signal(new String[] { this.toString() }, getSourceLocation(), badLocs);
  352. }
  353. }
  354. badAdvice = null;
  355. // If we are an expression kind, we require our target/arguments on the stack
  356. // before we do our actual thing. However, they may have been removed
  357. // from the stack as the shadowMungers have requested state.
  358. // if any of our shadowMungers requested either the arguments or target,
  359. // the munger will have added code
  360. // to pop the target/arguments into temporary variables, represented by
  361. // targetVar and argVars. In such a case, we must make sure to re-push the
  362. // values.
  363. // If we are nonExpressionKind, we don't expect arguments on the stack
  364. // so this is moot. If our argVars happen to be null, then we know that
  365. // no ShadowMunger has squirrelled away our arguments, so they're still
  366. // on the stack.
  367. InstructionFactory fact = getFactory();
  368. if (getKind().argsOnStack() && argVars != null) {
  369. // Special case first (pr46298). If we are an exception handler and the instruction
  370. // just after the shadow is a POP then we should remove the pop. The code
  371. // above which generated the store instruction has already cleared the stack.
  372. // We also don't generate any code for the arguments in this case as it would be
  373. // an incorrect aload.
  374. if (getKind() == ExceptionHandler && range.getEnd().getNext().getInstruction().equals(InstructionConstants.POP)) {
  375. // easier than deleting it ...
  376. range.getEnd().getNext().setInstruction(InstructionConstants.NOP);
  377. } else {
  378. range.insert(BcelRenderer.renderExprs(fact, world, argVars), Range.InsideBefore);
  379. if (targetVar != null) {
  380. range.insert(BcelRenderer.renderExpr(fact, world, targetVar), Range.InsideBefore);
  381. }
  382. if (getKind() == ConstructorCall) {
  383. if (!world.isJoinpointArrayConstructionEnabled() || !this.getSignature().getDeclaringType().isArray()) {
  384. if (deletedNewAndDup) { // if didnt delete them, dont insert any!
  385. range.insert(InstructionFactory.createDup(1), Range.InsideBefore);
  386. range.insert(fact.createNew((ObjectType) BcelWorld.makeBcelType(getSignature().getDeclaringType())),
  387. Range.InsideBefore);
  388. }
  389. }
  390. }
  391. }
  392. }
  393. }
  394. // ---- getters
  395. public ShadowRange getRange() {
  396. return range;
  397. }
  398. public void setRange(ShadowRange range) {
  399. this.range = range;
  400. }
  401. private int sourceline = -1;
  402. public int getSourceLine() {
  403. // if the kind of join point for which we are a shadow represents
  404. // a method or constructor execution, then the best source line is
  405. // the one from the enclosingMethod declarationLineNumber if available.
  406. if (sourceline != -1) {
  407. return sourceline;
  408. }
  409. Kind kind = getKind();
  410. if ((kind == MethodExecution) || (kind == ConstructorExecution) || (kind == AdviceExecution)
  411. || (kind == StaticInitialization) || (kind == PreInitialization) || (kind == Initialization)) {
  412. if (getEnclosingMethod().hasDeclaredLineNumberInfo()) {
  413. sourceline = getEnclosingMethod().getDeclarationLineNumber();
  414. return sourceline;
  415. }
  416. }
  417. if (range == null) {
  418. if (getEnclosingMethod().hasBody()) {
  419. sourceline = Utility.getSourceLine(getEnclosingMethod().getBody().getStart());
  420. return sourceline;
  421. } else {
  422. sourceline = 0;
  423. return sourceline;
  424. }
  425. }
  426. sourceline = Utility.getSourceLine(range.getStart());
  427. if (sourceline < 0) {
  428. sourceline = 0;
  429. }
  430. return sourceline;
  431. }
  432. @Override
  433. public ResolvedType getEnclosingType() {
  434. return getEnclosingClass().getType();
  435. }
  436. public LazyClassGen getEnclosingClass() {
  437. return enclosingMethod.getEnclosingClass();
  438. }
  439. public BcelWorld getWorld() {
  440. return world;
  441. }
  442. // ---- factory methods
  443. public static BcelShadow makeConstructorExecution(BcelWorld world, LazyMethodGen enclosingMethod,
  444. InstructionHandle justBeforeStart) {
  445. final InstructionList body = enclosingMethod.getBody();
  446. BcelShadow s = new BcelShadow(world, ConstructorExecution, world.makeJoinPointSignatureFromMethod(enclosingMethod,
  447. Member.CONSTRUCTOR), enclosingMethod, null);
  448. ShadowRange r = new ShadowRange(body);
  449. r.associateWithShadow(s);
  450. r.associateWithTargets(Range.genStart(body, justBeforeStart.getNext()), Range.genEnd(body));
  451. return s;
  452. }
  453. public static BcelShadow makeStaticInitialization(BcelWorld world, LazyMethodGen enclosingMethod) {
  454. InstructionList body = enclosingMethod.getBody();
  455. // move the start past ajc$preClinit
  456. InstructionHandle clinitStart = body.getStart();
  457. if (clinitStart.getInstruction() instanceof InvokeInstruction) {
  458. InvokeInstruction ii = (InvokeInstruction) clinitStart.getInstruction();
  459. if (ii.getName(enclosingMethod.getEnclosingClass().getConstantPool()).equals(NameMangler.AJC_PRE_CLINIT_NAME)) {
  460. clinitStart = clinitStart.getNext();
  461. }
  462. }
  463. InstructionHandle clinitEnd = body.getEnd();
  464. // XXX should move the end before the postClinit, but the return is then tricky...
  465. // if (clinitEnd.getInstruction() instanceof InvokeInstruction) {
  466. // InvokeInstruction ii = (InvokeInstruction)clinitEnd.getInstruction();
  467. // if (ii.getName(enclosingMethod.getEnclosingClass().getConstantPool()).equals(NameMangler.AJC_POST_CLINIT_NAME)) {
  468. // clinitEnd = clinitEnd.getPrev();
  469. // }
  470. // }
  471. BcelShadow s = new BcelShadow(world, StaticInitialization, world.makeJoinPointSignatureFromMethod(enclosingMethod,
  472. Member.STATIC_INITIALIZATION), enclosingMethod, null);
  473. ShadowRange r = new ShadowRange(body);
  474. r.associateWithShadow(s);
  475. r.associateWithTargets(Range.genStart(body, clinitStart), Range.genEnd(body, clinitEnd));
  476. return s;
  477. }
  478. /**
  479. * Make the shadow for an exception handler. Currently makes an empty shadow that only allows before advice to be woven into it.
  480. */
  481. public static BcelShadow makeExceptionHandler(BcelWorld world, ExceptionRange exceptionRange, LazyMethodGen enclosingMethod,
  482. InstructionHandle startOfHandler, BcelShadow enclosingShadow) {
  483. InstructionList body = enclosingMethod.getBody();
  484. UnresolvedType catchType = exceptionRange.getCatchType();
  485. UnresolvedType inType = enclosingMethod.getEnclosingClass().getType();
  486. ResolvedMemberImpl sig = MemberImpl.makeExceptionHandlerSignature(inType, catchType);
  487. sig.setParameterNames(new String[] { findHandlerParamName(startOfHandler) });
  488. BcelShadow s = new BcelShadow(world, ExceptionHandler, sig, enclosingMethod, enclosingShadow);
  489. ShadowRange r = new ShadowRange(body);
  490. r.associateWithShadow(s);
  491. InstructionHandle start = Range.genStart(body, startOfHandler);
  492. InstructionHandle end = Range.genEnd(body, start);
  493. r.associateWithTargets(start, end);
  494. exceptionRange.updateTarget(startOfHandler, start, body);
  495. return s;
  496. }
  497. private static String findHandlerParamName(InstructionHandle startOfHandler) {
  498. if (startOfHandler.getInstruction().isStoreInstruction() && startOfHandler.getNext() != null) {
  499. int slot = startOfHandler.getInstruction().getIndex();
  500. // System.out.println("got store: " + startOfHandler.getInstruction() + ", " + index);
  501. for (InstructionTargeter targeter : startOfHandler.getNext().getTargeters()) {
  502. if (targeter instanceof LocalVariableTag) {
  503. LocalVariableTag t = (LocalVariableTag) targeter;
  504. if (t.getSlot() == slot) {
  505. return t.getName();
  506. }
  507. }
  508. }
  509. }
  510. return "<missing>";
  511. }
  512. /** create an init join point associated w/ an interface in the body of a constructor */
  513. public static BcelShadow makeIfaceInitialization(BcelWorld world, LazyMethodGen constructor,
  514. Member interfaceConstructorSignature) {
  515. // this call marks the instruction list as changed
  516. constructor.getBody();
  517. // UnresolvedType inType = constructor.getEnclosingClass().getType();
  518. BcelShadow s = new BcelShadow(world, Initialization, interfaceConstructorSignature, constructor, null);
  519. // s.fallsThrough = true;
  520. // ShadowRange r = new ShadowRange(body);
  521. // r.associateWithShadow(s);
  522. // InstructionHandle start = Range.genStart(body, handle);
  523. // InstructionHandle end = Range.genEnd(body, handle);
  524. //
  525. // r.associateWithTargets(start, end);
  526. return s;
  527. }
  528. public void initIfaceInitializer(InstructionHandle end) {
  529. final InstructionList body = enclosingMethod.getBody();
  530. ShadowRange r = new ShadowRange(body);
  531. r.associateWithShadow(this);
  532. InstructionHandle nop = body.insert(end, InstructionConstants.NOP);
  533. r.associateWithTargets(Range.genStart(body, nop), Range.genEnd(body, nop));
  534. }
  535. // public static BcelShadow makeIfaceConstructorExecution(
  536. // BcelWorld world,
  537. // LazyMethodGen constructor,
  538. // InstructionHandle next,
  539. // Member interfaceConstructorSignature)
  540. // {
  541. // // final InstructionFactory fact = constructor.getEnclosingClass().getFactory();
  542. // InstructionList body = constructor.getBody();
  543. // // UnresolvedType inType = constructor.getEnclosingClass().getType();
  544. // BcelShadow s =
  545. // new BcelShadow(
  546. // world,
  547. // ConstructorExecution,
  548. // interfaceConstructorSignature,
  549. // constructor,
  550. // null);
  551. // s.fallsThrough = true;
  552. // ShadowRange r = new ShadowRange(body);
  553. // r.associateWithShadow(s);
  554. // // ??? this may or may not work
  555. // InstructionHandle start = Range.genStart(body, next);
  556. // //InstructionHandle end = Range.genEnd(body, body.append(start, fact.NOP));
  557. // InstructionHandle end = Range.genStart(body, next);
  558. // //body.append(start, fact.NOP);
  559. //
  560. // r.associateWithTargets(start, end);
  561. // return s;
  562. // }
  563. /**
  564. * Create an initialization join point associated with a constructor, but not with any body of code yet. If this is actually
  565. * matched, its range will be set when we inline self constructors.
  566. *
  567. * @param constructor The constructor starting this initialization.
  568. */
  569. public static BcelShadow makeUnfinishedInitialization(BcelWorld world, LazyMethodGen constructor) {
  570. BcelShadow ret = new BcelShadow(world, Initialization, world.makeJoinPointSignatureFromMethod(constructor,
  571. Member.CONSTRUCTOR), constructor, null);
  572. if (constructor.getEffectiveSignature() != null) {
  573. ret.setMatchingSignature(constructor.getEffectiveSignature().getEffectiveSignature());
  574. }
  575. return ret;
  576. }
  577. public static BcelShadow makeUnfinishedPreinitialization(BcelWorld world, LazyMethodGen constructor) {
  578. BcelShadow ret = new BcelShadow(world, PreInitialization, world.makeJoinPointSignatureFromMethod(constructor,
  579. Member.CONSTRUCTOR), constructor, null);
  580. if (constructor.getEffectiveSignature() != null) {
  581. ret.setMatchingSignature(constructor.getEffectiveSignature().getEffectiveSignature());
  582. }
  583. return ret;
  584. }
  585. public static BcelShadow makeMethodExecution(BcelWorld world, LazyMethodGen enclosingMethod, boolean lazyInit) {
  586. if (!lazyInit) {
  587. return makeMethodExecution(world, enclosingMethod);
  588. }
  589. BcelShadow s = new BcelShadow(world, MethodExecution, enclosingMethod.getMemberView(), enclosingMethod, null);
  590. return s;
  591. }
  592. public void init() {
  593. if (range != null) {
  594. return;
  595. }
  596. final InstructionList body = enclosingMethod.getBody();
  597. ShadowRange r = new ShadowRange(body);
  598. r.associateWithShadow(this);
  599. r.associateWithTargets(Range.genStart(body), Range.genEnd(body));
  600. }
  601. public static BcelShadow makeMethodExecution(BcelWorld world, LazyMethodGen enclosingMethod) {
  602. return makeShadowForMethod(world, enclosingMethod, MethodExecution, enclosingMethod.getMemberView());
  603. }
  604. public static BcelShadow makeShadowForMethod(BcelWorld world, LazyMethodGen enclosingMethod, Shadow.Kind kind, Member sig) {
  605. final InstructionList body = enclosingMethod.getBody();
  606. BcelShadow s = new BcelShadow(world, kind, sig, enclosingMethod, null);
  607. ShadowRange r = new ShadowRange(body);
  608. r.associateWithShadow(s);
  609. r.associateWithTargets(// OPTIMIZE this occurs lots of times for all jp kinds...
  610. Range.genStart(body), Range.genEnd(body));
  611. return s;
  612. }
  613. public static BcelShadow makeAdviceExecution(BcelWorld world, LazyMethodGen enclosingMethod) {
  614. final InstructionList body = enclosingMethod.getBody();
  615. BcelShadow s = new BcelShadow(world, AdviceExecution,
  616. world.makeJoinPointSignatureFromMethod(enclosingMethod, Member.ADVICE), enclosingMethod, null);
  617. ShadowRange r = new ShadowRange(body);
  618. r.associateWithShadow(s);
  619. r.associateWithTargets(Range.genStart(body), Range.genEnd(body));
  620. return s;
  621. }
  622. // constructor call shadows are <em>initially</em> just around the
  623. // call to the constructor. If ANY advice gets put on it, we move
  624. // the NEW instruction inside the join point, which involves putting
  625. // all the arguments in temps.
  626. public static BcelShadow makeConstructorCall(BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle callHandle,
  627. BcelShadow enclosingShadow) {
  628. final InstructionList body = enclosingMethod.getBody();
  629. Member sig = world.makeJoinPointSignatureForMethodInvocation(enclosingMethod.getEnclosingClass(),
  630. (InvokeInstruction) callHandle.getInstruction());
  631. BcelShadow s = new BcelShadow(world, ConstructorCall, sig, enclosingMethod, enclosingShadow);
  632. ShadowRange r = new ShadowRange(body);
  633. r.associateWithShadow(s);
  634. r.associateWithTargets(Range.genStart(body, callHandle), Range.genEnd(body, callHandle));
  635. retargetAllBranches(callHandle, r.getStart());
  636. return s;
  637. }
  638. public static BcelShadow makeArrayConstructorCall(BcelWorld world, LazyMethodGen enclosingMethod,
  639. InstructionHandle arrayInstruction, BcelShadow enclosingShadow) {
  640. final InstructionList body = enclosingMethod.getBody();
  641. Member sig = world.makeJoinPointSignatureForArrayConstruction(enclosingMethod.getEnclosingClass(), arrayInstruction);
  642. BcelShadow s = new BcelShadow(world, ConstructorCall, sig, enclosingMethod, enclosingShadow);
  643. ShadowRange r = new ShadowRange(body);
  644. r.associateWithShadow(s);
  645. r.associateWithTargets(Range.genStart(body, arrayInstruction), Range.genEnd(body, arrayInstruction));
  646. retargetAllBranches(arrayInstruction, r.getStart());
  647. return s;
  648. }
  649. public static BcelShadow makeMonitorEnter(BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle monitorInstruction,
  650. BcelShadow enclosingShadow) {
  651. final InstructionList body = enclosingMethod.getBody();
  652. Member sig = world.makeJoinPointSignatureForMonitorEnter(enclosingMethod.getEnclosingClass(), monitorInstruction);
  653. BcelShadow s = new BcelShadow(world, SynchronizationLock, sig, enclosingMethod, enclosingShadow);
  654. ShadowRange r = new ShadowRange(body);
  655. r.associateWithShadow(s);
  656. r.associateWithTargets(Range.genStart(body, monitorInstruction), Range.genEnd(body, monitorInstruction));
  657. retargetAllBranches(monitorInstruction, r.getStart());
  658. return s;
  659. }
  660. public static BcelShadow makeMonitorExit(BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle monitorInstruction,
  661. BcelShadow enclosingShadow) {
  662. final InstructionList body = enclosingMethod.getBody();
  663. Member sig = world.makeJoinPointSignatureForMonitorExit(enclosingMethod.getEnclosingClass(), monitorInstruction);
  664. BcelShadow s = new BcelShadow(world, SynchronizationUnlock, sig, enclosingMethod, enclosingShadow);
  665. ShadowRange r = new ShadowRange(body);
  666. r.associateWithShadow(s);
  667. r.associateWithTargets(Range.genStart(body, monitorInstruction), Range.genEnd(body, monitorInstruction));
  668. retargetAllBranches(monitorInstruction, r.getStart());
  669. return s;
  670. }
  671. // see pr77166
  672. // public static BcelShadow makeArrayLoadCall(
  673. // BcelWorld world,
  674. // LazyMethodGen enclosingMethod,
  675. // InstructionHandle arrayInstruction,
  676. // BcelShadow enclosingShadow)
  677. // {
  678. // final InstructionList body = enclosingMethod.getBody();
  679. // Member sig = world.makeJoinPointSignatureForArrayLoad(enclosingMethod.getEnclosingClass(),arrayInstruction);
  680. // BcelShadow s =
  681. // new BcelShadow(
  682. // world,
  683. // MethodCall,
  684. // sig,
  685. // enclosingMethod,
  686. // enclosingShadow);
  687. // ShadowRange r = new ShadowRange(body);
  688. // r.associateWithShadow(s);
  689. // r.associateWithTargets(
  690. // Range.genStart(body, arrayInstruction),
  691. // Range.genEnd(body, arrayInstruction));
  692. // retargetAllBranches(arrayInstruction, r.getStart());
  693. // return s;
  694. // }
  695. public static BcelShadow makeMethodCall(BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle callHandle,
  696. BcelShadow enclosingShadow) {
  697. final InstructionList body = enclosingMethod.getBody();
  698. BcelShadow s = new BcelShadow(world, MethodCall, world.makeJoinPointSignatureForMethodInvocation(
  699. enclosingMethod.getEnclosingClass(), (InvokeInstruction) callHandle.getInstruction()), enclosingMethod,
  700. enclosingShadow);
  701. ShadowRange r = new ShadowRange(body);
  702. r.associateWithShadow(s);
  703. r.associateWithTargets(Range.genStart(body, callHandle), Range.genEnd(body, callHandle));
  704. retargetAllBranches(callHandle, r.getStart());
  705. return s;
  706. }
  707. public static BcelShadow makeShadowForMethodCall(BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle callHandle,
  708. BcelShadow enclosingShadow, Kind kind, ResolvedMember sig) {
  709. final InstructionList body = enclosingMethod.getBody();
  710. BcelShadow s = new BcelShadow(world, kind, sig, enclosingMethod, enclosingShadow);
  711. ShadowRange r = new ShadowRange(body);
  712. r.associateWithShadow(s);
  713. r.associateWithTargets(Range.genStart(body, callHandle), Range.genEnd(body, callHandle));
  714. retargetAllBranches(callHandle, r.getStart());
  715. return s;
  716. }
  717. public static BcelShadow makeFieldGet(BcelWorld world, ResolvedMember field, LazyMethodGen enclosingMethod,
  718. InstructionHandle getHandle, BcelShadow enclosingShadow) {
  719. final InstructionList body = enclosingMethod.getBody();
  720. BcelShadow s = new BcelShadow(world, FieldGet, field,
  721. // BcelWorld.makeFieldSignature(
  722. // enclosingMethod.getEnclosingClass(),
  723. // (FieldInstruction) getHandle.getInstruction()),
  724. enclosingMethod, enclosingShadow);
  725. ShadowRange r = new ShadowRange(body);
  726. r.associateWithShadow(s);
  727. r.associateWithTargets(Range.genStart(body, getHandle), Range.genEnd(body, getHandle));
  728. retargetAllBranches(getHandle, r.getStart());
  729. return s;
  730. }
  731. public static BcelShadow makeFieldSet(BcelWorld world, ResolvedMember field, LazyMethodGen enclosingMethod,
  732. InstructionHandle setHandle, BcelShadow enclosingShadow) {
  733. final InstructionList body = enclosingMethod.getBody();
  734. BcelShadow s = new BcelShadow(world, FieldSet, field,
  735. // BcelWorld.makeFieldJoinPointSignature(
  736. // enclosingMethod.getEnclosingClass(),
  737. // (FieldInstruction) setHandle.getInstruction()),
  738. enclosingMethod, enclosingShadow);
  739. ShadowRange r = new ShadowRange(body);
  740. r.associateWithShadow(s);
  741. r.associateWithTargets(Range.genStart(body, setHandle), Range.genEnd(body, setHandle));
  742. retargetAllBranches(setHandle, r.getStart());
  743. return s;
  744. }
  745. public static void retargetAllBranches(InstructionHandle from, InstructionHandle to) {
  746. for (InstructionTargeter source : from.getTargetersCopy()) {
  747. if (source instanceof InstructionBranch) {
  748. source.updateTarget(from, to);
  749. }
  750. }
  751. }
  752. // // ---- type access methods
  753. // private ObjectType getTargetBcelType() {
  754. // return (ObjectType) BcelWorld.makeBcelType(getTargetType());
  755. // }
  756. // private Type getArgBcelType(int arg) {
  757. // return BcelWorld.makeBcelType(getArgType(arg));
  758. // }
  759. // ---- kinding
  760. /**
  761. * If the end of my range has no real instructions following then my context needs a return at the end.
  762. */
  763. public boolean terminatesWithReturn() {
  764. return getRange().getRealNext() == null;
  765. }
  766. /**
  767. * Is arg0 occupied with the value of this
  768. */
  769. public boolean arg0HoldsThis() {
  770. if (getKind().isEnclosingKind()) {
  771. return !Modifier.isStatic(getSignature().getModifiers());
  772. } else if (enclosingShadow == null) {
  773. // XXX this is mostly right
  774. // this doesn't do the right thing for calls in the pre part of introduced constructors.
  775. return !enclosingMethod.isStatic();
  776. } else {
  777. return ((BcelShadow) enclosingShadow).arg0HoldsThis();
  778. }
  779. }
  780. // ---- argument getting methods
  781. private BcelVar thisVar = null;
  782. private BcelVar targetVar = null;
  783. private BcelVar[] argVars = null;
  784. private Map<ResolvedType, AnnotationAccessVar> kindedAnnotationVars = null;
  785. private Map<ResolvedType, TypeAnnotationAccessVar> thisAnnotationVars = null;
  786. private Map<ResolvedType, TypeAnnotationAccessVar> targetAnnotationVars = null;
  787. // private Map/* <UnresolvedType,BcelVar> */[] argAnnotationVars = null;
  788. private Map<ResolvedType, AnnotationAccessVar> withinAnnotationVars = null;
  789. private Map<ResolvedType, AnnotationAccessVar> withincodeAnnotationVars = null;
  790. private boolean allArgVarsInitialized = false;
  791. // If in annotation style and the relevant advice is using PJP then this will
  792. // be set to true when the closure variable is initialized - if it gets set
  793. // (which means link() has been called) then we will need to call unlink()
  794. // after the code has been run.
  795. boolean closureVarInitialized = false;
  796. @Override
  797. public Var getThisVar() {
  798. if (!hasThis()) {
  799. throw new IllegalStateException("no this");
  800. }
  801. initializeThisVar();
  802. return thisVar;
  803. }
  804. @Override
  805. public Var getThisAnnotationVar(UnresolvedType forAnnotationType) {
  806. if (!hasThis()) {
  807. throw new IllegalStateException("no this");
  808. }
  809. initializeThisAnnotationVars(); // FIXME asc Why bother with this if we always return one?
  810. // Even if we can't find one, we have to return one as we might have this annotation at runtime
  811. Var v = thisAnnotationVars.get(forAnnotationType);
  812. if (v == null) {
  813. v = new TypeAnnotationAccessVar(forAnnotationType.resolve(world), (BcelVar) getThisVar());
  814. }
  815. return v;
  816. }
  817. @Override
  818. public Var getTargetVar() {
  819. if (!hasTarget()) {
  820. throw new IllegalStateException("no target");
  821. }
  822. initializeTargetVar();
  823. return targetVar;
  824. }
  825. @Override
  826. public Var getTargetAnnotationVar(UnresolvedType forAnnotationType) {
  827. if (!hasTarget()) {
  828. throw new IllegalStateException("no target");
  829. }
  830. initializeTargetAnnotationVars(); // FIXME asc why bother with this if we always return one?
  831. Var v = targetAnnotationVars.get(forAnnotationType);
  832. // Even if we can't find one, we have to return one as we might have this annotation at runtime
  833. if (v == null) {
  834. v = new TypeAnnotationAccessVar(forAnnotationType.resolve(world), (BcelVar) getTargetVar());
  835. }
  836. return v;
  837. }
  838. @Override
  839. public Var getArgVar(int i) {
  840. ensureInitializedArgVar(i);
  841. return argVars[i];
  842. }
  843. @Override
  844. public Var getArgAnnotationVar(int i, UnresolvedType forAnnotationType) {
  845. return new TypeAnnotationAccessVar(forAnnotationType.resolve(world), (BcelVar) getArgVar(i));
  846. // initializeArgAnnotationVars();
  847. //
  848. // Var v = (Var) argAnnotationVars[i].get(forAnnotationType);
  849. // if (v == null) {
  850. // v = new TypeAnnotationAccessVar(forAnnotationType.resolve(world), (BcelVar) getArgVar(i));
  851. // }
  852. // return v;
  853. }
  854. @Override
  855. public Var getKindedAnnotationVar(UnresolvedType forAnnotationType) {
  856. initializeKindedAnnotationVars();
  857. return kindedAnnotationVars.get(forAnnotationType);
  858. }
  859. @Override
  860. public Var getWithinAnnotationVar(UnresolvedType forAnnotationType) {
  861. initializeWithinAnnotationVars();
  862. return withinAnnotationVars.get(forAnnotationType);
  863. }
  864. @Override
  865. public Var getWithinCodeAnnotationVar(UnresolvedType forAnnotationType) {
  866. initializeWithinCodeAnnotationVars();
  867. return withincodeAnnotationVars.get(forAnnotationType);
  868. }
  869. // reflective thisJoinPoint support
  870. private BcelVar thisJoinPointVar = null;
  871. private boolean isThisJoinPointLazy;
  872. private int lazyTjpConsumers = 0;
  873. private BcelVar thisJoinPointStaticPartVar = null;
  874. // private BcelVar thisEnclosingJoinPointStaticPartVar = null;
  875. @Override
  876. public final Var getThisJoinPointStaticPartVar() {
  877. return getThisJoinPointStaticPartBcelVar();
  878. }
  879. @Override
  880. public final Var getThisEnclosingJoinPointStaticPartVar() {
  881. return getThisEnclosingJoinPointStaticPartBcelVar();
  882. }
  883. public void requireThisJoinPoint(boolean hasGuardTest, boolean isAround) {
  884. if (!isAround) {
  885. if (!hasGuardTest) {
  886. isThisJoinPointLazy = false;
  887. } else {
  888. lazyTjpConsumers++;
  889. }
  890. }
  891. // if (!hasGuardTest) {
  892. // isThisJoinPointLazy = false;
  893. // } else {
  894. // lazyTjpConsumers++;
  895. // }
  896. if (thisJoinPointVar == null) {
  897. thisJoinPointVar = genTempVar(UnresolvedType.forName("org.aspectj.lang.JoinPoint"));
  898. }
  899. }
  900. @Override
  901. public Var getThisJoinPointVar() {
  902. requireThisJoinPoint(false, false);
  903. return thisJoinPointVar;
  904. }
  905. void initializeThisJoinPoint() {
  906. if (thisJoinPointVar == null) {
  907. return;
  908. }
  909. if (isThisJoinPointLazy) {
  910. isThisJoinPointLazy = checkLazyTjp();
  911. }
  912. if (isThisJoinPointLazy) {
  913. appliedLazyTjpOptimization = true;
  914. createThisJoinPoint(); // make sure any state needed is initialized, but throw the instructions out
  915. if (lazyTjpConsumers == 1) {
  916. return; // special case only one lazyTjpUser
  917. }
  918. InstructionFactory fact = getFactory();
  919. InstructionList il = new InstructionList();
  920. il.append(InstructionConstants.ACONST_NULL);
  921. il.append(thisJoinPointVar.createStore(fact));
  922. range.insert(il, Range.OutsideBefore);
  923. } else {
  924. appliedLazyTjpOptimization = false;
  925. InstructionFactory fact = getFactory();
  926. InstructionList il = createThisJoinPoint();
  927. il.append(thisJoinPointVar.createStore(fact));
  928. range.insert(il, Range.OutsideBefore);
  929. }
  930. }
  931. private boolean checkLazyTjp() {
  932. // check for around advice
  933. for (ShadowMunger munger : mungers) {
  934. if (munger instanceof Advice) {
  935. if (((Advice) munger).getKind() == AdviceKind.Around) {
  936. if (munger.getSourceLocation() != null) { // do we know enough to bother reporting?
  937. if (world.getLint().canNotImplementLazyTjp.isEnabled()) {
  938. world.getLint().canNotImplementLazyTjp.signal(new String[]{toString()}, getSourceLocation(),
  939. new ISourceLocation[]{munger.getSourceLocation()});
  940. }
  941. }
  942. return false;
  943. }
  944. }
  945. }
  946. return true;
  947. }
  948. InstructionList loadThisJoinPoint() {
  949. InstructionFactory fact = getFactory();
  950. InstructionList il = new InstructionList();
  951. if (isThisJoinPointLazy) {
  952. // If we're lazy, build the join point right here.
  953. il.append(createThisJoinPoint());
  954. // Does someone else need it? If so, store it for later retrieval
  955. if (lazyTjpConsumers > 1) {
  956. il.append(thisJoinPointVar.createStore(fact));
  957. InstructionHandle end = il.append(thisJoinPointVar.createLoad(fact));
  958. il.insert(InstructionFactory.createBranchInstruction(Constants.IFNONNULL, end));
  959. il.insert(thisJoinPointVar.createLoad(fact));
  960. }
  961. } else {
  962. // If not lazy, its already been built and stored, just retrieve it
  963. thisJoinPointVar.appendLoad(il, fact);
  964. }
  965. return il;
  966. }
  967. InstructionList createThisJoinPoint() {
  968. InstructionFactory fact = getFactory();
  969. InstructionList il = new InstructionList();
  970. BcelVar staticPart = getThisJoinPointStaticPartBcelVar();
  971. staticPart.appendLoad(il, fact);
  972. if (hasThis()) {
  973. ((BcelVar) getThisVar()).appendLoad(il, fact);
  974. } else {
  975. il.append(InstructionConstants.ACONST_NULL);
  976. }
  977. if (hasTarget()) {
  978. ((BcelVar) getTargetVar()).appendLoad(il, fact);
  979. } else {
  980. il.append(InstructionConstants.ACONST_NULL);
  981. }
  982. switch (getArgCount()) {
  983. case 0:
  984. il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory", "makeJP", LazyClassGen.tjpType, new Type[] {
  985. LazyClassGen.staticTjpType, Type.OBJECT, Type.OBJECT }, Constants.INVOKESTATIC));
  986. break;
  987. case 1:
  988. ((BcelVar) getArgVar(0)).appendLoadAndConvert(il, fact, world.getCoreType(ResolvedType.OBJECT));
  989. il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory", "makeJP", LazyClassGen.tjpType, new Type[] {
  990. LazyClassGen.staticTjpType, Type.OBJECT, Type.OBJECT, Type.OBJECT }, Constants.INVOKESTATIC));
  991. break;
  992. case 2:
  993. ((BcelVar) getArgVar(0)).appendLoadAndConvert(il, fact, world.getCoreType(ResolvedType.OBJECT));
  994. ((BcelVar) getArgVar(1)).appendLoadAndConvert(il, fact, world.getCoreType(ResolvedType.OBJECT));
  995. il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory", "makeJP", LazyClassGen.tjpType, new Type[] {
  996. LazyClassGen.staticTjpType, Type.OBJECT, Type.OBJECT, Type.OBJECT, Type.OBJECT }, Constants.INVOKESTATIC));
  997. break;
  998. default:
  999. il.append(makeArgsObjectArray());
  1000. il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory", "makeJP", LazyClassGen.tjpType, new Type[] {
  1001. LazyClassGen.staticTjpType, Type.OBJECT, Type.OBJECT, new ArrayType(Type.OBJECT, 1) }, Constants.INVOKESTATIC));
  1002. break;
  1003. }
  1004. return il;
  1005. }
  1006. public BcelVar getThisJoinPointStaticPartBcelVar() {
  1007. return getThisJoinPointStaticPartBcelVar(false);
  1008. }
  1009. @Override
  1010. public BcelVar getThisAspectInstanceVar(ResolvedType aspectType) {
  1011. return new AspectInstanceVar(aspectType);
  1012. }
  1013. /**
  1014. * Get the Var for the xxxxJpStaticPart, xxx = this or enclosing
  1015. *
  1016. * @param isEnclosingJp true to have the enclosingJpStaticPart
  1017. * @return
  1018. */
  1019. public BcelVar getThisJoinPointStaticPartBcelVar(final boolean isEnclosingJp) {
  1020. if (thisJoinPointStaticPartVar == null) {
  1021. Field field = getEnclosingClass().getTjpField(this, isEnclosingJp);
  1022. ResolvedType sjpType = null;
  1023. if (world.isTargettingAspectJRuntime12()) { // TAG:SUPPORTING12: We didn't have different jpsp types in 1.2
  1024. sjpType = world.getCoreType(UnresolvedType.JOINPOINT_STATICPART);
  1025. } else {
  1026. sjpType = isEnclosingJp ? world.getCoreType(UnresolvedType.JOINPOINT_ENCLOSINGSTATICPART) : world
  1027. .getCoreType(UnresolvedType.JOINPOINT_STATICPART);
  1028. }
  1029. thisJoinPointStaticPartVar = new BcelFieldRef(sjpType, getEnclosingClass().getClassName(), field.getName());
  1030. // getEnclosingClass().warnOnAddedStaticInitializer(this,munger.getSourceLocation());
  1031. }
  1032. return thisJoinPointStaticPartVar;
  1033. }
  1034. /**
  1035. * Get the Var for the enclosingJpStaticPart
  1036. *
  1037. * @return
  1038. */
  1039. public BcelVar getThisEnclosingJoinPointStaticPartBcelVar() {
  1040. if (enclosingShadow == null) {
  1041. // the enclosing of an execution is itself
  1042. return getThisJoinPointStaticPartBcelVar(true);
  1043. } else {
  1044. return ((BcelShadow) enclosingShadow).getThisJoinPointStaticPartBcelVar(true);
  1045. }
  1046. }
  1047. // ??? need to better understand all the enclosing variants
  1048. @Override
  1049. public Member getEnclosingCodeSignature() {
  1050. if (getKind().isEnclosingKind()) {
  1051. return getSignature();
  1052. } else if (getKind() == Shadow.PreInitialization) {
  1053. // PreInit doesn't enclose code but its signature
  1054. // is correctly the signature of the ctor.
  1055. return getSignature();
  1056. } else if (enclosingShadow == null) {
  1057. return getEnclosingMethod().getMemberView();
  1058. } else {
  1059. return enclosingShadow.getSignature();
  1060. }
  1061. }
  1062. public Member getRealEnclosingCodeSignature() {
  1063. return enclosingMethod.getMemberView();
  1064. }
  1065. // public Member getEnclosingCodeSignatureForModel() {
  1066. // if (getKind().isEnclosingKind()) {
  1067. // return getSignature();
  1068. // } else if (getKind() == Shadow.PreInitialization) {
  1069. // // PreInit doesn't enclose code but its signature
  1070. // // is correctly the signature of the ctor.
  1071. // return getSignature();
  1072. // } else if (enclosingShadow == null) {
  1073. // return getEnclosingMethod().getMemberView();
  1074. // } else {
  1075. // if (enclosingShadow.getKind() == Shadow.MethodExecution && enclosingMethod.getEffectiveSignature() != null) {
  1076. //
  1077. // } else {
  1078. // return enclosingShadow.getSignature();
  1079. // }
  1080. // }
  1081. // }
  1082. private InstructionList makeArgsObjectArray() {
  1083. InstructionFactory fact = getFactory();
  1084. BcelVar arrayVar = genTempVar(UnresolvedType.OBJECTARRAY);
  1085. final InstructionList il = new InstructionList();
  1086. int alen = getArgCount();
  1087. il.append(Utility.createConstant(fact, alen));
  1088. il.append(fact.createNewArray(Type.OBJECT, (short) 1));
  1089. arrayVar.appendStore(il, fact);
  1090. int stateIndex = 0;
  1091. for (int i = 0, len = getArgCount(); i < len; i++) {
  1092. arrayVar.appendConvertableArrayStore(il, fact, stateIndex, (BcelVar) getArgVar(i));
  1093. stateIndex++;
  1094. }
  1095. arrayVar.appendLoad(il, fact);
  1096. return il;
  1097. }
  1098. // ---- initializing var tables
  1099. /*
  1100. * initializing this is doesn't do anything, because this is protected from side-effects, so we don't need to copy its location
  1101. */
  1102. private void initializeThisVar() {
  1103. if (thisVar != null) {
  1104. return;
  1105. }
  1106. thisVar = new BcelVar(getThisType().resolve(world), 0);
  1107. thisVar.setPositionInAroundState(0);
  1108. }
  1109. public void initializeTargetVar() {
  1110. InstructionFactory fact = getFactory();
  1111. if (targetVar != null) {
  1112. return;
  1113. }
  1114. if (getKind().isTargetSameAsThis()) {
  1115. if (hasThis()) {
  1116. initializeThisVar();
  1117. }
  1118. targetVar = thisVar;
  1119. } else {
  1120. initializeArgVars(); // gotta pop off the args before we find the target
  1121. UnresolvedType type = getTargetType();
  1122. type = ensureTargetTypeIsCorrect(type);
  1123. targetVar = genTempVar(type, "ajc$target");
  1124. range.insert(targetVar.createStore(fact), Range.OutsideBefore);
  1125. targetVar.setPositionInAroundState(hasThis() ? 1 : 0);
  1126. }
  1127. }
  1128. /*
  1129. * PR 72528 This method double checks the target type under certain conditions. The Java 1.4 compilers seem to take calls to
  1130. * clone methods on array types and create bytecode that looks like clone is being called on Object. If we advise a clone call
  1131. * with around advice we extract the call into a helper method which we can then refer to. Because the type in the bytecode for
  1132. * the call to clone is Object we create a helper method with an Object parameter - this is not correct as we have lost the fact
  1133. * that the actual type is an array type. If we don't do the check below we will create code that fails java verification. This
  1134. * method checks for the peculiar set of conditions and if they are true, it has a sneak peek at the code before the call to see
  1135. * what is on the stack.
  1136. */
  1137. public UnresolvedType ensureTargetTypeIsCorrect(UnresolvedType tx) {
  1138. Member msig = getSignature();
  1139. if (msig.getArity() == 0 && getKind() == MethodCall && msig.getName().charAt(0) == 'c' && tx.equals(ResolvedType.OBJECT)
  1140. && msig.getReturnType().equals(ResolvedType.OBJECT) && msig.getName().equals("clone")) {
  1141. // Lets go back through the code from the start of the shadow
  1142. InstructionHandle searchPtr = range.getStart().getPrev();
  1143. while (Range.isRangeHandle(searchPtr) || searchPtr.getInstruction().isStoreInstruction()) { // ignore this instruction -
  1144. // it doesnt give us the
  1145. // info we want
  1146. searchPtr = searchPtr.getPrev();
  1147. }
  1148. // A load instruction may tell us the real type of what the clone() call is on
  1149. if (searchPtr.getInstruction().isLoadInstruction()) {
  1150. LocalVariableTag lvt = LazyMethodGen.getLocalVariableTag(searchPtr, searchPtr.getInstruction().getIndex());
  1151. if (lvt != null) {
  1152. return UnresolvedType.forSignature(lvt.getType());
  1153. }
  1154. }
  1155. // A field access instruction may tell us the real type of what the clone() call is on
  1156. if (searchPtr.getInstruction() instanceof FieldInstruction) {
  1157. FieldInstruction si = (FieldInstruction) searchPtr.getInstruction();
  1158. Type t = si.getFieldType(getEnclosingClass().getConstantPool());
  1159. return BcelWorld.fromBcel(t);
  1160. }
  1161. // A new array instruction obviously tells us it is an array type !
  1162. if (searchPtr.getInstruction().opcode == Constants.ANEWARRAY) {
  1163. // ANEWARRAY ana = (ANEWARRAY)searchPoint.getInstruction();
  1164. // Type t = ana.getType(getEnclosingClass().getConstantPool());
  1165. // Just use a standard java.lang.object array - that will work fine
  1166. return BcelWorld.fromBcel(new ArrayType(Type.OBJECT, 1));
  1167. }
  1168. // A multi new array instruction obviously tells us it is an array type !
  1169. if (searchPtr.getInstruction() instanceof MULTIANEWARRAY) {
  1170. MULTIANEWARRAY ana = (MULTIANEWARRAY) searchPtr.getInstruction();
  1171. // Type t = ana.getType(getEnclosingClass().getConstantPool());
  1172. // t = new ArrayType(t,ana.getDimensions());
  1173. // Just use a standard java.lang.object array - that will work fine
  1174. return BcelWorld.fromBcel(new ArrayType(Type.OBJECT, ana.getDimensions()));
  1175. }
  1176. throw new BCException("Can't determine real target of clone() when processing instruction "
  1177. + searchPtr.getInstruction() + ". Perhaps avoid selecting clone with your pointcut?");
  1178. }
  1179. return tx;
  1180. }
  1181. public void ensureInitializedArgVar(int argNumber) {
  1182. if (allArgVarsInitialized || (argVars != null && argVars[argNumber] != null)) {
  1183. return;
  1184. }
  1185. InstructionFactory fact = getFactory();
  1186. int len = getArgCount();
  1187. if (argVars == null) {
  1188. argVars = new BcelVar[len];
  1189. }
  1190. // Need to initialize argument i
  1191. int positionOffset = (hasTarget() ? 1 : 0) + ((hasThis() && !getKind().isTargetSameAsThis()) ? 1 : 0);
  1192. if (getKind().argsOnStack()) {
  1193. // Let's just do them all now since they are on the stack
  1194. // we move backwards because we're popping off the stack
  1195. for (int i = len - 1; i >= 0; i--) {
  1196. UnresolvedType type = getArgType(i);
  1197. BcelVar tmp = genTempVar(type, "ajc$arg" + i);
  1198. range.insert(tmp.createStore(getFactory()), Range.OutsideBefore);
  1199. int position = i;
  1200. position += positionOffset;
  1201. tmp.setPositionInAroundState(position);
  1202. argVars[i] = tmp;
  1203. }
  1204. allArgVarsInitialized = true;
  1205. } else {
  1206. int index = 0;
  1207. if (arg0HoldsThis()) {
  1208. index++;
  1209. }
  1210. boolean allInited = true;
  1211. for (int i = 0; i < len; i++) {
  1212. UnresolvedType type = getArgType(i);
  1213. if (i == argNumber) {
  1214. argVars[argNumber] = genTempVar(type, "ajc$arg" + argNumber);
  1215. range.insert(argVars[argNumber].createCopyFrom(fact, index), Range.OutsideBefore);
  1216. argVars[argNumber].setPositionInAroundState(argNumber + positionOffset);
  1217. }
  1218. allInited = allInited && argVars[i] != null;
  1219. index += type.getSize();
  1220. }
  1221. if (allInited && (argNumber + 1) == len) {
  1222. allArgVarsInitialized = true;
  1223. }
  1224. }
  1225. }
  1226. /**
  1227. * Initialize all the available arguments at the shadow. This means creating a copy of them that we can then use for advice
  1228. * calls (the copy ensures we are not affected by other advice changing the values). This method initializes all arguments
  1229. * whereas the method ensureInitializedArgVar will only ensure a single argument is setup.
  1230. */
  1231. public void initializeArgVars() {
  1232. if (allArgVarsInitialized) {
  1233. return;
  1234. }
  1235. InstructionFactory fact = getFactory();
  1236. int len = getArgCount();
  1237. if (argVars == null) {
  1238. argVars = new BcelVar[len];
  1239. }
  1240. int positionOffset = (hasTarget() ? 1 : 0) + ((hasThis() && !getKind().isTargetSameAsThis()) ? 1 : 0);
  1241. if (getKind().argsOnStack()) {
  1242. // we move backwards because we're popping off the stack
  1243. for (int i = len - 1; i >= 0; i--) {
  1244. UnresolvedType type = getArgType(i);
  1245. BcelVar tmp = genTempVar(type, "ajc$arg" + i);
  1246. range.insert(tmp.createStore(getFactory()), Range.OutsideBefore);
  1247. int position = i;
  1248. position += positionOffset;
  1249. tmp.setPositionInAroundState(position);
  1250. argVars[i] = tmp;
  1251. }
  1252. } else {
  1253. int index = 0;
  1254. if (arg0HoldsThis()) {
  1255. index++;
  1256. }
  1257. for (int i = 0; i < len; i++) {
  1258. UnresolvedType type = getArgType(i);
  1259. if (argVars[i] == null) {
  1260. BcelVar tmp = genTempVar(type, "ajc$arg" + i);
  1261. range.insert(tmp.createCopyFrom(fact, index), Range.OutsideBefore);
  1262. argVars[i] = tmp;
  1263. tmp.setPositionInAroundState(i + positionOffset);
  1264. }
  1265. index += type.resolve(world).getSize();
  1266. }
  1267. }
  1268. allArgVarsInitialized = true;
  1269. }
  1270. public void initializeForAroundClosure() {
  1271. initializeArgVars();
  1272. if (hasTarget()) {
  1273. initializeTargetVar();
  1274. }
  1275. if (hasThis()) {
  1276. initializeThisVar();
  1277. // System.out.println("initialized: " + this + " thisVar = " + thisVar);
  1278. }
  1279. }
  1280. public void initializeThisAnnotationVars() {
  1281. if (thisAnnotationVars != null) {
  1282. return;
  1283. }
  1284. thisAnnotationVars = new HashMap<>();
  1285. // populate..
  1286. }
  1287. public void initializeTargetAnnotationVars() {
  1288. if (targetAnnotationVars != null) {
  1289. return;
  1290. }
  1291. if (getKind().isTargetSameAsThis()) {
  1292. if (hasThis()) {
  1293. initializeThisAnnotationVars();
  1294. }
  1295. targetAnnotationVars = thisAnnotationVars;
  1296. } else {
  1297. targetAnnotationVars = new HashMap<>();
  1298. ResolvedType[] rtx = this.getTargetType().resolve(world).getAnnotationTypes(); // what about annotations we havent
  1299. // gotten yet but we will get in
  1300. // subclasses?
  1301. for (ResolvedType typeX : rtx) {
  1302. targetAnnotationVars.put(typeX, new TypeAnnotationAccessVar(typeX, (BcelVar) getTargetVar()));
  1303. }
  1304. // populate.
  1305. }
  1306. }
  1307. // public void initializeArgAnnotationVars() {
  1308. // if (argAnnotationVars != null) {
  1309. // return;
  1310. // }
  1311. // int numArgs = getArgCount();
  1312. // argAnnotationVars = new Map[numArgs];
  1313. // for (int i = 0; i < argAnnotationVars.length; i++) {
  1314. // argAnnotationVars[i] = new HashMap();
  1315. // // FIXME asc just delete this logic - we always build the Var on demand, as we don't know at weave time
  1316. // // what the full set of annotations could be (due to static/dynamic type differences...)
  1317. // }
  1318. // }
  1319. protected ResolvedMember getRelevantMember(ResolvedMember foundMember, Member relevantMember, ResolvedType relevantType) {
  1320. if (foundMember != null) {
  1321. return foundMember;
  1322. }
  1323. foundMember = getSignature().resolve(world);
  1324. if (foundMember == null && relevantMember != null) {
  1325. foundMember = relevantType.lookupMemberWithSupersAndITDs(relevantMember);
  1326. }
  1327. // check the ITD'd dooberries
  1328. List<ConcreteTypeMunger> mungers = relevantType.resolve(world).getInterTypeMungers();
  1329. for (ConcreteTypeMunger typeMunger : mungers) {
  1330. if (typeMunger.getMunger() instanceof NewMethodTypeMunger || typeMunger.getMunger() instanceof NewConstructorTypeMunger) {
  1331. ResolvedMember fakerm = typeMunger.getSignature();
  1332. if (fakerm.getName().equals(getSignature().getName())
  1333. && fakerm.getParameterSignature().equals(getSignature().getParameterSignature())) {
  1334. if (foundMember.getKind() == ResolvedMember.CONSTRUCTOR) {
  1335. foundMember = AjcMemberMaker.interConstructor(relevantType, foundMember, typeMunger.getAspectType());
  1336. } else {
  1337. foundMember = AjcMemberMaker.interMethod(foundMember, typeMunger.getAspectType(), false);
  1338. // ResolvedMember o = AjcMemberMaker.interMethodBody(fakerm, typeMunger.getAspectType());
  1339. // // Object os = o.getAnnotations();
  1340. // ResolvedMember foundMember2 = findMethod(typeMunger.getAspectType(), o);
  1341. // Object os2 = foundMember2.getAnnotations();
  1342. // int stop = 1;
  1343. // foundMember = foundMember2;
  1344. // foundMember = AjcMemberMaker.interMethod(foundMember, typeMunger.getAspectType());
  1345. }
  1346. // in the above.. what about if it's on an Interface? Can that happen?
  1347. // then the last arg of the above should be true
  1348. return foundMember;
  1349. }
  1350. }
  1351. }
  1352. return foundMember;
  1353. }
  1354. protected ResolvedType[] getAnnotations(ResolvedMember foundMember, Member relevantMember, ResolvedType relevantType) {
  1355. if (foundMember == null) {
  1356. // check the ITD'd dooberries
  1357. List<ConcreteTypeMunger> mungers = relevantType.resolve(world).getInterTypeMungers();
  1358. for (ConcreteTypeMunger typeMunger : mungers) {
  1359. if (typeMunger.getMunger() instanceof NewMethodTypeMunger
  1360. || typeMunger.getMunger() instanceof NewConstructorTypeMunger) {
  1361. ResolvedMember fakerm = typeMunger.getSignature();
  1362. // if (fakerm.hasAnnotations())
  1363. ResolvedMember ajcMethod = (getSignature().getKind() == ResolvedMember.CONSTRUCTOR ? AjcMemberMaker
  1364. .postIntroducedConstructor(typeMunger.getAspectType(), fakerm.getDeclaringType(),
  1365. fakerm.getParameterTypes()) : AjcMemberMaker.interMethodDispatcher(fakerm,
  1366. typeMunger.getAspectType()));
  1367. // AjcMemberMaker.interMethodBody(fakerm,typeMunger.getAspectType()));
  1368. ResolvedMember rmm = findMethod(typeMunger.getAspectType(), ajcMethod);
  1369. if (fakerm.getName().equals(getSignature().getName())
  1370. && fakerm.getParameterSignature().equals(getSignature().getParameterSignature())) {
  1371. relevantType = typeMunger.getAspectType();
  1372. foundMember = rmm;
  1373. return foundMember.getAnnotationTypes();
  1374. }
  1375. }
  1376. }
  1377. // didn't find in ITDs, look in supers
  1378. foundMember = relevantType.lookupMemberWithSupersAndITDs(relevantMember);
  1379. if (foundMember == null) {
  1380. throw new IllegalStateException("Couldn't find member " + relevantMember + " for type " + relevantType);
  1381. }
  1382. }
  1383. return foundMember.getAnnotationTypes();
  1384. }
  1385. /**
  1386. * By determining what "kind" of shadow we are, we can find out the annotations on the appropriate element (method, field,
  1387. * constructor, type). Then create one BcelVar entry in the map for each annotation, keyed by annotation type.
  1388. */
  1389. public void initializeKindedAnnotationVars() {
  1390. if (kindedAnnotationVars != null) {
  1391. return;
  1392. }
  1393. kindedAnnotationVars = new HashMap<>();
  1394. ResolvedType[] annotations = null;
  1395. Member shadowSignature = getSignature();
  1396. Member annotationHolder = getSignature();
  1397. ResolvedType relevantType = shadowSignature.getDeclaringType().resolve(world);
  1398. if (relevantType.isRawType() || relevantType.isParameterizedType()) {
  1399. relevantType = relevantType.getGenericType();
  1400. }
  1401. // Determine the annotations that are of interest
  1402. if (getKind() == Shadow.StaticInitialization) {
  1403. annotations = relevantType.resolve(world).getAnnotationTypes();
  1404. } else if (getKind() == Shadow.MethodCall || getKind() == Shadow.ConstructorCall) {
  1405. ResolvedMember foundMember = findMethod2(relevantType.resolve(world).getDeclaredMethods(), getSignature());
  1406. annotations = getAnnotations(foundMember, shadowSignature, relevantType);
  1407. annotationHolder = getRelevantMember(foundMember, shadowSignature, relevantType);
  1408. relevantType = annotationHolder.getDeclaringType().resolve(world);
  1409. } else if (getKind() == Shadow.FieldSet || getKind() == Shadow.FieldGet) {
  1410. annotationHolder = findField(relevantType.getDeclaredFields(), getSignature());
  1411. if (annotationHolder == null) {
  1412. // check the ITD'd dooberries
  1413. List<ConcreteTypeMunger> mungers = relevantType.resolve(world).getInterTypeMungers();
  1414. for (ConcreteTypeMunger typeMunger : mungers) {
  1415. if (typeMunger.getMunger() instanceof NewFieldTypeMunger) {
  1416. ResolvedMember fakerm = typeMunger.getSignature();
  1417. // if (fakerm.hasAnnotations())
  1418. ResolvedMember ajcMethod = AjcMemberMaker.interFieldInitializer(fakerm, typeMunger.getAspectType());
  1419. ResolvedMember rmm = findMethod(typeMunger.getAspectType(), ajcMethod);
  1420. if (fakerm.equals(getSignature())) {
  1421. relevantType = typeMunger.getAspectType();
  1422. annotationHolder = rmm;
  1423. }
  1424. }
  1425. }
  1426. }
  1427. annotations = ((ResolvedMember) annotationHolder).getAnnotationTypes();
  1428. } else if (getKind() == Shadow.MethodExecution || getKind() == Shadow.ConstructorExecution
  1429. || getKind() == Shadow.AdviceExecution) {
  1430. ResolvedMember foundMember = findMethod2(relevantType.getDeclaredMethods(), getSignature());
  1431. annotations = getAnnotations(foundMember, shadowSignature, relevantType);
  1432. annotationHolder = getRelevantMember(foundMember, annotationHolder, relevantType);
  1433. UnresolvedType ut = annotationHolder.getDeclaringType();
  1434. relevantType = ut.resolve(world);
  1435. } else if (getKind() == Shadow.ExceptionHandler) {
  1436. relevantType = getSignature().getParameterTypes()[0].resolve(world);
  1437. annotations = relevantType.getAnnotationTypes();
  1438. } else if (getKind() == Shadow.PreInitialization || getKind() == Shadow.Initialization) {
  1439. ResolvedMember found = findMethod2(relevantType.getDeclaredMethods(), getSignature());
  1440. annotations = found.getAnnotationTypes();
  1441. }
  1442. if (annotations == null) {
  1443. // We can't have recognized the shadow - should blow up now to be on the safe side
  1444. throw new BCException("Could not discover annotations for shadow: " + getKind());
  1445. }
  1446. for (ResolvedType annotationType : annotations) {
  1447. AnnotationAccessVar accessVar = new AnnotationAccessVar(this, getKind(), annotationType.resolve(world), relevantType,
  1448. annotationHolder, false);
  1449. kindedAnnotationVars.put(annotationType, accessVar);
  1450. }
  1451. }
  1452. private ResolvedMember findMethod2(ResolvedMember members[], Member sig) {
  1453. String signatureName = sig.getName();
  1454. String parameterSignature = sig.getParameterSignature();
  1455. for (ResolvedMember member : members) {
  1456. if (member.getName().equals(signatureName) && member.getParameterSignature().equals(parameterSignature)) {
  1457. return member;
  1458. }
  1459. }
  1460. return null;
  1461. }
  1462. private ResolvedMember findMethod(ResolvedType aspectType, ResolvedMember ajcMethod) {
  1463. ResolvedMember decMethods[] = aspectType.getDeclaredMethods();
  1464. for (ResolvedMember member : decMethods) {
  1465. if (member.equals(ajcMethod)) {
  1466. return member;
  1467. }
  1468. }
  1469. return null;
  1470. }
  1471. private ResolvedMember findField(ResolvedMember[] members, Member lookingFor) {
  1472. for (ResolvedMember member : members) {
  1473. if (member.getName().equals(getSignature().getName()) && member.getType().equals(getSignature().getType())) {
  1474. return member;
  1475. }
  1476. }
  1477. return null;
  1478. }
  1479. public void initializeWithinAnnotationVars() {
  1480. if (withinAnnotationVars != null) {
  1481. return;
  1482. }
  1483. withinAnnotationVars = new HashMap<>();
  1484. ResolvedType[] annotations = getEnclosingType().resolve(world).getAnnotationTypes();
  1485. for (ResolvedType ann : annotations) {
  1486. Kind k = Shadow.StaticInitialization;
  1487. withinAnnotationVars.put(ann, new AnnotationAccessVar(this, k, ann, getEnclosingType(), null, true));
  1488. }
  1489. }
  1490. public void initializeWithinCodeAnnotationVars() {
  1491. if (withincodeAnnotationVars != null) {
  1492. return;
  1493. }
  1494. withincodeAnnotationVars = new HashMap<>();
  1495. // For some shadow we are interested in annotations on the method containing that shadow.
  1496. ResolvedType[] annotations = getEnclosingMethod().getMemberView().getAnnotationTypes();
  1497. for (ResolvedType ann : annotations) {
  1498. Kind k = (getEnclosingMethod().getMemberView().getKind() == Member.CONSTRUCTOR ? Shadow.ConstructorExecution
  1499. : Shadow.MethodExecution);
  1500. withincodeAnnotationVars.put(ann, new AnnotationAccessVar(this, k, ann, getEnclosingType(),
  1501. getEnclosingCodeSignature(), true));
  1502. }
  1503. }
  1504. // ---- weave methods
  1505. void weaveBefore(BcelAdvice munger) {
  1506. range.insert(munger.getAdviceInstructions(this, null, range.getRealStart()), Range.InsideBefore);
  1507. }
  1508. public void weaveAfter(BcelAdvice munger) {
  1509. weaveAfterThrowing(munger, UnresolvedType.THROWABLE);
  1510. weaveAfterReturning(munger);
  1511. }
  1512. /**
  1513. * The basic strategy here is to add a set of instructions at the end of the shadow range that dispatch the advice, and then
  1514. * return whatever the shadow was going to return anyway.
  1515. *
  1516. * To achieve this, we note all the return statements in the advice, and replace them with code that: 1) stores the return value
  1517. * on top of the stack in a temp var 2) jumps to the start of our advice block 3) restores the return value at the end of the
  1518. * advice block before ultimately returning
  1519. *
  1520. * We also need to bind the return value into a returning parameter, if the advice specified one.
  1521. */
  1522. public void weaveAfterReturning(BcelAdvice munger) {
  1523. List<InstructionHandle> returns = findReturnInstructions();
  1524. boolean hasReturnInstructions = !returns.isEmpty();
  1525. // list of instructions that handle the actual return from the join point
  1526. InstructionList retList = new InstructionList();
  1527. // variable that holds the return value
  1528. BcelVar returnValueVar = null;
  1529. if (hasReturnInstructions) {
  1530. returnValueVar = generateReturnInstructions(returns, retList);
  1531. } else {
  1532. // we need at least one instruction, as the target for jumps
  1533. retList.append(InstructionConstants.NOP);
  1534. }
  1535. // list of instructions for dispatching to the advice itself
  1536. InstructionList advice = getAfterReturningAdviceDispatchInstructions(munger, retList.getStart());
  1537. if (hasReturnInstructions) {
  1538. InstructionHandle gotoTarget = advice.getStart();
  1539. for (InstructionHandle ih : returns) {
  1540. retargetReturnInstruction(munger.hasExtraParameter(), returnValueVar, gotoTarget, ih);
  1541. }
  1542. }
  1543. range.append(advice);
  1544. range.append(retList);
  1545. }
  1546. /**
  1547. * @return a list of all the return instructions in the range of this shadow
  1548. */
  1549. private List<InstructionHandle> findReturnInstructions() {
  1550. List<InstructionHandle> returns = new ArrayList<>();
  1551. for (InstructionHandle ih = range.getStart(); ih != range.getEnd(); ih = ih.getNext()) {
  1552. if (ih.getInstruction().isReturnInstruction()) {
  1553. returns.add(ih);
  1554. }
  1555. }
  1556. return returns;
  1557. }
  1558. /**
  1559. * Given a list containing all the return instruction handles for this shadow, finds the last return instruction and copies it,
  1560. * making this the ultimate return. If the shadow has a non-void return type, we also create a temporary variable to hold the
  1561. * return value, and load the value from this var before returning (see pr148007 for why we do this - it works around a JRockit
  1562. * bug, and is also closer to what javac generates)
  1563. *
  1564. * Sometimes the 'last return' isnt the right one - some rogue code can include the real return from the body of a subroutine
  1565. * that exists at the end of the method. In this case the last return is RETURN but that may not be correct for a method with a
  1566. * non-void return type... pr151673
  1567. *
  1568. * @param returns list of all the return instructions in the shadow
  1569. * @param returnInstructions instruction list into which the return instructions should be generated
  1570. * @return the variable holding the return value, if needed
  1571. */
  1572. private BcelVar generateReturnInstructions(List<InstructionHandle> returns, InstructionList returnInstructions) {
  1573. BcelVar returnValueVar = null;
  1574. if (this.hasANonVoidReturnType()) {
  1575. // Find the last *correct* return - this is a method with a non-void return type
  1576. // so ignore RETURN
  1577. Instruction newReturnInstruction = null;
  1578. int i = returns.size() - 1;
  1579. while (newReturnInstruction == null && i >= 0) {
  1580. InstructionHandle ih = returns.get(i);
  1581. if (ih.getInstruction().opcode != Constants.RETURN) {
  1582. newReturnInstruction = Utility.copyInstruction(ih.getInstruction());
  1583. }
  1584. i--;
  1585. }
  1586. returnValueVar = genTempVar(this.getReturnType());
  1587. returnValueVar.appendLoad(returnInstructions, getFactory());
  1588. returnInstructions.append(newReturnInstruction);
  1589. } else {
  1590. InstructionHandle lastReturnHandle = returns.get(returns.size() - 1);
  1591. Instruction newReturnInstruction = Utility.copyInstruction(lastReturnHandle.getInstruction());
  1592. returnInstructions.append(newReturnInstruction);
  1593. }
  1594. return returnValueVar;
  1595. }
  1596. /**
  1597. * @return true, iff this shadow returns a value
  1598. */
  1599. private boolean hasANonVoidReturnType() {
  1600. return !this.getReturnType().equals(UnresolvedType.VOID);
  1601. }
  1602. /**
  1603. * Get the list of instructions used to dispatch to the after advice
  1604. *
  1605. * @param munger
  1606. * @param firstInstructionInReturnSequence
  1607. * @return
  1608. */
  1609. private InstructionList getAfterReturningAdviceDispatchInstructions(BcelAdvice munger,
  1610. InstructionHandle firstInstructionInReturnSequence) {
  1611. InstructionList advice = new InstructionList();
  1612. BcelVar tempVar = null;
  1613. if (munger.hasExtraParameter()) {
  1614. tempVar = insertAdviceInstructionsForBindingReturningParameter(advice);
  1615. }
  1616. advice.append(munger.getAdviceInstructions(this, tempVar, firstInstructionInReturnSequence));
  1617. return advice;
  1618. }
  1619. /**
  1620. * If the after() returning(Foo f) form is used, bind the return value to the parameter. If the shadow returns void, bind null.
  1621. *
  1622. * @param advice
  1623. * @return
  1624. */
  1625. private BcelVar insertAdviceInstructionsForBindingReturningParameter(InstructionList advice) {
  1626. BcelVar tempVar;
  1627. UnresolvedType tempVarType = getReturnType();
  1628. if (tempVarType.equals(UnresolvedType.VOID)) {
  1629. tempVar = genTempVar(UnresolvedType.OBJECT);
  1630. advice.append(InstructionConstants.ACONST_NULL);
  1631. tempVar.appendStore(advice, getFactory());
  1632. } else {
  1633. tempVar = genTempVar(tempVarType);
  1634. advice.append(InstructionFactory.createDup(tempVarType.getSize()));
  1635. tempVar.appendStore(advice, getFactory());
  1636. }
  1637. return tempVar;
  1638. }
  1639. /**
  1640. * Helper method for weaveAfterReturning
  1641. *
  1642. * Each return instruction in the method body is retargeted by calling this method. The return instruction is replaced by up to
  1643. * three instructions: 1) if the shadow returns a value, and that value is bound to an after returning parameter, then we DUP
  1644. * the return value on the top of the stack 2) if the shadow returns a value, we store it in the returnValueVar (it will be
  1645. * retrieved from here when we ultimately return after the advice dispatch) 3) if the return was the last instruction, we add a
  1646. * NOP (it will fall through to the advice dispatch), otherwise we add a GOTO that branches to the supplied gotoTarget (start of
  1647. * the advice dispatch)
  1648. */
  1649. private void retargetReturnInstruction(boolean hasReturningParameter, BcelVar returnValueVar, InstructionHandle gotoTarget,
  1650. InstructionHandle returnHandle) {
  1651. // pr148007, work around JRockit bug
  1652. // replace ret with store into returnValueVar, followed by goto if not
  1653. // at the end of the instruction list...
  1654. InstructionList newInstructions = new InstructionList();
  1655. if (returnValueVar != null) {
  1656. if (hasReturningParameter) {
  1657. // we have to dup the return val before consuming it...
  1658. newInstructions.append(InstructionFactory.createDup(this.getReturnType().getSize()));
  1659. }
  1660. // store the return value into this var
  1661. returnValueVar.appendStore(newInstructions, getFactory());
  1662. }
  1663. if (!isLastInstructionInRange(returnHandle, range)) {
  1664. newInstructions.append(InstructionFactory.createBranchInstruction(Constants.GOTO, gotoTarget));
  1665. }
  1666. if (newInstructions.isEmpty()) {
  1667. newInstructions.append(InstructionConstants.NOP);
  1668. }
  1669. Utility.replaceInstruction(returnHandle, newInstructions, enclosingMethod);
  1670. }
  1671. private boolean isLastInstructionInRange(InstructionHandle ih, ShadowRange aRange) {
  1672. return ih.getNext() == aRange.getEnd();
  1673. }
  1674. public void weaveAfterThrowing(BcelAdvice munger, UnresolvedType catchType) {
  1675. // a good optimization would be not to generate anything here
  1676. // if the shadow is GUARANTEED empty (i.e., there's NOTHING, not even
  1677. // a shadow, inside me).
  1678. if (getRange().getStart().getNext() == getRange().getEnd()) {
  1679. return;
  1680. }
  1681. InstructionFactory fact = getFactory();
  1682. InstructionList handler = new InstructionList();
  1683. BcelVar exceptionVar = genTempVar(catchType);
  1684. exceptionVar.appendStore(handler, fact);
  1685. // pr62642
  1686. // I will now jump through some firey BCEL hoops to generate a trivial bit of code:
  1687. // if (exc instanceof ExceptionInInitializerError)
  1688. // throw (ExceptionInInitializerError)exc;
  1689. if (this.getEnclosingMethod().getName().equals("<clinit>")) {
  1690. ResolvedType eiieType = world.resolve("java.lang.ExceptionInInitializerError");
  1691. ObjectType eiieBcelType = (ObjectType) BcelWorld.makeBcelType(eiieType);
  1692. InstructionList ih = new InstructionList(InstructionConstants.NOP);
  1693. handler.append(exceptionVar.createLoad(fact));
  1694. handler.append(fact.createInstanceOf(eiieBcelType));
  1695. InstructionBranch bi = InstructionFactory.createBranchInstruction(Constants.IFEQ, ih.getStart());
  1696. handler.append(bi);
  1697. handler.append(exceptionVar.createLoad(fact));
  1698. handler.append(fact.createCheckCast(eiieBcelType));
  1699. handler.append(InstructionConstants.ATHROW);
  1700. handler.append(ih);
  1701. }
  1702. InstructionList endHandler = new InstructionList(exceptionVar.createLoad(fact));
  1703. handler.append(munger.getAdviceInstructions(this, exceptionVar, endHandler.getStart()));
  1704. handler.append(endHandler);
  1705. handler.append(InstructionConstants.ATHROW);
  1706. InstructionHandle handlerStart = handler.getStart();
  1707. if (isFallsThrough()) {
  1708. InstructionHandle jumpTarget = handler.append(InstructionConstants.NOP);
  1709. handler.insert(InstructionFactory.createBranchInstruction(Constants.GOTO, jumpTarget));
  1710. }
  1711. InstructionHandle protectedEnd = handler.getStart();
  1712. range.insert(handler, Range.InsideAfter);
  1713. enclosingMethod.addExceptionHandler(range.getStart().getNext(), protectedEnd.getPrev(), handlerStart,
  1714. (ObjectType) BcelWorld.makeBcelType(catchType), // ???Type.THROWABLE,
  1715. // high priority if our args are on the stack
  1716. getKind().hasHighPriorityExceptions());
  1717. }
  1718. // ??? this shares a lot of code with the above weaveAfterThrowing
  1719. // ??? would be nice to abstract that to say things only once
  1720. public void weaveSoftener(BcelAdvice munger, UnresolvedType catchType) {
  1721. // a good optimization would be not to generate anything here
  1722. // if the shadow is GUARANTEED empty (i.e., there's NOTHING, not even
  1723. // a shadow, inside me).
  1724. if (getRange().getStart().getNext() == getRange().getEnd()) {
  1725. return;
  1726. }
  1727. InstructionFactory fact = getFactory();
  1728. InstructionList handler = new InstructionList();
  1729. InstructionList rtExHandler = new InstructionList();
  1730. BcelVar exceptionVar = genTempVar(catchType);
  1731. handler.append(fact.createNew(NameMangler.SOFT_EXCEPTION_TYPE));
  1732. handler.append(InstructionFactory.createDup(1));
  1733. handler.append(exceptionVar.createLoad(fact));
  1734. handler.append(fact.createInvoke(NameMangler.SOFT_EXCEPTION_TYPE, "<init>", Type.VOID, new Type[] { Type.THROWABLE },
  1735. Constants.INVOKESPECIAL)); // ??? special
  1736. handler.append(InstructionConstants.ATHROW);
  1737. // ENH 42737
  1738. exceptionVar.appendStore(rtExHandler, fact);
  1739. // aload_1
  1740. rtExHandler.append(exceptionVar.createLoad(fact));
  1741. // instanceof class java/lang/RuntimeException
  1742. rtExHandler.append(fact.createInstanceOf(new ObjectType("java.lang.RuntimeException")));
  1743. // ifeq go to new SOFT_EXCEPTION_TYPE instruction
  1744. rtExHandler.append(InstructionFactory.createBranchInstruction(Constants.IFEQ, handler.getStart()));
  1745. // aload_1
  1746. rtExHandler.append(exceptionVar.createLoad(fact));
  1747. // athrow
  1748. rtExHandler.append(InstructionFactory.ATHROW);
  1749. InstructionHandle handlerStart = rtExHandler.getStart();
  1750. if (isFallsThrough()) {
  1751. InstructionHandle jumpTarget = range.getEnd();// handler.append(fact.NOP);
  1752. rtExHandler.insert(InstructionFactory.createBranchInstruction(Constants.GOTO, jumpTarget));
  1753. }
  1754. rtExHandler.append(handler);
  1755. InstructionHandle protectedEnd = rtExHandler.getStart();
  1756. range.insert(rtExHandler, Range.InsideAfter);
  1757. enclosingMethod.addExceptionHandler(range.getStart().getNext(), protectedEnd.getPrev(), handlerStart,
  1758. (ObjectType) BcelWorld.makeBcelType(catchType),
  1759. // high priority if our args are on the stack
  1760. getKind().hasHighPriorityExceptions());
  1761. }
  1762. public void weavePerObjectEntry(final BcelAdvice munger, final BcelVar onVar) {
  1763. final InstructionFactory fact = getFactory();
  1764. InstructionList entryInstructions = new InstructionList();
  1765. InstructionList entrySuccessInstructions = new InstructionList();
  1766. onVar.appendLoad(entrySuccessInstructions, fact);
  1767. entrySuccessInstructions
  1768. .append(Utility.createInvoke(fact, world, AjcMemberMaker.perObjectBind(munger.getConcreteAspect())));
  1769. InstructionList testInstructions = munger.getTestInstructions(this, entrySuccessInstructions.getStart(),
  1770. range.getRealStart(), entrySuccessInstructions.getStart());
  1771. entryInstructions.append(testInstructions);
  1772. entryInstructions.append(entrySuccessInstructions);
  1773. range.insert(entryInstructions, Range.InsideBefore);
  1774. }
  1775. // PTWIMPL Create static initializer to call the aspect factory
  1776. /**
  1777. * Causes the aspect instance to be *set* for later retrievable through localAspectof()/aspectOf()
  1778. */
  1779. public void weavePerTypeWithinAspectInitialization(final BcelAdvice munger, UnresolvedType t) {
  1780. ResolvedType tResolved = t.resolve(world);
  1781. if (tResolved.isInterface()) {
  1782. return; // Don't initialize statics in interfaces
  1783. }
  1784. ResolvedType aspectRT = munger.getConcreteAspect();
  1785. BcelWorld.getBcelObjectType(aspectRT);
  1786. // Although matched, if the visibility rules prevent the aspect from seeing this type, don't
  1787. // insert any code (easier to do it here than try to affect the matching logic, unfortunately)
  1788. if (!(tResolved.canBeSeenBy(aspectRT) || aspectRT.isPrivilegedAspect())) {
  1789. return;
  1790. }
  1791. final InstructionFactory fact = getFactory();
  1792. InstructionList entryInstructions = new InstructionList();
  1793. InstructionList entrySuccessInstructions = new InstructionList();
  1794. String aspectname = munger.getConcreteAspect().getName();
  1795. String ptwField = NameMangler.perTypeWithinFieldForTarget(munger.getConcreteAspect());
  1796. entrySuccessInstructions.append(InstructionFactory.PUSH(fact.getConstantPool(), t.getName()));
  1797. entrySuccessInstructions.append(fact.createInvoke(aspectname, "ajc$createAspectInstance", new ObjectType(aspectname),
  1798. new Type[] { new ObjectType("java.lang.String") }, Constants.INVOKESTATIC));
  1799. entrySuccessInstructions.append(fact.createPutStatic(t.getName(), ptwField, new ObjectType(aspectname)));
  1800. entryInstructions.append(entrySuccessInstructions);
  1801. range.insert(entryInstructions, Range.InsideBefore);
  1802. }
  1803. public void weaveCflowEntry(final BcelAdvice munger, final Member cflowField) {
  1804. final boolean isPer = munger.getKind() == AdviceKind.PerCflowBelowEntry || munger.getKind() == AdviceKind.PerCflowEntry;
  1805. if (!isPer && getKind() == PreInitialization) {
  1806. return;
  1807. }
  1808. final Type objectArrayType = new ArrayType(Type.OBJECT, 1);
  1809. final InstructionFactory fact = getFactory();
  1810. final BcelVar testResult = genTempVar(UnresolvedType.BOOLEAN);
  1811. InstructionList entryInstructions = new InstructionList();
  1812. {
  1813. InstructionList entrySuccessInstructions = new InstructionList();
  1814. if (munger.hasDynamicTests()) {
  1815. entryInstructions.append(Utility.createConstant(fact, 0));
  1816. testResult.appendStore(entryInstructions, fact);
  1817. entrySuccessInstructions.append(Utility.createConstant(fact, 1));
  1818. testResult.appendStore(entrySuccessInstructions, fact);
  1819. }
  1820. if (isPer) {
  1821. entrySuccessInstructions.append(fact.createInvoke(munger.getConcreteAspect().getName(),
  1822. NameMangler.PERCFLOW_PUSH_METHOD, Type.VOID, Type.NO_ARGS, Constants.INVOKESTATIC));
  1823. } else {
  1824. BcelVar[] cflowStateVars = munger.getExposedStateAsBcelVars(false);
  1825. if (cflowStateVars.length == 0) {
  1826. // This should be getting managed by a counter - lets make sure.
  1827. if (!cflowField.getType().getName().endsWith("CFlowCounter")) {
  1828. throw new RuntimeException("Incorrectly attempting counter operation on stacked cflow");
  1829. }
  1830. entrySuccessInstructions.append(Utility.createGet(fact, cflowField));
  1831. // arrayVar.appendLoad(entrySuccessInstructions, fact);
  1832. entrySuccessInstructions.append(fact.createInvoke(NameMangler.CFLOW_COUNTER_TYPE, "inc", Type.VOID,
  1833. Type.NO_ARGS, Constants.INVOKEVIRTUAL));
  1834. } else {
  1835. BcelVar arrayVar = genTempVar(UnresolvedType.OBJECTARRAY);
  1836. int alen = cflowStateVars.length;
  1837. entrySuccessInstructions.append(Utility.createConstant(fact, alen));
  1838. entrySuccessInstructions.append(fact.createNewArray(Type.OBJECT, (short) 1));
  1839. arrayVar.appendStore(entrySuccessInstructions, fact);
  1840. for (int i = 0; i < alen; i++) {
  1841. arrayVar.appendConvertableArrayStore(entrySuccessInstructions, fact, i, cflowStateVars[i]);
  1842. }
  1843. entrySuccessInstructions.append(Utility.createGet(fact, cflowField));
  1844. arrayVar.appendLoad(entrySuccessInstructions, fact);
  1845. entrySuccessInstructions.append(fact.createInvoke(NameMangler.CFLOW_STACK_TYPE, "push", Type.VOID,
  1846. new Type[] { objectArrayType }, Constants.INVOKEVIRTUAL));
  1847. }
  1848. }
  1849. InstructionList testInstructions = munger.getTestInstructions(this, entrySuccessInstructions.getStart(),
  1850. range.getRealStart(), entrySuccessInstructions.getStart());
  1851. entryInstructions.append(testInstructions);
  1852. entryInstructions.append(entrySuccessInstructions);
  1853. }
  1854. BcelAdvice exitAdvice = new BcelAdvice(null, null, null, 0, 0, 0, null, munger.getConcreteAspect()) {
  1855. @Override
  1856. public InstructionList getAdviceInstructions(BcelShadow s, BcelVar extraArgVar, InstructionHandle ifNoAdvice) {
  1857. InstructionList exitInstructions = new InstructionList();
  1858. if (munger.hasDynamicTests()) {
  1859. testResult.appendLoad(exitInstructions, fact);
  1860. exitInstructions.append(InstructionFactory.createBranchInstruction(Constants.IFEQ, ifNoAdvice));
  1861. }
  1862. exitInstructions.append(Utility.createGet(fact, cflowField));
  1863. if (munger.getKind() != AdviceKind.PerCflowEntry && munger.getKind() != AdviceKind.PerCflowBelowEntry
  1864. && munger.getExposedStateAsBcelVars(false).length == 0) {
  1865. exitInstructions.append(fact.createInvoke(NameMangler.CFLOW_COUNTER_TYPE, "dec", Type.VOID, Type.NO_ARGS,
  1866. Constants.INVOKEVIRTUAL));
  1867. } else {
  1868. exitInstructions.append(fact.createInvoke(NameMangler.CFLOW_STACK_TYPE, "pop", Type.VOID, Type.NO_ARGS,
  1869. Constants.INVOKEVIRTUAL));
  1870. }
  1871. return exitInstructions;
  1872. }
  1873. };
  1874. // if (getKind() == PreInitialization) {
  1875. // weaveAfterReturning(exitAdvice);
  1876. // }
  1877. // else {
  1878. weaveAfter(exitAdvice);
  1879. // }
  1880. range.insert(entryInstructions, Range.InsideBefore);
  1881. }
  1882. /*
  1883. * Implementation notes:
  1884. *
  1885. * AroundInline still extracts the instructions of the original shadow into an extracted method. This allows inlining of even
  1886. * that advice that doesn't call proceed or calls proceed more than once.
  1887. *
  1888. * It extracts the instructions of the original shadow into a method.
  1889. *
  1890. * Then it extracts the instructions of the advice into a new method defined on this enclosing class. This new method can then
  1891. * be specialized as below.
  1892. *
  1893. * Then it searches in the instructions of the advice for any call to the proceed method.
  1894. *
  1895. * At such a call, there is stuff on the stack representing the arguments to proceed. Pop these into the frame.
  1896. *
  1897. * Now build the stack for the call to the extracted method, taking values either from the join point state or from the new
  1898. * frame locs from proceed. Now call the extracted method. The right return value should be on the stack, so no cast is
  1899. * necessary.
  1900. *
  1901. * If only one call to proceed is made, we can re-inline the original shadow. We are not doing that presently.
  1902. *
  1903. * If the body of the advice can be determined to not alter the stack, or if this shadow doesn't care about the stack, i.e.
  1904. * method-execution, then the new method for the advice can also be re-lined. We are not doing that presently.
  1905. */
  1906. public void weaveAroundInline(BcelAdvice munger, boolean hasDynamicTest) {
  1907. // !!! THIS BLOCK OF CODE SHOULD BE IN A METHOD CALLED weaveAround(...);
  1908. Member mungerSig = munger.getSignature();
  1909. // Member originalSig = mungerSig; // If mungerSig is on a parameterized type, originalSig is the member on the generic type
  1910. if (mungerSig instanceof ResolvedMember) {
  1911. ResolvedMember rm = (ResolvedMember) mungerSig;
  1912. if (rm.hasBackingGenericMember()) {
  1913. mungerSig = rm.getBackingGenericMember();
  1914. }
  1915. }
  1916. ResolvedType declaringAspectType = world.resolve(mungerSig.getDeclaringType(), true);
  1917. if (declaringAspectType.isMissing()) {
  1918. world.getLint().cantFindType.signal(
  1919. new String[] { WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE,
  1920. declaringAspectType.getClassName()) }, getSourceLocation(),
  1921. new ISourceLocation[] { munger.getSourceLocation() });
  1922. }
  1923. // ??? might want some checks here to give better errors
  1924. ResolvedType rt = (declaringAspectType.isParameterizedType() ? declaringAspectType.getGenericType() : declaringAspectType);
  1925. BcelObjectType ot = BcelWorld.getBcelObjectType(rt);
  1926. LazyMethodGen adviceMethod = ot.getLazyClassGen().getLazyMethodGen(mungerSig);
  1927. if (!adviceMethod.getCanInline()) {
  1928. weaveAroundClosure(munger, hasDynamicTest);
  1929. return;
  1930. }
  1931. // specific test for @AJ proceedInInners
  1932. if (isAnnotationStylePassingProceedingJoinPointOutOfAdvice(munger, hasDynamicTest, adviceMethod)) {
  1933. return;
  1934. }
  1935. // We can't inline around methods if they have around advice on them, this
  1936. // is because the weaving will extract the body and hence the proceed call.
  1937. // TODO should consider optimizations to recognize simple cases that don't require body extraction
  1938. enclosingMethod.setCanInline(false);
  1939. LazyClassGen shadowClass = getEnclosingClass();
  1940. // Extract the shadow into a new method. For example:
  1941. // "private static final void method_aroundBody0(M, M, String, org.aspectj.lang.JoinPoint)"
  1942. // Parameters are: this if there is one, target if there is one and its different to this, then original arguments
  1943. // at the shadow, then tjp
  1944. String extractedShadowMethodName = NameMangler.aroundShadowMethodName(getSignature(), shadowClass.getNewGeneratedNameTag());
  1945. List<String> parameterNames = new ArrayList<>();
  1946. boolean shadowClassIsInterface = shadowClass.isInterface();
  1947. LazyMethodGen extractedShadowMethod = extractShadowInstructionsIntoNewMethod(extractedShadowMethodName,
  1948. shadowClassIsInterface?Modifier.PUBLIC:Modifier.PRIVATE,
  1949. munger.getSourceLocation(), parameterNames,shadowClassIsInterface);
  1950. List<BcelVar> argsToCallLocalAdviceMethodWith = new ArrayList<>();
  1951. List<BcelVar> proceedVarList = new ArrayList<>();
  1952. int extraParamOffset = 0;
  1953. // Create the extra parameters that are needed for passing to proceed
  1954. // This code is very similar to that found in makeCallToCallback and should
  1955. // be rationalized in the future
  1956. if (thisVar != null) {
  1957. argsToCallLocalAdviceMethodWith.add(thisVar);
  1958. proceedVarList.add(new BcelVar(thisVar.getType(), extraParamOffset));
  1959. extraParamOffset += thisVar.getType().getSize();
  1960. }
  1961. if (targetVar != null && targetVar != thisVar) {
  1962. argsToCallLocalAdviceMethodWith.add(targetVar);
  1963. proceedVarList.add(new BcelVar(targetVar.getType(), extraParamOffset));
  1964. extraParamOffset += targetVar.getType().getSize();
  1965. }
  1966. for (int i = 0, len = getArgCount(); i < len; i++) {
  1967. argsToCallLocalAdviceMethodWith.add(argVars[i]);
  1968. proceedVarList.add(new BcelVar(argVars[i].getType(), extraParamOffset));
  1969. extraParamOffset += argVars[i].getType().getSize();
  1970. }
  1971. if (thisJoinPointVar != null) {
  1972. argsToCallLocalAdviceMethodWith.add(thisJoinPointVar);
  1973. proceedVarList.add(new BcelVar(thisJoinPointVar.getType(), extraParamOffset));
  1974. extraParamOffset += thisJoinPointVar.getType().getSize();
  1975. }
  1976. // We use the munger signature here because it allows for any parameterization of the mungers pointcut that
  1977. // may have occurred ie. if the pointcut is p(T t) in the super aspect and that has become p(Foo t) in the sub aspect
  1978. // then here the munger signature will have 'Foo' as an argument in it whilst the adviceMethod argument type will be
  1979. // 'Object' - since it represents the advice method in the superaspect which uses the erasure of the type variable p(Object
  1980. // t) - see pr174449.
  1981. Type[] adviceParameterTypes = BcelWorld.makeBcelTypes(munger.getSignature().getParameterTypes());
  1982. // forces initialization ... dont like this but seems to be required for some tests to pass, I think that means there
  1983. // is a LazyMethodGen method that is not correctly setup to call initialize() when it is invoked - but I dont have
  1984. // time right now to discover which
  1985. adviceMethod.getArgumentTypes();
  1986. Type[] extractedMethodParameterTypes = extractedShadowMethod.getArgumentTypes();
  1987. Type[] parameterTypes = new Type[extractedMethodParameterTypes.length + adviceParameterTypes.length + 1];
  1988. int parameterIndex = 0;
  1989. System.arraycopy(extractedMethodParameterTypes, 0, parameterTypes, parameterIndex, extractedMethodParameterTypes.length);
  1990. parameterIndex += extractedMethodParameterTypes.length;
  1991. parameterTypes[parameterIndex++] = BcelWorld.makeBcelType(adviceMethod.getEnclosingClass().getType());
  1992. System.arraycopy(adviceParameterTypes, 0, parameterTypes, parameterIndex, adviceParameterTypes.length);
  1993. // Extract the advice into a new method. This will go in the same type as the shadow
  1994. // name will be something like foo_aroundBody1$advice
  1995. String localAdviceMethodName = NameMangler.aroundAdviceMethodName(getSignature(), shadowClass.getNewGeneratedNameTag());
  1996. int localAdviceMethodModifiers = Modifier.PRIVATE | (world.useFinal() & !shadowClassIsInterface ? Modifier.FINAL : 0) | Modifier.STATIC;
  1997. LazyMethodGen localAdviceMethod = new LazyMethodGen(localAdviceMethodModifiers, BcelWorld.makeBcelType(mungerSig.getReturnType()), localAdviceMethodName, parameterTypes,
  1998. NoDeclaredExceptions, shadowClass);
  1999. // Doesnt work properly, so leave it out:
  2000. // String aspectFilename = adviceMethod.getEnclosingClass().getInternalFileName();
  2001. // String shadowFilename = shadowClass.getInternalFileName();
  2002. // if (!aspectFilename.equals(shadowFilename)) {
  2003. // localAdviceMethod.fromFilename = aspectFilename;
  2004. // shadowClass.addInlinedSourceFileInfo(aspectFilename, adviceMethod.highestLineNumber);
  2005. // }
  2006. shadowClass.addMethodGen(localAdviceMethod);
  2007. // create a map that will move all slots in advice method forward by extraParamOffset
  2008. // in order to make room for the new proceed-required arguments that are added at
  2009. // the beginning of the parameter list
  2010. int nVars = adviceMethod.getMaxLocals() + extraParamOffset;
  2011. IntMap varMap = IntMap.idMap(nVars);
  2012. for (int i = extraParamOffset; i < nVars; i++) {
  2013. varMap.put(i - extraParamOffset, i);
  2014. }
  2015. final InstructionFactory fact = getFactory();
  2016. localAdviceMethod.getBody().insert(
  2017. BcelClassWeaver.genInlineInstructions(adviceMethod, localAdviceMethod, varMap, fact, true));
  2018. localAdviceMethod.setMaxLocals(nVars);
  2019. // the shadow is now empty. First, create a correct call
  2020. // to the around advice. This includes both the call (which may involve
  2021. // value conversion of the advice arguments) and the return
  2022. // (which may involve value conversion of the return value). Right now
  2023. // we push a null for the unused closure. It's sad, but there it is.
  2024. InstructionList advice = new InstructionList();
  2025. // InstructionHandle adviceMethodInvocation;
  2026. {
  2027. for (BcelVar var : argsToCallLocalAdviceMethodWith) {
  2028. var.appendLoad(advice, fact);
  2029. }
  2030. // ??? we don't actually need to push NULL for the closure if we take care
  2031. boolean isAnnoStyleConcreteAspect = munger.getConcreteAspect().isAnnotationStyleAspect();
  2032. boolean isAnnoStyleDeclaringAspect = munger.getDeclaringAspect() != null ? munger.getDeclaringAspect().resolve(world)
  2033. .isAnnotationStyleAspect() : false;
  2034. InstructionList iList = null;
  2035. if (isAnnoStyleConcreteAspect && isAnnoStyleDeclaringAspect) {
  2036. iList = this.loadThisJoinPoint();
  2037. iList.append(Utility.createConversion(getFactory(), LazyClassGen.tjpType, LazyClassGen.proceedingTjpType));
  2038. } else {
  2039. iList = new InstructionList(InstructionConstants.ACONST_NULL);
  2040. }
  2041. advice.append(munger.getAdviceArgSetup(this, null, iList));
  2042. // adviceMethodInvocation =
  2043. advice.append(Utility.createInvoke(fact, localAdviceMethod)); // (fact, getWorld(), munger.getSignature()));
  2044. advice.append(Utility.createConversion(getFactory(), BcelWorld.makeBcelType(mungerSig.getReturnType()),
  2045. extractedShadowMethod.getReturnType(), world.isInJava5Mode()));
  2046. if (!isFallsThrough()) {
  2047. advice.append(InstructionFactory.createReturn(extractedShadowMethod.getReturnType()));
  2048. }
  2049. }
  2050. // now, situate the call inside the possible dynamic tests,
  2051. // and actually add the whole mess to the shadow
  2052. if (!hasDynamicTest) {
  2053. range.append(advice);
  2054. } else {
  2055. InstructionList afterThingie = new InstructionList(InstructionConstants.NOP);
  2056. InstructionList callback = makeCallToCallback(extractedShadowMethod);
  2057. if (terminatesWithReturn()) {
  2058. callback.append(InstructionFactory.createReturn(extractedShadowMethod.getReturnType()));
  2059. } else {
  2060. // InstructionHandle endNop = range.insert(fact.NOP, Range.InsideAfter);
  2061. advice.append(InstructionFactory.createBranchInstruction(Constants.GOTO, afterThingie.getStart()));
  2062. }
  2063. range.append(munger.getTestInstructions(this, advice.getStart(), callback.getStart(), advice.getStart()));
  2064. range.append(advice);
  2065. range.append(callback);
  2066. range.append(afterThingie);
  2067. }
  2068. // now search through the advice, looking for a call to PROCEED.
  2069. // Then we replace the call to proceed with some argument setup, and a
  2070. // call to the extracted method.
  2071. // inlining support for code style aspects
  2072. if (!munger.getDeclaringType().isAnnotationStyleAspect()) {
  2073. String proceedName = NameMangler.proceedMethodName(munger.getSignature().getName());
  2074. InstructionHandle curr = localAdviceMethod.getBody().getStart();
  2075. InstructionHandle end = localAdviceMethod.getBody().getEnd();
  2076. ConstantPool cpg = localAdviceMethod.getEnclosingClass().getConstantPool();
  2077. while (curr != end) {
  2078. InstructionHandle next = curr.getNext();
  2079. Instruction inst = curr.getInstruction();
  2080. if ((inst.opcode == Constants.INVOKESTATIC) && proceedName.equals(((InvokeInstruction) inst).getMethodName(cpg))) {
  2081. localAdviceMethod.getBody().append(curr,
  2082. getRedoneProceedCall(fact, extractedShadowMethod, munger, localAdviceMethod, proceedVarList));
  2083. Utility.deleteInstruction(curr, localAdviceMethod);
  2084. }
  2085. curr = next;
  2086. }
  2087. // and that's it.
  2088. } else {
  2089. // ATAJ inlining support for @AJ aspects
  2090. // [TODO document @AJ code rule: don't manipulate 2 jps proceed at the same time.. in an advice body]
  2091. InstructionHandle curr = localAdviceMethod.getBody().getStart();
  2092. InstructionHandle end = localAdviceMethod.getBody().getEnd();
  2093. ConstantPool cpg = localAdviceMethod.getEnclosingClass().getConstantPool();
  2094. while (curr != end) {
  2095. InstructionHandle next = curr.getNext();
  2096. Instruction inst = curr.getInstruction();
  2097. if ((inst instanceof INVOKEINTERFACE) && "proceed".equals(((INVOKEINTERFACE) inst).getMethodName(cpg))) {
  2098. final boolean isProceedWithArgs;
  2099. if (((INVOKEINTERFACE) inst).getArgumentTypes(cpg).length == 1) {
  2100. // proceed with args as a boxed Object[]
  2101. isProceedWithArgs = true;
  2102. } else {
  2103. isProceedWithArgs = false;
  2104. }
  2105. InstructionList insteadProceedIl = getRedoneProceedCallForAnnotationStyle(fact, extractedShadowMethod, munger,
  2106. localAdviceMethod, proceedVarList, isProceedWithArgs);
  2107. localAdviceMethod.getBody().append(curr, insteadProceedIl);
  2108. Utility.deleteInstruction(curr, localAdviceMethod);
  2109. }
  2110. curr = next;
  2111. }
  2112. }
  2113. // if (parameterNames.size() == 0) {
  2114. // On return we have inserted the advice body into the local advice method. We have remapped all the local variables
  2115. // that were referenced in the advice as we did the copy, and so the local variable table for localAdviceMethod is
  2116. // now lacking any information about all the initial variables.
  2117. InstructionHandle start = localAdviceMethod.getBody().getStart();
  2118. InstructionHandle end = localAdviceMethod.getBody().getEnd();
  2119. // Find the real start and end
  2120. while (start.getInstruction().opcode == Constants.IMPDEP1) {
  2121. start = start.getNext();
  2122. }
  2123. while (end.getInstruction().opcode == Constants.IMPDEP1) {
  2124. end = end.getPrev();
  2125. }
  2126. Type[] args = localAdviceMethod.getArgumentTypes();
  2127. int argNumber = 0;
  2128. for (int slot = 0; slot < extraParamOffset; argNumber++) { // slot will increase by the argument size each time
  2129. String argumentName = null;
  2130. if (argNumber >= args.length || parameterNames.size() == 0 || argNumber >= parameterNames.size()) {
  2131. // this should be unnecessary as I think all known joinpoints and helper methods
  2132. // propagate the parameter names around correctly - but just in case let us do this
  2133. // rather than fail. If a bug is raised reporting unknown as a local variable name
  2134. // then investigate the joinpoint giving rise to the ResolvedMember and why it has
  2135. // no parameter names specified
  2136. argumentName = new StringBuilder("unknown").append(argNumber).toString();
  2137. } else {
  2138. argumentName = parameterNames.get(argNumber);
  2139. }
  2140. String argumentSignature = args[argNumber].getSignature();
  2141. LocalVariableTag lvt = new LocalVariableTag(argumentSignature, argumentName, slot, 0);
  2142. start.addTargeter(lvt);
  2143. end.addTargeter(lvt);
  2144. slot += args[argNumber].getSize();
  2145. }
  2146. }
  2147. /**
  2148. * Check if the advice method passes a pjp parameter out via an invoke instruction - if so we can't risk inlining.
  2149. */
  2150. private boolean isAnnotationStylePassingProceedingJoinPointOutOfAdvice(BcelAdvice munger, boolean hasDynamicTest,
  2151. LazyMethodGen adviceMethod) {
  2152. if (munger.getConcreteAspect().isAnnotationStyleAspect()) {
  2153. // if we can't find one proceed() we suspect that the call
  2154. // is happening in an inner class so we don't inline it.
  2155. // Note: for code style, this is done at Aspect compilation time.
  2156. boolean canSeeProceedPassedToOther = false;
  2157. InstructionHandle curr = adviceMethod.getBody().getStart();
  2158. InstructionHandle end = adviceMethod.getBody().getEnd();
  2159. ConstantPool cpg = adviceMethod.getEnclosingClass().getConstantPool();
  2160. while (curr != end) {
  2161. InstructionHandle next = curr.getNext();
  2162. Instruction inst = curr.getInstruction();
  2163. if ((inst instanceof InvokeInstruction)
  2164. && ((InvokeInstruction) inst).getSignature(cpg).indexOf("Lorg/aspectj/lang/ProceedingJoinPoint;") > 0) {
  2165. // we may want to refine to exclude stuff returning jp ?
  2166. // does code style skip inline if i write dump(thisJoinPoint) ?
  2167. canSeeProceedPassedToOther = true;// we see one pjp passed around - dangerous
  2168. break;
  2169. }
  2170. curr = next;
  2171. }
  2172. if (canSeeProceedPassedToOther) {
  2173. // remember this decision to avoid re-analysis
  2174. adviceMethod.setCanInline(false);
  2175. weaveAroundClosure(munger, hasDynamicTest);
  2176. return true;
  2177. }
  2178. }
  2179. return false;
  2180. }
  2181. private InstructionList getRedoneProceedCall(InstructionFactory fact, LazyMethodGen callbackMethod, BcelAdvice munger,
  2182. LazyMethodGen localAdviceMethod, List<BcelVar> argVarList) {
  2183. InstructionList ret = new InstructionList();
  2184. // we have on stack all the arguments for the ADVICE call.
  2185. // we have in frame somewhere all the arguments for the non-advice call.
  2186. BcelVar[] adviceVars = munger.getExposedStateAsBcelVars(true);
  2187. IntMap proceedMap = makeProceedArgumentMap(adviceVars);
  2188. // System.out.println(proceedMap + " for " + this);
  2189. // System.out.println(argVarList);
  2190. ResolvedType[] proceedParamTypes = world.resolve(munger.getSignature().getParameterTypes());
  2191. // remove this*JoinPoint* as arguments to proceed
  2192. if (munger.getBaseParameterCount() + 1 < proceedParamTypes.length) {
  2193. int len = munger.getBaseParameterCount() + 1;
  2194. ResolvedType[] newTypes = new ResolvedType[len];
  2195. System.arraycopy(proceedParamTypes, 0, newTypes, 0, len);
  2196. proceedParamTypes = newTypes;
  2197. }
  2198. // System.out.println("stateTypes: " + Arrays.asList(stateTypes));
  2199. BcelVar[] proceedVars = Utility.pushAndReturnArrayOfVars(proceedParamTypes, ret, fact, localAdviceMethod);
  2200. Type[] stateTypes = callbackMethod.getArgumentTypes();
  2201. // System.out.println("stateTypes: " + Arrays.asList(stateTypes));
  2202. for (int i = 0, len = stateTypes.length; i < len; i++) {
  2203. Type stateType = stateTypes[i];
  2204. ResolvedType stateTypeX = BcelWorld.fromBcel(stateType).resolve(world);
  2205. if (proceedMap.hasKey(i)) {
  2206. // throw new RuntimeException("unimplemented");
  2207. proceedVars[proceedMap.get(i)].appendLoadAndConvert(ret, fact, stateTypeX);
  2208. } else {
  2209. argVarList.get(i).appendLoad(ret, fact);
  2210. }
  2211. }
  2212. ret.append(Utility.createInvoke(fact, callbackMethod));
  2213. ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(),
  2214. BcelWorld.makeBcelType(munger.getSignature().getReturnType()), world.isInJava5Mode()));
  2215. return ret;
  2216. }
  2217. // private static boolean bindsThisOrTarget(Pointcut pointcut) {
  2218. // ThisTargetFinder visitor = new ThisTargetFinder();
  2219. // pointcut.accept(visitor, null);
  2220. // return visitor.bindsThisOrTarget;
  2221. // }
  2222. // private static class ThisTargetFinder extends IdentityPointcutVisitor {
  2223. // boolean bindsThisOrTarget = false;
  2224. //
  2225. // public Object visit(ThisOrTargetPointcut node, Object data) {
  2226. // if (node.isBinding()) {
  2227. // bindsThisOrTarget = true;
  2228. // }
  2229. // return node;
  2230. // }
  2231. //
  2232. // public Object visit(AndPointcut node, Object data) {
  2233. // if (!bindsThisOrTarget) node.getLeft().accept(this, data);
  2234. // if (!bindsThisOrTarget) node.getRight().accept(this, data);
  2235. // return node;
  2236. // }
  2237. //
  2238. // public Object visit(NotPointcut node, Object data) {
  2239. // if (!bindsThisOrTarget) node.getNegatedPointcut().accept(this, data);
  2240. // return node;
  2241. // }
  2242. //
  2243. // public Object visit(OrPointcut node, Object data) {
  2244. // if (!bindsThisOrTarget) node.getLeft().accept(this, data);
  2245. // if (!bindsThisOrTarget) node.getRight().accept(this, data);
  2246. // return node;
  2247. // }
  2248. // }
  2249. /**
  2250. * Annotation style handling for inlining.
  2251. *
  2252. * Note: The proceedingjoinpoint is already on the stack (since the user was calling pjp.proceed(...)
  2253. *
  2254. * The proceed map is ignored (in terms of argument repositioning) since we have a fixed expected format for annotation style.
  2255. * The aim here is to change the proceed() call into a call to the xxx_aroundBody0 method.
  2256. *
  2257. *
  2258. */
  2259. private InstructionList getRedoneProceedCallForAnnotationStyle(InstructionFactory fact, LazyMethodGen callbackMethod,
  2260. BcelAdvice munger, LazyMethodGen localAdviceMethod, List<BcelVar> argVarList, boolean isProceedWithArgs) {
  2261. InstructionList ret = new InstructionList();
  2262. // store the Object[] array on stack if proceed with args
  2263. if (isProceedWithArgs) {
  2264. // STORE the Object[] into a local variable
  2265. Type objectArrayType = Type.OBJECT_ARRAY;
  2266. int theObjectArrayLocalNumber = localAdviceMethod.allocateLocal(objectArrayType);
  2267. ret.append(InstructionFactory.createStore(objectArrayType, theObjectArrayLocalNumber));
  2268. // STORE the ProceedingJoinPoint instance into a local variable
  2269. Type proceedingJpType = Type.getType("Lorg/aspectj/lang/ProceedingJoinPoint;");
  2270. int pjpLocalNumber = localAdviceMethod.allocateLocal(proceedingJpType);
  2271. ret.append(InstructionFactory.createStore(proceedingJpType, pjpLocalNumber));
  2272. // Aim here initially is to determine whether the user will have provided a new
  2273. // this/target in the object array and consume them if they have, leaving us the rest of
  2274. // the arguments to process as regular arguments to the invocation at the original join point
  2275. boolean pointcutBindsThis = bindsThis(munger);
  2276. boolean pointcutBindsTarget = bindsTarget(munger);
  2277. boolean targetIsSameAsThis = getKind().isTargetSameAsThis();
  2278. int nextArgumentToProvideForCallback = 0;
  2279. if (hasThis()) {
  2280. if (!(pointcutBindsTarget && targetIsSameAsThis)) {
  2281. if (pointcutBindsThis) {
  2282. // they have supplied new this as first entry in object array, consume it
  2283. ret.append(InstructionFactory.createLoad(objectArrayType, theObjectArrayLocalNumber));
  2284. ret.append(Utility.createConstant(fact, 0));
  2285. ret.append(InstructionFactory.createArrayLoad(Type.OBJECT));
  2286. ret.append(Utility.createConversion(fact, Type.OBJECT, callbackMethod.getArgumentTypes()[0]));
  2287. } else {
  2288. // use local variable 0
  2289. ret.append(InstructionFactory.createALOAD(0));
  2290. }
  2291. nextArgumentToProvideForCallback++;
  2292. }
  2293. }
  2294. if (hasTarget()) {
  2295. if (pointcutBindsTarget) {
  2296. if (getKind().isTargetSameAsThis()) {
  2297. ret.append(InstructionFactory.createLoad(objectArrayType, theObjectArrayLocalNumber));
  2298. ret.append(Utility.createConstant(fact, pointcutBindsThis ? 1 : 0));
  2299. ret.append(InstructionFactory.createArrayLoad(Type.OBJECT));
  2300. ret.append(Utility.createConversion(fact, Type.OBJECT, callbackMethod.getArgumentTypes()[0]));
  2301. } else {
  2302. int position = (hasThis() && pointcutBindsThis)? 1 : 0;
  2303. ret.append(InstructionFactory.createLoad(objectArrayType, theObjectArrayLocalNumber));
  2304. ret.append(Utility.createConstant(fact, position));
  2305. ret.append(InstructionFactory.createArrayLoad(Type.OBJECT));
  2306. ret.append(Utility.createConversion(fact, Type.OBJECT, callbackMethod.getArgumentTypes()[nextArgumentToProvideForCallback]));
  2307. }
  2308. nextArgumentToProvideForCallback++;
  2309. } else {
  2310. if (getKind().isTargetSameAsThis()) {
  2311. // ret.append(new ALOAD(0));
  2312. } else {
  2313. ret.append(InstructionFactory.createLoad(localAdviceMethod.getArgumentTypes()[0], hasThis() ? 1 : 0));
  2314. nextArgumentToProvideForCallback++;
  2315. }
  2316. }
  2317. }
  2318. // Where to start in the object array in order to pick up arguments
  2319. int indexIntoObjectArrayForArguments = (pointcutBindsThis ? 1 : 0) + (pointcutBindsTarget ? 1 : 0);
  2320. int len = callbackMethod.getArgumentTypes().length;
  2321. for (int i = nextArgumentToProvideForCallback; i < len; i++) {
  2322. Type stateType = callbackMethod.getArgumentTypes()[i];
  2323. BcelWorld.fromBcel(stateType).resolve(world);
  2324. if ("Lorg/aspectj/lang/JoinPoint;".equals(stateType.getSignature())) {
  2325. ret.append(new InstructionLV(Constants.ALOAD, pjpLocalNumber));
  2326. } else {
  2327. ret.append(InstructionFactory.createLoad(objectArrayType, theObjectArrayLocalNumber));
  2328. ret.append(Utility
  2329. .createConstant(fact, i - nextArgumentToProvideForCallback + indexIntoObjectArrayForArguments));
  2330. ret.append(InstructionFactory.createArrayLoad(Type.OBJECT));
  2331. ret.append(Utility.createConversion(fact, Type.OBJECT, stateType));
  2332. }
  2333. }
  2334. } else {
  2335. Type proceedingJpType = Type.getType("Lorg/aspectj/lang/ProceedingJoinPoint;");
  2336. int localJp = localAdviceMethod.allocateLocal(proceedingJpType);
  2337. ret.append(InstructionFactory.createStore(proceedingJpType, localJp));
  2338. int idx = 0;
  2339. for (int i = 0, len = callbackMethod.getArgumentTypes().length; i < len; i++) {
  2340. Type stateType = callbackMethod.getArgumentTypes()[i];
  2341. /* ResolvedType stateTypeX = */
  2342. BcelWorld.fromBcel(stateType).resolve(world);
  2343. if ("Lorg/aspectj/lang/JoinPoint;".equals(stateType.getSignature())) {
  2344. ret.append(InstructionFactory.createALOAD(localJp));// from localAdvice signature
  2345. // } else if ("Lorg/aspectj/lang/ProceedingJoinPoint;".equals(stateType.getSignature())) {
  2346. // //FIXME ALEX?
  2347. // ret.append(new ALOAD(localJp));// from localAdvice signature
  2348. // // ret.append(fact.createCheckCast(
  2349. // // (ReferenceType) BcelWorld.makeBcelType(stateTypeX)
  2350. // // ));
  2351. // // cast ?
  2352. //
  2353. idx++;
  2354. } else {
  2355. ret.append(InstructionFactory.createLoad(stateType, idx));
  2356. idx += stateType.getSize();
  2357. }
  2358. }
  2359. }
  2360. // do the callback invoke
  2361. ret.append(Utility.createInvoke(fact, callbackMethod));
  2362. // box it again. Handles cases where around advice does return something else than Object
  2363. if (!UnresolvedType.OBJECT.equals(munger.getSignature().getReturnType())) {
  2364. ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(), Type.OBJECT));
  2365. }
  2366. ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(),
  2367. BcelWorld.makeBcelType(munger.getSignature().getReturnType()), world.isInJava5Mode()));
  2368. return ret;
  2369. //
  2370. //
  2371. //
  2372. // if (proceedMap.hasKey(i)) {
  2373. // ret.append(new ALOAD(i));
  2374. // //throw new RuntimeException("unimplemented");
  2375. // //proceedVars[proceedMap.get(i)].appendLoadAndConvert(ret, fact, stateTypeX);
  2376. // } else {
  2377. // //((BcelVar) argVarList.get(i)).appendLoad(ret, fact);
  2378. // //ret.append(new ALOAD(i));
  2379. // if ("Lorg/aspectj/lang/JoinPoint;".equals(stateType.getSignature())) {
  2380. // ret.append(new ALOAD(i));
  2381. // } else {
  2382. // ret.append(new ALOAD(i));
  2383. // }
  2384. // }
  2385. // }
  2386. //
  2387. // ret.append(Utility.createInvoke(fact, callbackMethod));
  2388. // ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(),
  2389. // BcelWorld.makeBcelType(munger.getSignature().getReturnType())));
  2390. //
  2391. // //ret.append(new ACONST_NULL());//will be POPed
  2392. // if (true) return ret;
  2393. //
  2394. //
  2395. //
  2396. // // we have on stack all the arguments for the ADVICE call.
  2397. // // we have in frame somewhere all the arguments for the non-advice call.
  2398. //
  2399. // BcelVar[] adviceVars = munger.getExposedStateAsBcelVars();
  2400. // IntMap proceedMap = makeProceedArgumentMap(adviceVars);
  2401. //
  2402. // System.out.println(proceedMap + " for " + this);
  2403. // System.out.println(argVarList);
  2404. //
  2405. // ResolvedType[] proceedParamTypes =
  2406. // world.resolve(munger.getSignature().getParameterTypes());
  2407. // // remove this*JoinPoint* as arguments to proceed
  2408. // if (munger.getBaseParameterCount()+1 < proceedParamTypes.length) {
  2409. // int len = munger.getBaseParameterCount()+1;
  2410. // ResolvedType[] newTypes = new ResolvedType[len];
  2411. // System.arraycopy(proceedParamTypes, 0, newTypes, 0, len);
  2412. // proceedParamTypes = newTypes;
  2413. // }
  2414. //
  2415. // //System.out.println("stateTypes: " + Arrays.asList(stateTypes));
  2416. // BcelVar[] proceedVars =
  2417. // Utility.pushAndReturnArrayOfVars(proceedParamTypes, ret, fact, localAdviceMethod);
  2418. //
  2419. // Type[] stateTypes = callbackMethod.getArgumentTypes();
  2420. // // System.out.println("stateTypes: " + Arrays.asList(stateTypes));
  2421. //
  2422. // for (int i=0, len=stateTypes.length; i < len; i++) {
  2423. // Type stateType = stateTypes[i];
  2424. // ResolvedType stateTypeX = BcelWorld.fromBcel(stateType).resolve(world);
  2425. // if (proceedMap.hasKey(i)) {
  2426. // //throw new RuntimeException("unimplemented");
  2427. // proceedVars[proceedMap.get(i)].appendLoadAndConvert(ret, fact, stateTypeX);
  2428. // } else {
  2429. // ((BcelVar) argVarList.get(i)).appendLoad(ret, fact);
  2430. // }
  2431. // }
  2432. //
  2433. // ret.append(Utility.createInvoke(fact, callbackMethod));
  2434. // ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(),
  2435. // BcelWorld.makeBcelType(munger.getSignature().getReturnType())));
  2436. // return ret;
  2437. }
  2438. private boolean bindsThis(BcelAdvice munger) {
  2439. UsesThisVisitor utv = new UsesThisVisitor();
  2440. munger.getPointcut().accept(utv, null);
  2441. return utv.usesThis;
  2442. }
  2443. private boolean bindsTarget(BcelAdvice munger) {
  2444. UsesTargetVisitor utv = new UsesTargetVisitor();
  2445. munger.getPointcut().accept(utv, null);
  2446. return utv.usesTarget;
  2447. }
  2448. private static class UsesThisVisitor extends AbstractPatternNodeVisitor {
  2449. boolean usesThis = false;
  2450. @Override
  2451. public Object visit(ThisOrTargetPointcut node, Object data) {
  2452. if (node.isThis() && node.isBinding()) {
  2453. usesThis = true;
  2454. }
  2455. return node;
  2456. }
  2457. @Override
  2458. public Object visit(AndPointcut node, Object data) {
  2459. if (!usesThis) {
  2460. node.getLeft().accept(this, data);
  2461. }
  2462. if (!usesThis) {
  2463. node.getRight().accept(this, data);
  2464. }
  2465. return node;
  2466. }
  2467. @Override
  2468. public Object visit(NotPointcut node, Object data) {
  2469. if (!usesThis) {
  2470. node.getNegatedPointcut().accept(this, data);
  2471. }
  2472. return node;
  2473. }
  2474. @Override
  2475. public Object visit(OrPointcut node, Object data) {
  2476. if (!usesThis) {
  2477. node.getLeft().accept(this, data);
  2478. }
  2479. if (!usesThis) {
  2480. node.getRight().accept(this, data);
  2481. }
  2482. return node;
  2483. }
  2484. }
  2485. private static class UsesTargetVisitor extends AbstractPatternNodeVisitor {
  2486. boolean usesTarget = false;
  2487. @Override
  2488. public Object visit(ThisOrTargetPointcut node, Object data) {
  2489. if (!node.isThis() && node.isBinding()) {
  2490. usesTarget = true;
  2491. }
  2492. return node;
  2493. }
  2494. @Override
  2495. public Object visit(AndPointcut node, Object data) {
  2496. if (!usesTarget) {
  2497. node.getLeft().accept(this, data);
  2498. }
  2499. if (!usesTarget) {
  2500. node.getRight().accept(this, data);
  2501. }
  2502. return node;
  2503. }
  2504. @Override
  2505. public Object visit(NotPointcut node, Object data) {
  2506. if (!usesTarget) {
  2507. node.getNegatedPointcut().accept(this, data);
  2508. }
  2509. return node;
  2510. }
  2511. @Override
  2512. public Object visit(OrPointcut node, Object data) {
  2513. if (!usesTarget) {
  2514. node.getLeft().accept(this, data);
  2515. }
  2516. if (!usesTarget) {
  2517. node.getRight().accept(this, data);
  2518. }
  2519. return node;
  2520. }
  2521. }
  2522. BcelVar aroundClosureInstance = null;
  2523. public void weaveAroundClosure(BcelAdvice munger, boolean hasDynamicTest) {
  2524. InstructionFactory fact = getFactory();
  2525. enclosingMethod.setCanInline(false);
  2526. int linenumber = getSourceLine();
  2527. // MOVE OUT ALL THE INSTRUCTIONS IN MY SHADOW INTO ANOTHER METHOD!
  2528. // callbackMethod will be something like: "static final void m_aroundBody0(I)"
  2529. boolean shadowClassIsInterface = getEnclosingClass().isInterface();
  2530. LazyMethodGen callbackMethod = extractShadowInstructionsIntoNewMethod(
  2531. NameMangler.aroundShadowMethodName(getSignature(), getEnclosingClass().getNewGeneratedNameTag()), shadowClassIsInterface?Modifier.PUBLIC:0,
  2532. munger.getSourceLocation(), new ArrayList<>(),shadowClassIsInterface);
  2533. BcelVar[] adviceVars = munger.getExposedStateAsBcelVars(true);
  2534. String closureClassName = NameMangler.makeClosureClassName(getEnclosingClass().getType(), getEnclosingClass()
  2535. .getNewGeneratedNameTag());
  2536. Member constructorSig = new MemberImpl(Member.CONSTRUCTOR, UnresolvedType.forName(closureClassName), 0, "<init>",
  2537. "([Ljava/lang/Object;)V");
  2538. BcelVar closureHolder = null;
  2539. // This is not being used currently since getKind() == preinitializaiton
  2540. // cannot happen in around advice
  2541. if (getKind() == PreInitialization) {
  2542. closureHolder = genTempVar(AjcMemberMaker.AROUND_CLOSURE_TYPE);
  2543. }
  2544. InstructionList closureInstantiation = makeClosureInstantiation(constructorSig, closureHolder);
  2545. /* LazyMethodGen constructor = */
  2546. makeClosureClassAndReturnConstructor(closureClassName, callbackMethod, makeProceedArgumentMap(adviceVars));
  2547. InstructionList returnConversionCode;
  2548. if (getKind() == PreInitialization) {
  2549. returnConversionCode = new InstructionList();
  2550. BcelVar stateTempVar = genTempVar(UnresolvedType.OBJECTARRAY);
  2551. closureHolder.appendLoad(returnConversionCode, fact);
  2552. returnConversionCode.append(Utility.createInvoke(fact, world, AjcMemberMaker.aroundClosurePreInitializationGetter()));
  2553. stateTempVar.appendStore(returnConversionCode, fact);
  2554. Type[] stateTypes = getSuperConstructorParameterTypes();
  2555. returnConversionCode.append(InstructionConstants.ALOAD_0); // put "this" back on the stack
  2556. for (int i = 0, len = stateTypes.length; i < len; i++) {
  2557. UnresolvedType bcelTX = BcelWorld.fromBcel(stateTypes[i]);
  2558. ResolvedType stateRTX = world.resolve(bcelTX, true);
  2559. if (stateRTX.isMissing()) {
  2560. world.getLint().cantFindType.signal(
  2561. new String[] { WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE_PREINIT,
  2562. bcelTX.getClassName()) }, getSourceLocation(),
  2563. new ISourceLocation[] { munger.getSourceLocation() });
  2564. // IMessage msg = new Message(
  2565. // WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE_PREINIT,bcelTX.getClassName()),
  2566. // "",IMessage.ERROR,getSourceLocation(),null,
  2567. // new ISourceLocation[]{ munger.getSourceLocation()});
  2568. // world.getMessageHandler().handleMessage(msg);
  2569. }
  2570. stateTempVar.appendConvertableArrayLoad(returnConversionCode, fact, i, stateRTX);
  2571. }
  2572. } else {
  2573. // pr226201
  2574. Member mungerSignature = munger.getSignature();
  2575. if (munger.getSignature() instanceof ResolvedMember) {
  2576. if (((ResolvedMember) mungerSignature).hasBackingGenericMember()) {
  2577. mungerSignature = ((ResolvedMember) mungerSignature).getBackingGenericMember();
  2578. }
  2579. }
  2580. UnresolvedType returnType = mungerSignature.getReturnType();
  2581. returnConversionCode = Utility.createConversion(getFactory(), BcelWorld.makeBcelType(returnType),
  2582. callbackMethod.getReturnType(), world.isInJava5Mode());
  2583. if (!isFallsThrough()) {
  2584. returnConversionCode.append(InstructionFactory.createReturn(callbackMethod.getReturnType()));
  2585. }
  2586. }
  2587. // initialize the bit flags for this shadow
  2588. int bitflags = 0x000000;
  2589. if (getKind().isTargetSameAsThis()) {
  2590. bitflags |= 0x010000;
  2591. }
  2592. if (hasThis()) {
  2593. bitflags |= 0x001000;
  2594. }
  2595. if (bindsThis(munger)) {
  2596. bitflags |= 0x000100;
  2597. }
  2598. if (hasTarget()) {
  2599. bitflags |= 0x000010;
  2600. }
  2601. if (bindsTarget(munger)) {
  2602. bitflags |= 0x000001;
  2603. }
  2604. closureVarInitialized = false;
  2605. // ATAJ for @AJ aspect we need to link the closure with the joinpoint instance
  2606. if (munger.getConcreteAspect() != null && munger.getConcreteAspect().isAnnotationStyleAspect()
  2607. && munger.getDeclaringAspect() != null && munger.getDeclaringAspect().resolve(world).isAnnotationStyleAspect()) {
  2608. aroundClosureInstance = genTempVar(AjcMemberMaker.AROUND_CLOSURE_TYPE);
  2609. closureInstantiation.append(fact.createDup(1));
  2610. aroundClosureInstance.appendStore(closureInstantiation, fact);
  2611. // stick the bitflags on the stack and call the variant of linkClosureAndJoinPoint that takes an int
  2612. closureInstantiation.append(fact.createConstant(bitflags));
  2613. if (needAroundClosureStacking) {
  2614. closureInstantiation.append(Utility.createInvoke(getFactory(), getWorld(),
  2615. new MemberImpl(Member.METHOD, UnresolvedType.forName("org.aspectj.runtime.internal.AroundClosure"),
  2616. Modifier.PUBLIC, "linkStackClosureAndJoinPoint", String.format("%s%s", "(I)", "Lorg/aspectj/lang/ProceedingJoinPoint;"))));
  2617. } else {
  2618. closureInstantiation.append(Utility.createInvoke(getFactory(), getWorld(),
  2619. new MemberImpl(Member.METHOD, UnresolvedType.forName("org.aspectj.runtime.internal.AroundClosure"),
  2620. Modifier.PUBLIC, "linkClosureAndJoinPoint", String.format("%s%s", "(I)", "Lorg/aspectj/lang/ProceedingJoinPoint;"))));
  2621. }
  2622. }
  2623. InstructionList advice = new InstructionList();
  2624. advice.append(munger.getAdviceArgSetup(this, null, closureInstantiation));
  2625. // invoke the advice
  2626. InstructionHandle tryUnlinkPosition = advice.append(munger.getNonTestAdviceInstructions(this));
  2627. if (needAroundClosureStacking) {
  2628. // Call AroundClosure.unlink() in a 'finally' block
  2629. if (munger.getConcreteAspect() != null && munger.getConcreteAspect().isAnnotationStyleAspect()
  2630. && munger.getDeclaringAspect() != null
  2631. && munger.getDeclaringAspect().resolve(world).isAnnotationStyleAspect()
  2632. && closureVarInitialized) {
  2633. // Call unlink when 'normal' flow occurring
  2634. aroundClosureInstance.appendLoad(advice, fact);
  2635. InstructionHandle unlinkInsn = advice.append(Utility.createInvoke(getFactory(), getWorld(), new MemberImpl(Member.METHOD, UnresolvedType
  2636. .forName("org.aspectj.runtime.internal.AroundClosure"), Modifier.PUBLIC, "unlink",
  2637. "()V")));
  2638. BranchHandle jumpOverHandler = advice.append(new InstructionBranch(Constants.GOTO, null));
  2639. // Call unlink in finally block
  2640. // Do not POP the exception off, we need to rethrow it
  2641. InstructionHandle handlerStart = advice.append(aroundClosureInstance.createLoad(fact));
  2642. advice.append(Utility.createInvoke(getFactory(), getWorld(), new MemberImpl(Member.METHOD, UnresolvedType
  2643. .forName("org.aspectj.runtime.internal.AroundClosure"), Modifier.PUBLIC, "unlink",
  2644. "()V")));
  2645. // After that exception is on the top of the stack again
  2646. advice.append(InstructionConstants.ATHROW);
  2647. InstructionHandle jumpTarget = advice.append(InstructionConstants.NOP);
  2648. jumpOverHandler.setTarget(jumpTarget);
  2649. enclosingMethod.addExceptionHandler(tryUnlinkPosition, unlinkInsn, handlerStart, null/* ==finally */, false);
  2650. }
  2651. }
  2652. advice.append(returnConversionCode);
  2653. if (getKind() == Shadow.MethodExecution && linenumber > 0) {
  2654. advice.getStart().addTargeter(new LineNumberTag(linenumber));
  2655. }
  2656. if (!hasDynamicTest) {
  2657. range.append(advice);
  2658. } else {
  2659. InstructionList callback = makeCallToCallback(callbackMethod);
  2660. InstructionList postCallback = new InstructionList();
  2661. if (terminatesWithReturn()) {
  2662. callback.append(InstructionFactory.createReturn(callbackMethod.getReturnType()));
  2663. } else {
  2664. advice.append(InstructionFactory.createBranchInstruction(Constants.GOTO,
  2665. postCallback.append(InstructionConstants.NOP)));
  2666. }
  2667. range.append(munger.getTestInstructions(this, advice.getStart(), callback.getStart(), advice.getStart()));
  2668. range.append(advice);
  2669. range.append(callback);
  2670. range.append(postCallback);
  2671. }
  2672. }
  2673. // exposed for testing
  2674. InstructionList makeCallToCallback(LazyMethodGen callbackMethod) {
  2675. InstructionFactory fact = getFactory();
  2676. InstructionList callback = new InstructionList();
  2677. if (thisVar != null) {
  2678. callback.append(InstructionConstants.ALOAD_0);
  2679. }
  2680. if (targetVar != null && targetVar != thisVar) {
  2681. callback.append(BcelRenderer.renderExpr(fact, world, targetVar));
  2682. }
  2683. callback.append(BcelRenderer.renderExprs(fact, world, argVars));
  2684. // remember to render tjps
  2685. if (thisJoinPointVar != null) {
  2686. callback.append(BcelRenderer.renderExpr(fact, world, thisJoinPointVar));
  2687. }
  2688. callback.append(Utility.createInvoke(fact, callbackMethod));
  2689. return callback;
  2690. }
  2691. /** side-effect-free */
  2692. private InstructionList makeClosureInstantiation(Member constructor, BcelVar holder) {
  2693. // LazyMethodGen constructor) {
  2694. InstructionFactory fact = getFactory();
  2695. BcelVar arrayVar = genTempVar(UnresolvedType.OBJECTARRAY);
  2696. // final Type objectArrayType = new ArrayType(Type.OBJECT, 1);
  2697. final InstructionList il = new InstructionList();
  2698. int alen = getArgCount() + (thisVar == null ? 0 : 1) + ((targetVar != null && targetVar != thisVar) ? 1 : 0)
  2699. + (thisJoinPointVar == null ? 0 : 1);
  2700. il.append(Utility.createConstant(fact, alen));
  2701. il.append(fact.createNewArray(Type.OBJECT, (short) 1));
  2702. arrayVar.appendStore(il, fact);
  2703. int stateIndex = 0;
  2704. if (thisVar != null) {
  2705. arrayVar.appendConvertableArrayStore(il, fact, stateIndex, thisVar);
  2706. thisVar.setPositionInAroundState(stateIndex);
  2707. stateIndex++;
  2708. }
  2709. if (targetVar != null && targetVar != thisVar) {
  2710. arrayVar.appendConvertableArrayStore(il, fact, stateIndex, targetVar);
  2711. targetVar.setPositionInAroundState(stateIndex);
  2712. stateIndex++;
  2713. }
  2714. for (int i = 0, len = getArgCount(); i < len; i++) {
  2715. arrayVar.appendConvertableArrayStore(il, fact, stateIndex, argVars[i]);
  2716. argVars[i].setPositionInAroundState(stateIndex);
  2717. stateIndex++;
  2718. }
  2719. if (thisJoinPointVar != null) {
  2720. arrayVar.appendConvertableArrayStore(il, fact, stateIndex, thisJoinPointVar);
  2721. thisJoinPointVar.setPositionInAroundState(stateIndex);
  2722. stateIndex++;
  2723. }
  2724. il.append(fact.createNew(new ObjectType(constructor.getDeclaringType().getName())));
  2725. il.append(InstructionConstants.DUP);
  2726. arrayVar.appendLoad(il, fact);
  2727. il.append(Utility.createInvoke(fact, world, constructor));
  2728. if (getKind() == PreInitialization) {
  2729. il.append(InstructionConstants.DUP);
  2730. holder.appendStore(il, fact);
  2731. }
  2732. return il;
  2733. }
  2734. private IntMap makeProceedArgumentMap(BcelVar[] adviceArgs) {
  2735. // System.err.println("coming in with " + Arrays.asList(adviceArgs));
  2736. IntMap ret = new IntMap();
  2737. for (int i = 0, len = adviceArgs.length; i < len; i++) {
  2738. BcelVar v = adviceArgs[i];
  2739. if (v == null) {
  2740. continue; // XXX we don't know why this is required
  2741. }
  2742. int pos = v.getPositionInAroundState();
  2743. if (pos >= 0) { // need this test to avoid args bound via cflow
  2744. ret.put(pos, i);
  2745. }
  2746. }
  2747. // System.err.println("returning " + ret);
  2748. return ret;
  2749. }
  2750. /**
  2751. *
  2752. * @param callbackMethod the method we will call back to when our run method gets called.
  2753. * @param proceedMap A map from state position to proceed argument position. May be non covering on state position.
  2754. */
  2755. private LazyMethodGen makeClosureClassAndReturnConstructor(String closureClassName, LazyMethodGen callbackMethod,
  2756. IntMap proceedMap) {
  2757. String superClassName = "org.aspectj.runtime.internal.AroundClosure";
  2758. Type objectArrayType = new ArrayType(Type.OBJECT, 1);
  2759. LazyClassGen closureClass = new LazyClassGen(closureClassName, superClassName, getEnclosingClass().getFileName(),
  2760. Modifier.PUBLIC, new String[] {}, getWorld());
  2761. closureClass.setMajorMinor(getEnclosingClass().getMajor(), getEnclosingClass().getMinor());
  2762. InstructionFactory fact = new InstructionFactory(closureClass.getConstantPool());
  2763. // constructor
  2764. LazyMethodGen constructor = new LazyMethodGen(Modifier.PUBLIC, Type.VOID, "<init>", new Type[] { objectArrayType },
  2765. new String[] {}, closureClass);
  2766. InstructionList cbody = constructor.getBody();
  2767. cbody.append(InstructionFactory.createLoad(Type.OBJECT, 0));
  2768. cbody.append(InstructionFactory.createLoad(objectArrayType, 1));
  2769. cbody.append(fact
  2770. .createInvoke(superClassName, "<init>", Type.VOID, new Type[] { objectArrayType }, Constants.INVOKESPECIAL));
  2771. cbody.append(InstructionFactory.createReturn(Type.VOID));
  2772. closureClass.addMethodGen(constructor);
  2773. // Create the 'Object run(Object[])' method
  2774. LazyMethodGen runMethod = new LazyMethodGen(Modifier.PUBLIC, Type.OBJECT, "run", new Type[] { objectArrayType },
  2775. new String[] {}, closureClass);
  2776. InstructionList mbody = runMethod.getBody();
  2777. BcelVar proceedVar = new BcelVar(UnresolvedType.OBJECTARRAY.resolve(world), 1);
  2778. // int proceedVarIndex = 1;
  2779. BcelVar stateVar = new BcelVar(UnresolvedType.OBJECTARRAY.resolve(world), runMethod.allocateLocal(1));
  2780. // int stateVarIndex = runMethod.allocateLocal(1);
  2781. mbody.append(InstructionFactory.createThis());
  2782. mbody.append(fact.createGetField(superClassName, "state", objectArrayType));
  2783. mbody.append(stateVar.createStore(fact));
  2784. // mbody.append(fact.createStore(objectArrayType, stateVarIndex));
  2785. Type[] stateTypes = callbackMethod.getArgumentTypes();
  2786. for (int i = 0, len = stateTypes.length; i < len; i++) {
  2787. ResolvedType resolvedStateType = BcelWorld.fromBcel(stateTypes[i]).resolve(world);
  2788. if (proceedMap.hasKey(i)) {
  2789. mbody.append(proceedVar.createConvertableArrayLoad(fact, proceedMap.get(i), resolvedStateType));
  2790. } else {
  2791. mbody.append(stateVar.createConvertableArrayLoad(fact, i, resolvedStateType));
  2792. }
  2793. }
  2794. mbody.append(Utility.createInvoke(fact, callbackMethod));
  2795. if (getKind() == PreInitialization) {
  2796. mbody.append(Utility.createSet(fact, AjcMemberMaker.aroundClosurePreInitializationField()));
  2797. mbody.append(InstructionConstants.ACONST_NULL);
  2798. } else {
  2799. mbody.append(Utility.createConversion(fact, callbackMethod.getReturnType(), Type.OBJECT));
  2800. }
  2801. mbody.append(InstructionFactory.createReturn(Type.OBJECT));
  2802. closureClass.addMethodGen(runMethod);
  2803. // class
  2804. getEnclosingClass().addGeneratedInner(closureClass);
  2805. return constructor;
  2806. }
  2807. // ---- extraction methods
  2808. /**
  2809. * Extract the instructions in the shadow to a new method.
  2810. *
  2811. * @param extractedMethodName name for the new method
  2812. * @param extractedMethodVisibilityModifier visibility modifiers for the new method
  2813. * @param adviceSourceLocation source location of the advice affecting the shadow
  2814. * @param beingPlacedInInterface is this new method going into an interface
  2815. */
  2816. LazyMethodGen extractShadowInstructionsIntoNewMethod(String extractedMethodName, int extractedMethodVisibilityModifier,
  2817. ISourceLocation adviceSourceLocation, List<String> parameterNames, boolean beingPlacedInInterface) {
  2818. // LazyMethodGen.assertGoodBody(range.getBody(), extractedMethodName);
  2819. if (!getKind().allowsExtraction()) {
  2820. throw new BCException("Attempt to extract method from a shadow kind (" + getKind()
  2821. + ") that does not support this operation");
  2822. }
  2823. LazyMethodGen newMethod = createShadowMethodGen(extractedMethodName, extractedMethodVisibilityModifier, parameterNames, beingPlacedInInterface);
  2824. IntMap remapper = makeRemap();
  2825. range.extractInstructionsInto(newMethod, remapper, (getKind() != PreInitialization) && isFallsThrough());
  2826. if (getKind() == PreInitialization) {
  2827. addPreInitializationReturnCode(newMethod, getSuperConstructorParameterTypes());
  2828. }
  2829. getEnclosingClass().addMethodGen(newMethod, adviceSourceLocation);
  2830. return newMethod;
  2831. }
  2832. private void addPreInitializationReturnCode(LazyMethodGen extractedMethod, Type[] superConstructorTypes) {
  2833. InstructionList body = extractedMethod.getBody();
  2834. final InstructionFactory fact = getFactory();
  2835. BcelVar arrayVar = new BcelVar(world.getCoreType(UnresolvedType.OBJECTARRAY), extractedMethod.allocateLocal(1));
  2836. int len = superConstructorTypes.length;
  2837. body.append(Utility.createConstant(fact, len));
  2838. body.append(fact.createNewArray(Type.OBJECT, (short) 1));
  2839. arrayVar.appendStore(body, fact);
  2840. for (int i = len - 1; i >= 0; i++) {
  2841. // convert thing on top of stack to object
  2842. body.append(Utility.createConversion(fact, superConstructorTypes[i], Type.OBJECT));
  2843. // push object array
  2844. arrayVar.appendLoad(body, fact);
  2845. // swap
  2846. body.append(InstructionConstants.SWAP);
  2847. // do object array store.
  2848. body.append(Utility.createConstant(fact, i));
  2849. body.append(InstructionConstants.SWAP);
  2850. body.append(InstructionFactory.createArrayStore(Type.OBJECT));
  2851. }
  2852. arrayVar.appendLoad(body, fact);
  2853. body.append(InstructionConstants.ARETURN);
  2854. }
  2855. private Type[] getSuperConstructorParameterTypes() {
  2856. // assert getKind() == PreInitialization
  2857. InstructionHandle superCallHandle = getRange().getEnd().getNext();
  2858. InvokeInstruction superCallInstruction = (InvokeInstruction) superCallHandle.getInstruction();
  2859. return superCallInstruction.getArgumentTypes(getEnclosingClass().getConstantPool());
  2860. }
  2861. /**
  2862. * make a map from old frame location to new frame location. Any unkeyed frame location picks out a copied local
  2863. */
  2864. private IntMap makeRemap() {
  2865. IntMap ret = new IntMap(5);
  2866. int reti = 0;
  2867. if (thisVar != null) {
  2868. ret.put(0, reti++); // thisVar guaranteed to be 0
  2869. }
  2870. if (targetVar != null && targetVar != thisVar) {
  2871. ret.put(targetVar.getSlot(), reti++);
  2872. }
  2873. for (BcelVar argVar : argVars) {
  2874. ret.put(argVar.getSlot(), reti);
  2875. reti += argVar.getType().getSize();
  2876. }
  2877. if (thisJoinPointVar != null) {
  2878. ret.put(thisJoinPointVar.getSlot(), reti++);
  2879. }
  2880. // we not only need to put the arguments, we also need to remap their
  2881. // aliases, which we so helpfully put into temps at the beginning of this join
  2882. // point.
  2883. if (!getKind().argsOnStack()) {
  2884. int oldi = 0;
  2885. int newi = 0;
  2886. // if we're passing in a this and we're not argsOnStack we're always
  2887. // passing in a target too
  2888. if (arg0HoldsThis()) {
  2889. ret.put(0, 0);
  2890. oldi++;
  2891. newi += 1;
  2892. }
  2893. // assert targetVar == thisVar
  2894. for (int i = 0; i < getArgCount(); i++) {
  2895. UnresolvedType type = getArgType(i);
  2896. ret.put(oldi, newi);
  2897. oldi += type.getSize();
  2898. newi += type.getSize();
  2899. }
  2900. }
  2901. // System.err.println("making remap for : " + this);
  2902. // if (targetVar != null) System.err.println("target slot : " + targetVar.getSlot());
  2903. // if (thisVar != null) System.err.println(" this slot : " + thisVar.getSlot());
  2904. // System.err.println(ret);
  2905. return ret;
  2906. }
  2907. /**
  2908. * The new method always static. It may take some extra arguments: this, target. If it's argsOnStack, then it must take both
  2909. * this/target If it's argsOnFrame, it shares this and target. ??? rewrite this to do less array munging, please
  2910. */
  2911. private LazyMethodGen createShadowMethodGen(String newMethodName, int visibilityModifier, List<String> parameterNames, boolean beingPlacedInInterface) {
  2912. Type[] shadowParameterTypes = BcelWorld.makeBcelTypes(getArgTypes());
  2913. int modifiers = (world.useFinal() && !beingPlacedInInterface ? Modifier.FINAL : 0) | Modifier.STATIC | visibilityModifier;
  2914. if (targetVar != null && targetVar != thisVar) {
  2915. UnresolvedType targetType = getTargetType();
  2916. targetType = ensureTargetTypeIsCorrect(targetType);
  2917. // see pr109728,pr229910 - this fixes the case when the declaring class is sometype 'X' but the (gs)etfield
  2918. // in the bytecode refers to a subtype of 'X'. This makes sure we use the type originally
  2919. // mentioned in the fieldget instruction as the method parameter and *not* the type upon which the
  2920. // field is declared because when the instructions are extracted into the new around body,
  2921. // they will still refer to the subtype.
  2922. if ((getKind() == FieldGet || getKind() == FieldSet) && getActualTargetType() != null
  2923. && !getActualTargetType().equals(targetType.getName())) {
  2924. targetType = UnresolvedType.forName(getActualTargetType()).resolve(world);
  2925. }
  2926. ResolvedMember resolvedMember = getSignature().resolve(world);
  2927. // pr230075, pr197719
  2928. if (resolvedMember != null && Modifier.isProtected(resolvedMember.getModifiers())
  2929. && !samePackage(resolvedMember.getDeclaringType().getPackageName(), getEnclosingType().getPackageName())
  2930. && !resolvedMember.getName().equals("clone")) {
  2931. if (!hasThis()) { // pr197719 - static accessor has been created to handle the call
  2932. if (Modifier.isStatic(enclosingMethod.getAccessFlags()) && enclosingMethod.getName().startsWith("access$")) {
  2933. targetType = BcelWorld.fromBcel(enclosingMethod.getArgumentTypes()[0]);
  2934. }
  2935. } else {
  2936. if (!targetType.resolve(world).isAssignableFrom(getThisType().resolve(world))) {
  2937. throw new BCException("bad bytecode");
  2938. }
  2939. targetType = getThisType();
  2940. }
  2941. }
  2942. parameterNames.add("target");
  2943. // There is a 'target' and it is not the same as 'this', so add it to the parameter list
  2944. shadowParameterTypes = addTypeToFront(BcelWorld.makeBcelType(targetType), shadowParameterTypes);
  2945. }
  2946. if (thisVar != null) {
  2947. UnresolvedType thisType = getThisType();
  2948. parameterNames.add(0, "ajc$this");
  2949. shadowParameterTypes = addTypeToFront(BcelWorld.makeBcelType(thisType), shadowParameterTypes);
  2950. }
  2951. if (this.getKind() == Shadow.FieldSet || this.getKind() == Shadow.FieldGet) {
  2952. parameterNames.add(getSignature().getName());
  2953. } else {
  2954. String[] pnames = getSignature().getParameterNames(world);
  2955. if (pnames != null) {
  2956. for (int i = 0; i < pnames.length; i++) {
  2957. if (i == 0 && pnames[i].equals("this")) {
  2958. parameterNames.add("ajc$this");
  2959. } else {
  2960. parameterNames.add(pnames[i]);
  2961. }
  2962. }
  2963. }
  2964. }
  2965. // We always want to pass down thisJoinPoint in case we have already woven
  2966. // some advice in here. If we only have a single piece of around advice on a
  2967. // join point, it is unnecessary to accept (and pass) tjp.
  2968. if (thisJoinPointVar != null) {
  2969. parameterNames.add("thisJoinPoint");
  2970. shadowParameterTypes = addTypeToEnd(LazyClassGen.tjpType, shadowParameterTypes);
  2971. }
  2972. UnresolvedType returnType;
  2973. if (getKind() == PreInitialization) {
  2974. returnType = UnresolvedType.OBJECTARRAY;
  2975. } else {
  2976. if (getKind() == ConstructorCall) {
  2977. returnType = getSignature().getDeclaringType();
  2978. } else if (getKind() == FieldSet) {
  2979. returnType = UnresolvedType.VOID;
  2980. } else {
  2981. returnType = getSignature().getReturnType().resolve(world);
  2982. // returnType = getReturnType(); // for this and above lines, see pr137496
  2983. }
  2984. }
  2985. return new LazyMethodGen(modifiers, BcelWorld.makeBcelType(returnType), newMethodName, shadowParameterTypes,
  2986. NoDeclaredExceptions, getEnclosingClass());
  2987. }
  2988. private boolean samePackage(String p1, String p2) {
  2989. if (p1 == null) {
  2990. return p2 == null;
  2991. }
  2992. if (p2 == null) {
  2993. return false;
  2994. }
  2995. return p1.equals(p2);
  2996. }
  2997. private Type[] addTypeToFront(Type type, Type[] types) {
  2998. int len = types.length;
  2999. Type[] ret = new Type[len + 1];
  3000. ret[0] = type;
  3001. System.arraycopy(types, 0, ret, 1, len);
  3002. return ret;
  3003. }
  3004. private Type[] addTypeToEnd(Type type, Type[] types) {
  3005. int len = types.length;
  3006. Type[] ret = new Type[len + 1];
  3007. ret[len] = type;
  3008. System.arraycopy(types, 0, ret, 0, len);
  3009. return ret;
  3010. }
  3011. public BcelVar genTempVar(UnresolvedType utype) {
  3012. ResolvedType rtype = utype.resolve(world);
  3013. return new BcelVar(rtype, genTempVarIndex(rtype.getSize()));
  3014. }
  3015. // public static final boolean CREATE_TEMP_NAMES = true;
  3016. public BcelVar genTempVar(UnresolvedType typeX, String localName) {
  3017. BcelVar tv = genTempVar(typeX);
  3018. // if (CREATE_TEMP_NAMES) {
  3019. // for (InstructionHandle ih = range.getStart(); ih != range.getEnd(); ih = ih.getNext()) {
  3020. // if (Range.isRangeHandle(ih)) continue;
  3021. // ih.addTargeter(new LocalVariableTag(typeX, localName, tv.getSlot()));
  3022. // }
  3023. // }
  3024. return tv;
  3025. }
  3026. // eh doesn't think we need to garbage collect these (64K is a big number...)
  3027. private int genTempVarIndex(int size) {
  3028. return enclosingMethod.allocateLocal(size);
  3029. }
  3030. public InstructionFactory getFactory() {
  3031. return getEnclosingClass().getFactory();
  3032. }
  3033. @Override
  3034. public ISourceLocation getSourceLocation() {
  3035. int sourceLine = getSourceLine();
  3036. if (sourceLine == 0 || sourceLine == -1) {
  3037. // Thread.currentThread().dumpStack();
  3038. // System.err.println(this + ": " + range);
  3039. return getEnclosingClass().getType().getSourceLocation();
  3040. } else {
  3041. // For staticinitialization, if we have a nice offset, don't build a new source loc
  3042. if (getKind() == Shadow.StaticInitialization && getEnclosingClass().getType().getSourceLocation().getOffset() != 0) {
  3043. return getEnclosingClass().getType().getSourceLocation();
  3044. } else {
  3045. int offset = 0;
  3046. Kind kind = getKind();
  3047. if ((kind == MethodExecution) || (kind == ConstructorExecution) || (kind == AdviceExecution)
  3048. || (kind == StaticInitialization) || (kind == PreInitialization) || (kind == Initialization)) {
  3049. if (getEnclosingMethod().hasDeclaredLineNumberInfo()) {
  3050. offset = getEnclosingMethod().getDeclarationOffset();
  3051. }
  3052. }
  3053. return getEnclosingClass().getType().getSourceContext().makeSourceLocation(sourceLine, offset);
  3054. }
  3055. }
  3056. }
  3057. public Shadow getEnclosingShadow() {
  3058. return enclosingShadow;
  3059. }
  3060. public LazyMethodGen getEnclosingMethod() {
  3061. return enclosingMethod;
  3062. }
  3063. public boolean isFallsThrough() {
  3064. return !terminatesWithReturn();
  3065. }
  3066. public void setActualTargetType(String className) {
  3067. this.actualInstructionTargetType = className;
  3068. }
  3069. public String getActualTargetType() {
  3070. return actualInstructionTargetType;
  3071. }
  3072. }