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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425
  1. /* *******************************************************************
  2. * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
  3. * All rights reserved.
  4. * This program and the accompanying materials are made available
  5. * under the terms of the Eclipse Public License v1.0
  6. * which accompanies this distribution and is available at
  7. * http://www.eclipse.org/legal/epl-v10.html
  8. *
  9. * Contributors:
  10. * PARC initial implementation
  11. * Alexandre Vasseur 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.Iterator;
  19. import java.util.List;
  20. import java.util.Map;
  21. import org.aspectj.apache.bcel.Constants;
  22. import org.aspectj.apache.bcel.classfile.ConstantPool;
  23. import org.aspectj.apache.bcel.classfile.Field;
  24. import org.aspectj.apache.bcel.generic.ArrayType;
  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<ShadowMunger>();
  144. }
  145. List<ShadowMunger> dest = s.mungers;
  146. for (Iterator<ShadowMunger> i = src.iterator(); i.hasNext();) {
  147. dest.add(i.next());
  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<BcelAdvice>();
  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 (Iterator<BcelAdvice> iter = badAdvice.iterator(); iter.hasNext();) {
  336. BcelAdvice element = iter.next();
  337. ISourceLocation sLoc = element.getSourceLocation();
  338. if (sLoc != null && sLoc.getLine() > 0) {
  339. valid++;
  340. }
  341. }
  342. if (valid != 0) {
  343. ISourceLocation[] badLocs = new ISourceLocation[valid];
  344. int i = 0;
  345. for (Iterator<BcelAdvice> iter = badAdvice.iterator(); iter.hasNext();) {
  346. BcelAdvice element = iter.next();
  347. ISourceLocation sLoc = element.getSourceLocation();
  348. if (sLoc != null) {
  349. badLocs[i++] = sLoc;
  350. }
  351. }
  352. world.getLint().multipleAdviceStoppingLazyTjp
  353. .signal(new String[] { this.toString() }, getSourceLocation(), badLocs);
  354. }
  355. }
  356. badAdvice = null;
  357. // If we are an expression kind, we require our target/arguments on the stack
  358. // before we do our actual thing. However, they may have been removed
  359. // from the stack as the shadowMungers have requested state.
  360. // if any of our shadowMungers requested either the arguments or target,
  361. // the munger will have added code
  362. // to pop the target/arguments into temporary variables, represented by
  363. // targetVar and argVars. In such a case, we must make sure to re-push the
  364. // values.
  365. // If we are nonExpressionKind, we don't expect arguments on the stack
  366. // so this is moot. If our argVars happen to be null, then we know that
  367. // no ShadowMunger has squirrelled away our arguments, so they're still
  368. // on the stack.
  369. InstructionFactory fact = getFactory();
  370. if (getKind().argsOnStack() && argVars != null) {
  371. // Special case first (pr46298). If we are an exception handler and the instruction
  372. // just after the shadow is a POP then we should remove the pop. The code
  373. // above which generated the store instruction has already cleared the stack.
  374. // We also don't generate any code for the arguments in this case as it would be
  375. // an incorrect aload.
  376. if (getKind() == ExceptionHandler && range.getEnd().getNext().getInstruction().equals(InstructionConstants.POP)) {
  377. // easier than deleting it ...
  378. range.getEnd().getNext().setInstruction(InstructionConstants.NOP);
  379. } else {
  380. range.insert(BcelRenderer.renderExprs(fact, world, argVars), Range.InsideBefore);
  381. if (targetVar != null) {
  382. range.insert(BcelRenderer.renderExpr(fact, world, targetVar), Range.InsideBefore);
  383. }
  384. if (getKind() == ConstructorCall) {
  385. if (!world.isJoinpointArrayConstructionEnabled() || !this.getSignature().getDeclaringType().isArray()) {
  386. if (deletedNewAndDup) { // if didnt delete them, dont insert any!
  387. range.insert(InstructionFactory.createDup(1), Range.InsideBefore);
  388. range.insert(fact.createNew((ObjectType) BcelWorld.makeBcelType(getSignature().getDeclaringType())),
  389. Range.InsideBefore);
  390. }
  391. }
  392. }
  393. }
  394. }
  395. }
  396. // ---- getters
  397. public ShadowRange getRange() {
  398. return range;
  399. }
  400. public void setRange(ShadowRange range) {
  401. this.range = range;
  402. }
  403. private int sourceline = -1;
  404. public int getSourceLine() {
  405. // if the kind of join point for which we are a shadow represents
  406. // a method or constructor execution, then the best source line is
  407. // the one from the enclosingMethod declarationLineNumber if available.
  408. if (sourceline != -1) {
  409. return sourceline;
  410. }
  411. Kind kind = getKind();
  412. if ((kind == MethodExecution) || (kind == ConstructorExecution) || (kind == AdviceExecution)
  413. || (kind == StaticInitialization) || (kind == PreInitialization) || (kind == Initialization)) {
  414. if (getEnclosingMethod().hasDeclaredLineNumberInfo()) {
  415. sourceline = getEnclosingMethod().getDeclarationLineNumber();
  416. return sourceline;
  417. }
  418. }
  419. if (range == null) {
  420. if (getEnclosingMethod().hasBody()) {
  421. sourceline = Utility.getSourceLine(getEnclosingMethod().getBody().getStart());
  422. return sourceline;
  423. } else {
  424. sourceline = 0;
  425. return sourceline;
  426. }
  427. }
  428. sourceline = Utility.getSourceLine(range.getStart());
  429. if (sourceline < 0) {
  430. sourceline = 0;
  431. }
  432. return sourceline;
  433. }
  434. @Override
  435. public ResolvedType getEnclosingType() {
  436. return getEnclosingClass().getType();
  437. }
  438. public LazyClassGen getEnclosingClass() {
  439. return enclosingMethod.getEnclosingClass();
  440. }
  441. public BcelWorld getWorld() {
  442. return world;
  443. }
  444. // ---- factory methods
  445. public static BcelShadow makeConstructorExecution(BcelWorld world, LazyMethodGen enclosingMethod,
  446. InstructionHandle justBeforeStart) {
  447. final InstructionList body = enclosingMethod.getBody();
  448. BcelShadow s = new BcelShadow(world, ConstructorExecution, world.makeJoinPointSignatureFromMethod(enclosingMethod,
  449. Member.CONSTRUCTOR), enclosingMethod, null);
  450. ShadowRange r = new ShadowRange(body);
  451. r.associateWithShadow(s);
  452. r.associateWithTargets(Range.genStart(body, justBeforeStart.getNext()), Range.genEnd(body));
  453. return s;
  454. }
  455. public static BcelShadow makeStaticInitialization(BcelWorld world, LazyMethodGen enclosingMethod) {
  456. InstructionList body = enclosingMethod.getBody();
  457. // move the start past ajc$preClinit
  458. InstructionHandle clinitStart = body.getStart();
  459. if (clinitStart.getInstruction() instanceof InvokeInstruction) {
  460. InvokeInstruction ii = (InvokeInstruction) clinitStart.getInstruction();
  461. if (ii.getName(enclosingMethod.getEnclosingClass().getConstantPool()).equals(NameMangler.AJC_PRE_CLINIT_NAME)) {
  462. clinitStart = clinitStart.getNext();
  463. }
  464. }
  465. InstructionHandle clinitEnd = body.getEnd();
  466. // XXX should move the end before the postClinit, but the return is then tricky...
  467. // if (clinitEnd.getInstruction() instanceof InvokeInstruction) {
  468. // InvokeInstruction ii = (InvokeInstruction)clinitEnd.getInstruction();
  469. // if (ii.getName(enclosingMethod.getEnclosingClass().getConstantPool()).equals(NameMangler.AJC_POST_CLINIT_NAME)) {
  470. // clinitEnd = clinitEnd.getPrev();
  471. // }
  472. // }
  473. BcelShadow s = new BcelShadow(world, StaticInitialization, world.makeJoinPointSignatureFromMethod(enclosingMethod,
  474. Member.STATIC_INITIALIZATION), enclosingMethod, null);
  475. ShadowRange r = new ShadowRange(body);
  476. r.associateWithShadow(s);
  477. r.associateWithTargets(Range.genStart(body, clinitStart), Range.genEnd(body, clinitEnd));
  478. return s;
  479. }
  480. /**
  481. * Make the shadow for an exception handler. Currently makes an empty shadow that only allows before advice to be woven into it.
  482. */
  483. public static BcelShadow makeExceptionHandler(BcelWorld world, ExceptionRange exceptionRange, LazyMethodGen enclosingMethod,
  484. InstructionHandle startOfHandler, BcelShadow enclosingShadow) {
  485. InstructionList body = enclosingMethod.getBody();
  486. UnresolvedType catchType = exceptionRange.getCatchType();
  487. UnresolvedType inType = enclosingMethod.getEnclosingClass().getType();
  488. ResolvedMemberImpl sig = MemberImpl.makeExceptionHandlerSignature(inType, catchType);
  489. sig.setParameterNames(new String[] { findHandlerParamName(startOfHandler) });
  490. BcelShadow s = new BcelShadow(world, ExceptionHandler, sig, enclosingMethod, enclosingShadow);
  491. ShadowRange r = new ShadowRange(body);
  492. r.associateWithShadow(s);
  493. InstructionHandle start = Range.genStart(body, startOfHandler);
  494. InstructionHandle end = Range.genEnd(body, start);
  495. r.associateWithTargets(start, end);
  496. exceptionRange.updateTarget(startOfHandler, start, body);
  497. return s;
  498. }
  499. private static String findHandlerParamName(InstructionHandle startOfHandler) {
  500. if (startOfHandler.getInstruction().isStoreInstruction() && startOfHandler.getNext() != null) {
  501. int slot = startOfHandler.getInstruction().getIndex();
  502. // System.out.println("got store: " + startOfHandler.getInstruction() + ", " + index);
  503. Iterator<InstructionTargeter> tIter = startOfHandler.getNext().getTargeters().iterator();
  504. while (tIter.hasNext()) {
  505. InstructionTargeter targeter = tIter.next();
  506. if (targeter instanceof LocalVariableTag) {
  507. LocalVariableTag t = (LocalVariableTag) targeter;
  508. if (t.getSlot() == slot) {
  509. return t.getName();
  510. }
  511. }
  512. }
  513. }
  514. return "<missing>";
  515. }
  516. /** create an init join point associated w/ an interface in the body of a constructor */
  517. public static BcelShadow makeIfaceInitialization(BcelWorld world, LazyMethodGen constructor,
  518. Member interfaceConstructorSignature) {
  519. // this call marks the instruction list as changed
  520. constructor.getBody();
  521. // UnresolvedType inType = constructor.getEnclosingClass().getType();
  522. BcelShadow s = new BcelShadow(world, Initialization, interfaceConstructorSignature, constructor, null);
  523. // s.fallsThrough = true;
  524. // ShadowRange r = new ShadowRange(body);
  525. // r.associateWithShadow(s);
  526. // InstructionHandle start = Range.genStart(body, handle);
  527. // InstructionHandle end = Range.genEnd(body, handle);
  528. //
  529. // r.associateWithTargets(start, end);
  530. return s;
  531. }
  532. public void initIfaceInitializer(InstructionHandle end) {
  533. final InstructionList body = enclosingMethod.getBody();
  534. ShadowRange r = new ShadowRange(body);
  535. r.associateWithShadow(this);
  536. InstructionHandle nop = body.insert(end, InstructionConstants.NOP);
  537. r.associateWithTargets(Range.genStart(body, nop), Range.genEnd(body, nop));
  538. }
  539. // public static BcelShadow makeIfaceConstructorExecution(
  540. // BcelWorld world,
  541. // LazyMethodGen constructor,
  542. // InstructionHandle next,
  543. // Member interfaceConstructorSignature)
  544. // {
  545. // // final InstructionFactory fact = constructor.getEnclosingClass().getFactory();
  546. // InstructionList body = constructor.getBody();
  547. // // UnresolvedType inType = constructor.getEnclosingClass().getType();
  548. // BcelShadow s =
  549. // new BcelShadow(
  550. // world,
  551. // ConstructorExecution,
  552. // interfaceConstructorSignature,
  553. // constructor,
  554. // null);
  555. // s.fallsThrough = true;
  556. // ShadowRange r = new ShadowRange(body);
  557. // r.associateWithShadow(s);
  558. // // ??? this may or may not work
  559. // InstructionHandle start = Range.genStart(body, next);
  560. // //InstructionHandle end = Range.genEnd(body, body.append(start, fact.NOP));
  561. // InstructionHandle end = Range.genStart(body, next);
  562. // //body.append(start, fact.NOP);
  563. //
  564. // r.associateWithTargets(start, end);
  565. // return s;
  566. // }
  567. /**
  568. * Create an initialization join point associated with a constructor, but not with any body of code yet. If this is actually
  569. * matched, it's range will be set when we inline self constructors.
  570. *
  571. * @param constructor The constructor starting this initialization.
  572. */
  573. public static BcelShadow makeUnfinishedInitialization(BcelWorld world, LazyMethodGen constructor) {
  574. BcelShadow ret = new BcelShadow(world, Initialization, world.makeJoinPointSignatureFromMethod(constructor,
  575. Member.CONSTRUCTOR), constructor, null);
  576. if (constructor.getEffectiveSignature() != null) {
  577. ret.setMatchingSignature(constructor.getEffectiveSignature().getEffectiveSignature());
  578. }
  579. return ret;
  580. }
  581. public static BcelShadow makeUnfinishedPreinitialization(BcelWorld world, LazyMethodGen constructor) {
  582. BcelShadow ret = new BcelShadow(world, PreInitialization, world.makeJoinPointSignatureFromMethod(constructor,
  583. Member.CONSTRUCTOR), constructor, null);
  584. if (constructor.getEffectiveSignature() != null) {
  585. ret.setMatchingSignature(constructor.getEffectiveSignature().getEffectiveSignature());
  586. }
  587. return ret;
  588. }
  589. public static BcelShadow makeMethodExecution(BcelWorld world, LazyMethodGen enclosingMethod, boolean lazyInit) {
  590. if (!lazyInit) {
  591. return makeMethodExecution(world, enclosingMethod);
  592. }
  593. BcelShadow s = new BcelShadow(world, MethodExecution, enclosingMethod.getMemberView(), enclosingMethod, null);
  594. return s;
  595. }
  596. public void init() {
  597. if (range != null) {
  598. return;
  599. }
  600. final InstructionList body = enclosingMethod.getBody();
  601. ShadowRange r = new ShadowRange(body);
  602. r.associateWithShadow(this);
  603. r.associateWithTargets(Range.genStart(body), Range.genEnd(body));
  604. }
  605. public static BcelShadow makeMethodExecution(BcelWorld world, LazyMethodGen enclosingMethod) {
  606. return makeShadowForMethod(world, enclosingMethod, MethodExecution, enclosingMethod.getMemberView());
  607. }
  608. public static BcelShadow makeShadowForMethod(BcelWorld world, LazyMethodGen enclosingMethod, Shadow.Kind kind, Member sig) {
  609. final InstructionList body = enclosingMethod.getBody();
  610. BcelShadow s = new BcelShadow(world, kind, sig, enclosingMethod, null);
  611. ShadowRange r = new ShadowRange(body);
  612. r.associateWithShadow(s);
  613. r.associateWithTargets(// OPTIMIZE this occurs lots of times for all jp kinds...
  614. Range.genStart(body), Range.genEnd(body));
  615. return s;
  616. }
  617. public static BcelShadow makeAdviceExecution(BcelWorld world, LazyMethodGen enclosingMethod) {
  618. final InstructionList body = enclosingMethod.getBody();
  619. BcelShadow s = new BcelShadow(world, AdviceExecution,
  620. world.makeJoinPointSignatureFromMethod(enclosingMethod, Member.ADVICE), enclosingMethod, null);
  621. ShadowRange r = new ShadowRange(body);
  622. r.associateWithShadow(s);
  623. r.associateWithTargets(Range.genStart(body), Range.genEnd(body));
  624. return s;
  625. }
  626. // constructor call shadows are <em>initially</em> just around the
  627. // call to the constructor. If ANY advice gets put on it, we move
  628. // the NEW instruction inside the join point, which involves putting
  629. // all the arguments in temps.
  630. public static BcelShadow makeConstructorCall(BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle callHandle,
  631. BcelShadow enclosingShadow) {
  632. final InstructionList body = enclosingMethod.getBody();
  633. Member sig = world.makeJoinPointSignatureForMethodInvocation(enclosingMethod.getEnclosingClass(),
  634. (InvokeInstruction) callHandle.getInstruction());
  635. BcelShadow s = new BcelShadow(world, ConstructorCall, sig, enclosingMethod, enclosingShadow);
  636. ShadowRange r = new ShadowRange(body);
  637. r.associateWithShadow(s);
  638. r.associateWithTargets(Range.genStart(body, callHandle), Range.genEnd(body, callHandle));
  639. retargetAllBranches(callHandle, r.getStart());
  640. return s;
  641. }
  642. public static BcelShadow makeArrayConstructorCall(BcelWorld world, LazyMethodGen enclosingMethod,
  643. InstructionHandle arrayInstruction, BcelShadow enclosingShadow) {
  644. final InstructionList body = enclosingMethod.getBody();
  645. Member sig = world.makeJoinPointSignatureForArrayConstruction(enclosingMethod.getEnclosingClass(), arrayInstruction);
  646. BcelShadow s = new BcelShadow(world, ConstructorCall, sig, enclosingMethod, enclosingShadow);
  647. ShadowRange r = new ShadowRange(body);
  648. r.associateWithShadow(s);
  649. r.associateWithTargets(Range.genStart(body, arrayInstruction), Range.genEnd(body, arrayInstruction));
  650. retargetAllBranches(arrayInstruction, r.getStart());
  651. return s;
  652. }
  653. public static BcelShadow makeMonitorEnter(BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle monitorInstruction,
  654. BcelShadow enclosingShadow) {
  655. final InstructionList body = enclosingMethod.getBody();
  656. Member sig = world.makeJoinPointSignatureForMonitorEnter(enclosingMethod.getEnclosingClass(), monitorInstruction);
  657. BcelShadow s = new BcelShadow(world, SynchronizationLock, sig, enclosingMethod, enclosingShadow);
  658. ShadowRange r = new ShadowRange(body);
  659. r.associateWithShadow(s);
  660. r.associateWithTargets(Range.genStart(body, monitorInstruction), Range.genEnd(body, monitorInstruction));
  661. retargetAllBranches(monitorInstruction, r.getStart());
  662. return s;
  663. }
  664. public static BcelShadow makeMonitorExit(BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle monitorInstruction,
  665. BcelShadow enclosingShadow) {
  666. final InstructionList body = enclosingMethod.getBody();
  667. Member sig = world.makeJoinPointSignatureForMonitorExit(enclosingMethod.getEnclosingClass(), monitorInstruction);
  668. BcelShadow s = new BcelShadow(world, SynchronizationUnlock, sig, enclosingMethod, enclosingShadow);
  669. ShadowRange r = new ShadowRange(body);
  670. r.associateWithShadow(s);
  671. r.associateWithTargets(Range.genStart(body, monitorInstruction), Range.genEnd(body, monitorInstruction));
  672. retargetAllBranches(monitorInstruction, r.getStart());
  673. return s;
  674. }
  675. // see pr77166
  676. // public static BcelShadow makeArrayLoadCall(
  677. // BcelWorld world,
  678. // LazyMethodGen enclosingMethod,
  679. // InstructionHandle arrayInstruction,
  680. // BcelShadow enclosingShadow)
  681. // {
  682. // final InstructionList body = enclosingMethod.getBody();
  683. // Member sig = world.makeJoinPointSignatureForArrayLoad(enclosingMethod.getEnclosingClass(),arrayInstruction);
  684. // BcelShadow s =
  685. // new BcelShadow(
  686. // world,
  687. // MethodCall,
  688. // sig,
  689. // enclosingMethod,
  690. // enclosingShadow);
  691. // ShadowRange r = new ShadowRange(body);
  692. // r.associateWithShadow(s);
  693. // r.associateWithTargets(
  694. // Range.genStart(body, arrayInstruction),
  695. // Range.genEnd(body, arrayInstruction));
  696. // retargetAllBranches(arrayInstruction, r.getStart());
  697. // return s;
  698. // }
  699. public static BcelShadow makeMethodCall(BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle callHandle,
  700. BcelShadow enclosingShadow) {
  701. final InstructionList body = enclosingMethod.getBody();
  702. BcelShadow s = new BcelShadow(world, MethodCall, world.makeJoinPointSignatureForMethodInvocation(
  703. enclosingMethod.getEnclosingClass(), (InvokeInstruction) callHandle.getInstruction()), enclosingMethod,
  704. enclosingShadow);
  705. ShadowRange r = new ShadowRange(body);
  706. r.associateWithShadow(s);
  707. r.associateWithTargets(Range.genStart(body, callHandle), Range.genEnd(body, callHandle));
  708. retargetAllBranches(callHandle, r.getStart());
  709. return s;
  710. }
  711. public static BcelShadow makeShadowForMethodCall(BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle callHandle,
  712. BcelShadow enclosingShadow, Kind kind, ResolvedMember sig) {
  713. final InstructionList body = enclosingMethod.getBody();
  714. BcelShadow s = new BcelShadow(world, kind, sig, enclosingMethod, enclosingShadow);
  715. ShadowRange r = new ShadowRange(body);
  716. r.associateWithShadow(s);
  717. r.associateWithTargets(Range.genStart(body, callHandle), Range.genEnd(body, callHandle));
  718. retargetAllBranches(callHandle, r.getStart());
  719. return s;
  720. }
  721. public static BcelShadow makeFieldGet(BcelWorld world, ResolvedMember field, LazyMethodGen enclosingMethod,
  722. InstructionHandle getHandle, BcelShadow enclosingShadow) {
  723. final InstructionList body = enclosingMethod.getBody();
  724. BcelShadow s = new BcelShadow(world, FieldGet, field,
  725. // BcelWorld.makeFieldSignature(
  726. // enclosingMethod.getEnclosingClass(),
  727. // (FieldInstruction) getHandle.getInstruction()),
  728. enclosingMethod, enclosingShadow);
  729. ShadowRange r = new ShadowRange(body);
  730. r.associateWithShadow(s);
  731. r.associateWithTargets(Range.genStart(body, getHandle), Range.genEnd(body, getHandle));
  732. retargetAllBranches(getHandle, r.getStart());
  733. return s;
  734. }
  735. public static BcelShadow makeFieldSet(BcelWorld world, ResolvedMember field, LazyMethodGen enclosingMethod,
  736. InstructionHandle setHandle, BcelShadow enclosingShadow) {
  737. final InstructionList body = enclosingMethod.getBody();
  738. BcelShadow s = new BcelShadow(world, FieldSet, field,
  739. // BcelWorld.makeFieldJoinPointSignature(
  740. // enclosingMethod.getEnclosingClass(),
  741. // (FieldInstruction) setHandle.getInstruction()),
  742. enclosingMethod, enclosingShadow);
  743. ShadowRange r = new ShadowRange(body);
  744. r.associateWithShadow(s);
  745. r.associateWithTargets(Range.genStart(body, setHandle), Range.genEnd(body, setHandle));
  746. retargetAllBranches(setHandle, r.getStart());
  747. return s;
  748. }
  749. public static void retargetAllBranches(InstructionHandle from, InstructionHandle to) {
  750. for (InstructionTargeter source : from.getTargetersCopy()) {
  751. if (source instanceof InstructionBranch) {
  752. source.updateTarget(from, to);
  753. }
  754. }
  755. }
  756. // // ---- type access methods
  757. // private ObjectType getTargetBcelType() {
  758. // return (ObjectType) BcelWorld.makeBcelType(getTargetType());
  759. // }
  760. // private Type getArgBcelType(int arg) {
  761. // return BcelWorld.makeBcelType(getArgType(arg));
  762. // }
  763. // ---- kinding
  764. /**
  765. * If the end of my range has no real instructions following then my context needs a return at the end.
  766. */
  767. public boolean terminatesWithReturn() {
  768. return getRange().getRealNext() == null;
  769. }
  770. /**
  771. * Is arg0 occupied with the value of this
  772. */
  773. public boolean arg0HoldsThis() {
  774. if (getKind().isEnclosingKind()) {
  775. return !Modifier.isStatic(getSignature().getModifiers());
  776. } else if (enclosingShadow == null) {
  777. // XXX this is mostly right
  778. // this doesn't do the right thing for calls in the pre part of introduced constructors.
  779. return !enclosingMethod.isStatic();
  780. } else {
  781. return ((BcelShadow) enclosingShadow).arg0HoldsThis();
  782. }
  783. }
  784. // ---- argument getting methods
  785. private BcelVar thisVar = null;
  786. private BcelVar targetVar = null;
  787. private BcelVar[] argVars = null;
  788. private Map<ResolvedType, AnnotationAccessVar> kindedAnnotationVars = null;
  789. private Map<ResolvedType, TypeAnnotationAccessVar> thisAnnotationVars = null;
  790. private Map<ResolvedType, TypeAnnotationAccessVar> targetAnnotationVars = null;
  791. // private Map/* <UnresolvedType,BcelVar> */[] argAnnotationVars = null;
  792. private Map<ResolvedType, AnnotationAccessVar> withinAnnotationVars = null;
  793. private Map<ResolvedType, AnnotationAccessVar> withincodeAnnotationVars = null;
  794. private boolean allArgVarsInitialized = false;
  795. @Override
  796. public Var getThisVar() {
  797. if (!hasThis()) {
  798. throw new IllegalStateException("no this");
  799. }
  800. initializeThisVar();
  801. return thisVar;
  802. }
  803. @Override
  804. public Var getThisAnnotationVar(UnresolvedType forAnnotationType) {
  805. if (!hasThis()) {
  806. throw new IllegalStateException("no this");
  807. }
  808. initializeThisAnnotationVars(); // FIXME asc Why bother with this if we always return one?
  809. // Even if we can't find one, we have to return one as we might have this annotation at runtime
  810. Var v = thisAnnotationVars.get(forAnnotationType);
  811. if (v == null) {
  812. v = new TypeAnnotationAccessVar(forAnnotationType.resolve(world), (BcelVar) getThisVar());
  813. }
  814. return v;
  815. }
  816. @Override
  817. public Var getTargetVar() {
  818. if (!hasTarget()) {
  819. throw new IllegalStateException("no target");
  820. }
  821. initializeTargetVar();
  822. return targetVar;
  823. }
  824. @Override
  825. public Var getTargetAnnotationVar(UnresolvedType forAnnotationType) {
  826. if (!hasTarget()) {
  827. throw new IllegalStateException("no target");
  828. }
  829. initializeTargetAnnotationVars(); // FIXME asc why bother with this if we always return one?
  830. Var v = targetAnnotationVars.get(forAnnotationType);
  831. // Even if we can't find one, we have to return one as we might have this annotation at runtime
  832. if (v == null) {
  833. v = new TypeAnnotationAccessVar(forAnnotationType.resolve(world), (BcelVar) getTargetVar());
  834. }
  835. return v;
  836. }
  837. @Override
  838. public Var getArgVar(int i) {
  839. ensureInitializedArgVar(i);
  840. return argVars[i];
  841. }
  842. @Override
  843. public Var getArgAnnotationVar(int i, UnresolvedType forAnnotationType) {
  844. return new TypeAnnotationAccessVar(forAnnotationType.resolve(world), (BcelVar) getArgVar(i));
  845. // initializeArgAnnotationVars();
  846. //
  847. // Var v = (Var) argAnnotationVars[i].get(forAnnotationType);
  848. // if (v == null) {
  849. // v = new TypeAnnotationAccessVar(forAnnotationType.resolve(world), (BcelVar) getArgVar(i));
  850. // }
  851. // return v;
  852. }
  853. @Override
  854. public Var getKindedAnnotationVar(UnresolvedType forAnnotationType) {
  855. initializeKindedAnnotationVars();
  856. return kindedAnnotationVars.get(forAnnotationType);
  857. }
  858. @Override
  859. public Var getWithinAnnotationVar(UnresolvedType forAnnotationType) {
  860. initializeWithinAnnotationVars();
  861. return withinAnnotationVars.get(forAnnotationType);
  862. }
  863. @Override
  864. public Var getWithinCodeAnnotationVar(UnresolvedType forAnnotationType) {
  865. initializeWithinCodeAnnotationVars();
  866. return withincodeAnnotationVars.get(forAnnotationType);
  867. }
  868. // reflective thisJoinPoint support
  869. private BcelVar thisJoinPointVar = null;
  870. private boolean isThisJoinPointLazy;
  871. private int lazyTjpConsumers = 0;
  872. private BcelVar thisJoinPointStaticPartVar = null;
  873. // private BcelVar thisEnclosingJoinPointStaticPartVar = null;
  874. @Override
  875. public final Var getThisJoinPointStaticPartVar() {
  876. return getThisJoinPointStaticPartBcelVar();
  877. }
  878. @Override
  879. public final Var getThisEnclosingJoinPointStaticPartVar() {
  880. return getThisEnclosingJoinPointStaticPartBcelVar();
  881. }
  882. public void requireThisJoinPoint(boolean hasGuardTest, boolean isAround) {
  883. if (!isAround) {
  884. if (!hasGuardTest) {
  885. isThisJoinPointLazy = false;
  886. } else {
  887. lazyTjpConsumers++;
  888. }
  889. }
  890. // if (!hasGuardTest) {
  891. // isThisJoinPointLazy = false;
  892. // } else {
  893. // lazyTjpConsumers++;
  894. // }
  895. if (thisJoinPointVar == null) {
  896. thisJoinPointVar = genTempVar(UnresolvedType.forName("org.aspectj.lang.JoinPoint"));
  897. }
  898. }
  899. @Override
  900. public Var getThisJoinPointVar() {
  901. requireThisJoinPoint(false, false);
  902. return thisJoinPointVar;
  903. }
  904. void initializeThisJoinPoint() {
  905. if (thisJoinPointVar == null) {
  906. return;
  907. }
  908. if (isThisJoinPointLazy) {
  909. isThisJoinPointLazy = checkLazyTjp();
  910. }
  911. if (isThisJoinPointLazy) {
  912. appliedLazyTjpOptimization = true;
  913. createThisJoinPoint(); // make sure any state needed is initialized, but throw the instructions out
  914. if (lazyTjpConsumers == 1) {
  915. return; // special case only one lazyTjpUser
  916. }
  917. InstructionFactory fact = getFactory();
  918. InstructionList il = new InstructionList();
  919. il.append(InstructionConstants.ACONST_NULL);
  920. il.append(thisJoinPointVar.createStore(fact));
  921. range.insert(il, Range.OutsideBefore);
  922. } else {
  923. appliedLazyTjpOptimization = false;
  924. InstructionFactory fact = getFactory();
  925. InstructionList il = createThisJoinPoint();
  926. il.append(thisJoinPointVar.createStore(fact));
  927. range.insert(il, Range.OutsideBefore);
  928. }
  929. }
  930. private boolean checkLazyTjp() {
  931. // check for around advice
  932. for (Iterator<ShadowMunger> i = mungers.iterator(); i.hasNext();) {
  933. ShadowMunger munger = i.next();
  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<ResolvedType, TypeAnnotationAccessVar>();
  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<ResolvedType, TypeAnnotationAccessVar>();
  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 (int i = 0; i < rtx.length; i++) {
  1302. ResolvedType typeX = rtx[i];
  1303. targetAnnotationVars.put(typeX, new TypeAnnotationAccessVar(typeX, (BcelVar) getTargetVar()));
  1304. }
  1305. // populate.
  1306. }
  1307. }
  1308. // public void initializeArgAnnotationVars() {
  1309. // if (argAnnotationVars != null) {
  1310. // return;
  1311. // }
  1312. // int numArgs = getArgCount();
  1313. // argAnnotationVars = new Map[numArgs];
  1314. // for (int i = 0; i < argAnnotationVars.length; i++) {
  1315. // argAnnotationVars[i] = new HashMap();
  1316. // // FIXME asc just delete this logic - we always build the Var on demand, as we don't know at weave time
  1317. // // what the full set of annotations could be (due to static/dynamic type differences...)
  1318. // }
  1319. // }
  1320. protected ResolvedMember getRelevantMember(ResolvedMember foundMember, Member relevantMember, ResolvedType relevantType) {
  1321. if (foundMember != null) {
  1322. return foundMember;
  1323. }
  1324. foundMember = getSignature().resolve(world);
  1325. if (foundMember == null && relevantMember != null) {
  1326. foundMember = relevantType.lookupMemberWithSupersAndITDs(relevantMember);
  1327. }
  1328. // check the ITD'd dooberries
  1329. List<ConcreteTypeMunger> mungers = relevantType.resolve(world).getInterTypeMungers();
  1330. for (ConcreteTypeMunger typeMunger : mungers) {
  1331. if (typeMunger.getMunger() instanceof NewMethodTypeMunger || typeMunger.getMunger() instanceof NewConstructorTypeMunger) {
  1332. ResolvedMember fakerm = typeMunger.getSignature();
  1333. if (fakerm.getName().equals(getSignature().getName())
  1334. && fakerm.getParameterSignature().equals(getSignature().getParameterSignature())) {
  1335. if (foundMember.getKind() == ResolvedMember.CONSTRUCTOR) {
  1336. foundMember = AjcMemberMaker.interConstructor(relevantType, foundMember, typeMunger.getAspectType());
  1337. } else {
  1338. foundMember = AjcMemberMaker.interMethod(foundMember, typeMunger.getAspectType(), false);
  1339. // ResolvedMember o = AjcMemberMaker.interMethodBody(fakerm, typeMunger.getAspectType());
  1340. // // Object os = o.getAnnotations();
  1341. // ResolvedMember foundMember2 = findMethod(typeMunger.getAspectType(), o);
  1342. // Object os2 = foundMember2.getAnnotations();
  1343. // int stop = 1;
  1344. // foundMember = foundMember2;
  1345. // foundMember = AjcMemberMaker.interMethod(foundMember, typeMunger.getAspectType());
  1346. }
  1347. // in the above.. what about if it's on an Interface? Can that happen?
  1348. // then the last arg of the above should be true
  1349. return foundMember;
  1350. }
  1351. }
  1352. }
  1353. return foundMember;
  1354. }
  1355. protected ResolvedType[] getAnnotations(ResolvedMember foundMember, Member relevantMember, ResolvedType relevantType) {
  1356. if (foundMember == null) {
  1357. // check the ITD'd dooberries
  1358. List<ConcreteTypeMunger> mungers = relevantType.resolve(world).getInterTypeMungers();
  1359. for (Iterator<ConcreteTypeMunger> iter = mungers.iterator(); iter.hasNext();) {
  1360. Object munger = iter.next();
  1361. ConcreteTypeMunger typeMunger = (ConcreteTypeMunger) munger;
  1362. if (typeMunger.getMunger() instanceof NewMethodTypeMunger
  1363. || typeMunger.getMunger() instanceof NewConstructorTypeMunger) {
  1364. ResolvedMember fakerm = typeMunger.getSignature();
  1365. // if (fakerm.hasAnnotations())
  1366. ResolvedMember ajcMethod = (getSignature().getKind() == ResolvedMember.CONSTRUCTOR ? AjcMemberMaker
  1367. .postIntroducedConstructor(typeMunger.getAspectType(), fakerm.getDeclaringType(),
  1368. fakerm.getParameterTypes()) : AjcMemberMaker.interMethodDispatcher(fakerm,
  1369. typeMunger.getAspectType()));
  1370. // AjcMemberMaker.interMethodBody(fakerm,typeMunger.getAspectType()));
  1371. ResolvedMember rmm = findMethod(typeMunger.getAspectType(), ajcMethod);
  1372. if (fakerm.getName().equals(getSignature().getName())
  1373. && fakerm.getParameterSignature().equals(getSignature().getParameterSignature())) {
  1374. relevantType = typeMunger.getAspectType();
  1375. foundMember = rmm;
  1376. return foundMember.getAnnotationTypes();
  1377. }
  1378. }
  1379. }
  1380. // didn't find in ITDs, look in supers
  1381. foundMember = relevantType.lookupMemberWithSupersAndITDs(relevantMember);
  1382. if (foundMember == null) {
  1383. throw new IllegalStateException("Couldn't find member " + relevantMember + " for type " + relevantType);
  1384. }
  1385. }
  1386. return foundMember.getAnnotationTypes();
  1387. }
  1388. /**
  1389. * By determining what "kind" of shadow we are, we can find out the annotations on the appropriate element (method, field,
  1390. * constructor, type). Then create one BcelVar entry in the map for each annotation, keyed by annotation type.
  1391. */
  1392. public void initializeKindedAnnotationVars() {
  1393. if (kindedAnnotationVars != null) {
  1394. return;
  1395. }
  1396. kindedAnnotationVars = new HashMap<ResolvedType, AnnotationAccessVar>();
  1397. ResolvedType[] annotations = null;
  1398. Member shadowSignature = getSignature();
  1399. Member annotationHolder = getSignature();
  1400. ResolvedType relevantType = shadowSignature.getDeclaringType().resolve(world);
  1401. if (relevantType.isRawType() || relevantType.isParameterizedType()) {
  1402. relevantType = relevantType.getGenericType();
  1403. }
  1404. // Determine the annotations that are of interest
  1405. if (getKind() == Shadow.StaticInitialization) {
  1406. annotations = relevantType.resolve(world).getAnnotationTypes();
  1407. } else if (getKind() == Shadow.MethodCall || getKind() == Shadow.ConstructorCall) {
  1408. ResolvedMember foundMember = findMethod2(relevantType.resolve(world).getDeclaredMethods(), getSignature());
  1409. annotations = getAnnotations(foundMember, shadowSignature, relevantType);
  1410. annotationHolder = getRelevantMember(foundMember, shadowSignature, relevantType);
  1411. relevantType = annotationHolder.getDeclaringType().resolve(world);
  1412. } else if (getKind() == Shadow.FieldSet || getKind() == Shadow.FieldGet) {
  1413. annotationHolder = findField(relevantType.getDeclaredFields(), getSignature());
  1414. if (annotationHolder == null) {
  1415. // check the ITD'd dooberries
  1416. List<ConcreteTypeMunger> mungers = relevantType.resolve(world).getInterTypeMungers();
  1417. for (ConcreteTypeMunger typeMunger : mungers) {
  1418. if (typeMunger.getMunger() instanceof NewFieldTypeMunger) {
  1419. ResolvedMember fakerm = typeMunger.getSignature();
  1420. // if (fakerm.hasAnnotations())
  1421. ResolvedMember ajcMethod = AjcMemberMaker.interFieldInitializer(fakerm, typeMunger.getAspectType());
  1422. ResolvedMember rmm = findMethod(typeMunger.getAspectType(), ajcMethod);
  1423. if (fakerm.equals(getSignature())) {
  1424. relevantType = typeMunger.getAspectType();
  1425. annotationHolder = rmm;
  1426. }
  1427. }
  1428. }
  1429. }
  1430. annotations = ((ResolvedMember) annotationHolder).getAnnotationTypes();
  1431. } else if (getKind() == Shadow.MethodExecution || getKind() == Shadow.ConstructorExecution
  1432. || getKind() == Shadow.AdviceExecution) {
  1433. ResolvedMember foundMember = findMethod2(relevantType.getDeclaredMethods(), getSignature());
  1434. annotations = getAnnotations(foundMember, shadowSignature, relevantType);
  1435. annotationHolder = getRelevantMember(foundMember, annotationHolder, relevantType);
  1436. UnresolvedType ut = annotationHolder.getDeclaringType();
  1437. relevantType = ut.resolve(world);
  1438. } else if (getKind() == Shadow.ExceptionHandler) {
  1439. relevantType = getSignature().getParameterTypes()[0].resolve(world);
  1440. annotations = relevantType.getAnnotationTypes();
  1441. } else if (getKind() == Shadow.PreInitialization || getKind() == Shadow.Initialization) {
  1442. ResolvedMember found = findMethod2(relevantType.getDeclaredMethods(), getSignature());
  1443. annotations = found.getAnnotationTypes();
  1444. }
  1445. if (annotations == null) {
  1446. // We can't have recognized the shadow - should blow up now to be on the safe side
  1447. throw new BCException("Could not discover annotations for shadow: " + getKind());
  1448. }
  1449. for (ResolvedType annotationType : annotations) {
  1450. AnnotationAccessVar accessVar = new AnnotationAccessVar(this, getKind(), annotationType.resolve(world), relevantType,
  1451. annotationHolder, false);
  1452. kindedAnnotationVars.put(annotationType, accessVar);
  1453. }
  1454. }
  1455. private ResolvedMember findMethod2(ResolvedMember members[], Member sig) {
  1456. String signatureName = sig.getName();
  1457. String parameterSignature = sig.getParameterSignature();
  1458. for (ResolvedMember member : members) {
  1459. if (member.getName().equals(signatureName) && member.getParameterSignature().equals(parameterSignature)) {
  1460. return member;
  1461. }
  1462. }
  1463. return null;
  1464. }
  1465. private ResolvedMember findMethod(ResolvedType aspectType, ResolvedMember ajcMethod) {
  1466. ResolvedMember decMethods[] = aspectType.getDeclaredMethods();
  1467. for (int i = 0; i < decMethods.length; i++) {
  1468. ResolvedMember member = decMethods[i];
  1469. if (member.equals(ajcMethod)) {
  1470. return member;
  1471. }
  1472. }
  1473. return null;
  1474. }
  1475. private ResolvedMember findField(ResolvedMember[] members, Member lookingFor) {
  1476. for (int i = 0; i < members.length; i++) {
  1477. ResolvedMember member = members[i];
  1478. if (member.getName().equals(getSignature().getName()) && member.getType().equals(getSignature().getType())) {
  1479. return member;
  1480. }
  1481. }
  1482. return null;
  1483. }
  1484. public void initializeWithinAnnotationVars() {
  1485. if (withinAnnotationVars != null) {
  1486. return;
  1487. }
  1488. withinAnnotationVars = new HashMap<ResolvedType, AnnotationAccessVar>();
  1489. ResolvedType[] annotations = getEnclosingType().resolve(world).getAnnotationTypes();
  1490. for (int i = 0; i < annotations.length; i++) {
  1491. ResolvedType ann = annotations[i];
  1492. Kind k = Shadow.StaticInitialization;
  1493. withinAnnotationVars.put(ann, new AnnotationAccessVar(this, k, ann, getEnclosingType(), null, true));
  1494. }
  1495. }
  1496. public void initializeWithinCodeAnnotationVars() {
  1497. if (withincodeAnnotationVars != null) {
  1498. return;
  1499. }
  1500. withincodeAnnotationVars = new HashMap<ResolvedType, AnnotationAccessVar>();
  1501. // For some shadow we are interested in annotations on the method containing that shadow.
  1502. ResolvedType[] annotations = getEnclosingMethod().getMemberView().getAnnotationTypes();
  1503. for (int i = 0; i < annotations.length; i++) {
  1504. ResolvedType ann = annotations[i];
  1505. Kind k = (getEnclosingMethod().getMemberView().getKind() == Member.CONSTRUCTOR ? Shadow.ConstructorExecution
  1506. : Shadow.MethodExecution);
  1507. withincodeAnnotationVars.put(ann, new AnnotationAccessVar(this, k, ann, getEnclosingType(),
  1508. getEnclosingCodeSignature(), true));
  1509. }
  1510. }
  1511. // ---- weave methods
  1512. void weaveBefore(BcelAdvice munger) {
  1513. range.insert(munger.getAdviceInstructions(this, null, range.getRealStart()), Range.InsideBefore);
  1514. }
  1515. public void weaveAfter(BcelAdvice munger) {
  1516. weaveAfterThrowing(munger, UnresolvedType.THROWABLE);
  1517. weaveAfterReturning(munger);
  1518. }
  1519. /**
  1520. * The basic strategy here is to add a set of instructions at the end of the shadow range that dispatch the advice, and then
  1521. * return whatever the shadow was going to return anyway.
  1522. *
  1523. * To achieve this, we note all the return statements in the advice, and replace them with code that: 1) stores the return value
  1524. * 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
  1525. * advice block before ultimately returning
  1526. *
  1527. * We also need to bind the return value into a returning parameter, if the advice specified one.
  1528. */
  1529. public void weaveAfterReturning(BcelAdvice munger) {
  1530. List<InstructionHandle> returns = findReturnInstructions();
  1531. boolean hasReturnInstructions = !returns.isEmpty();
  1532. // list of instructions that handle the actual return from the join point
  1533. InstructionList retList = new InstructionList();
  1534. // variable that holds the return value
  1535. BcelVar returnValueVar = null;
  1536. if (hasReturnInstructions) {
  1537. returnValueVar = generateReturnInstructions(returns, retList);
  1538. } else {
  1539. // we need at least one instruction, as the target for jumps
  1540. retList.append(InstructionConstants.NOP);
  1541. }
  1542. // list of instructions for dispatching to the advice itself
  1543. InstructionList advice = getAfterReturningAdviceDispatchInstructions(munger, retList.getStart());
  1544. if (hasReturnInstructions) {
  1545. InstructionHandle gotoTarget = advice.getStart();
  1546. for (Iterator<InstructionHandle> i = returns.iterator(); i.hasNext();) {
  1547. InstructionHandle ih = i.next();
  1548. retargetReturnInstruction(munger.hasExtraParameter(), returnValueVar, gotoTarget, ih);
  1549. }
  1550. }
  1551. range.append(advice);
  1552. range.append(retList);
  1553. }
  1554. /**
  1555. * @return a list of all the return instructions in the range of this shadow
  1556. */
  1557. private List<InstructionHandle> findReturnInstructions() {
  1558. List<InstructionHandle> returns = new ArrayList<InstructionHandle>();
  1559. for (InstructionHandle ih = range.getStart(); ih != range.getEnd(); ih = ih.getNext()) {
  1560. if (ih.getInstruction().isReturnInstruction()) {
  1561. returns.add(ih);
  1562. }
  1563. }
  1564. return returns;
  1565. }
  1566. /**
  1567. * Given a list containing all the return instruction handles for this shadow, finds the last return instruction and copies it,
  1568. * making this the ultimate return. If the shadow has a non-void return type, we also create a temporary variable to hold the
  1569. * return value, and load the value from this var before returning (see pr148007 for why we do this - it works around a JRockit
  1570. * bug, and is also closer to what javac generates)
  1571. *
  1572. * Sometimes the 'last return' isnt the right one - some rogue code can include the real return from the body of a subroutine
  1573. * 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
  1574. * non-void return type... pr151673
  1575. *
  1576. * @param returns list of all the return instructions in the shadow
  1577. * @param returnInstructions instruction list into which the return instructions should be generated
  1578. * @return the variable holding the return value, if needed
  1579. */
  1580. private BcelVar generateReturnInstructions(List<InstructionHandle> returns, InstructionList returnInstructions) {
  1581. BcelVar returnValueVar = null;
  1582. if (this.hasANonVoidReturnType()) {
  1583. // Find the last *correct* return - this is a method with a non-void return type
  1584. // so ignore RETURN
  1585. Instruction newReturnInstruction = null;
  1586. int i = returns.size() - 1;
  1587. while (newReturnInstruction == null && i >= 0) {
  1588. InstructionHandle ih = returns.get(i);
  1589. if (ih.getInstruction().opcode != Constants.RETURN) {
  1590. newReturnInstruction = Utility.copyInstruction(ih.getInstruction());
  1591. }
  1592. i--;
  1593. }
  1594. returnValueVar = genTempVar(this.getReturnType());
  1595. returnValueVar.appendLoad(returnInstructions, getFactory());
  1596. returnInstructions.append(newReturnInstruction);
  1597. } else {
  1598. InstructionHandle lastReturnHandle = returns.get(returns.size() - 1);
  1599. Instruction newReturnInstruction = Utility.copyInstruction(lastReturnHandle.getInstruction());
  1600. returnInstructions.append(newReturnInstruction);
  1601. }
  1602. return returnValueVar;
  1603. }
  1604. /**
  1605. * @return true, iff this shadow returns a value
  1606. */
  1607. private boolean hasANonVoidReturnType() {
  1608. return !this.getReturnType().equals(UnresolvedType.VOID);
  1609. }
  1610. /**
  1611. * Get the list of instructions used to dispatch to the after advice
  1612. *
  1613. * @param munger
  1614. * @param firstInstructionInReturnSequence
  1615. * @return
  1616. */
  1617. private InstructionList getAfterReturningAdviceDispatchInstructions(BcelAdvice munger,
  1618. InstructionHandle firstInstructionInReturnSequence) {
  1619. InstructionList advice = new InstructionList();
  1620. BcelVar tempVar = null;
  1621. if (munger.hasExtraParameter()) {
  1622. tempVar = insertAdviceInstructionsForBindingReturningParameter(advice);
  1623. }
  1624. advice.append(munger.getAdviceInstructions(this, tempVar, firstInstructionInReturnSequence));
  1625. return advice;
  1626. }
  1627. /**
  1628. * If the after() returning(Foo f) form is used, bind the return value to the parameter. If the shadow returns void, bind null.
  1629. *
  1630. * @param advice
  1631. * @return
  1632. */
  1633. private BcelVar insertAdviceInstructionsForBindingReturningParameter(InstructionList advice) {
  1634. BcelVar tempVar;
  1635. UnresolvedType tempVarType = getReturnType();
  1636. if (tempVarType.equals(UnresolvedType.VOID)) {
  1637. tempVar = genTempVar(UnresolvedType.OBJECT);
  1638. advice.append(InstructionConstants.ACONST_NULL);
  1639. tempVar.appendStore(advice, getFactory());
  1640. } else {
  1641. tempVar = genTempVar(tempVarType);
  1642. advice.append(InstructionFactory.createDup(tempVarType.getSize()));
  1643. tempVar.appendStore(advice, getFactory());
  1644. }
  1645. return tempVar;
  1646. }
  1647. /**
  1648. * Helper method for weaveAfterReturning
  1649. *
  1650. * Each return instruction in the method body is retargeted by calling this method. The return instruction is replaced by up to
  1651. * three instructions: 1) if the shadow returns a value, and that value is bound to an after returning parameter, then we DUP
  1652. * 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
  1653. * retrieved from here when we ultimately return after the advice dispatch) 3) if the return was the last instruction, we add a
  1654. * NOP (it will fall through to the advice dispatch), otherwise we add a GOTO that branches to the supplied gotoTarget (start of
  1655. * the advice dispatch)
  1656. */
  1657. private void retargetReturnInstruction(boolean hasReturningParameter, BcelVar returnValueVar, InstructionHandle gotoTarget,
  1658. InstructionHandle returnHandle) {
  1659. // pr148007, work around JRockit bug
  1660. // replace ret with store into returnValueVar, followed by goto if not
  1661. // at the end of the instruction list...
  1662. InstructionList newInstructions = new InstructionList();
  1663. if (returnValueVar != null) {
  1664. if (hasReturningParameter) {
  1665. // we have to dup the return val before consuming it...
  1666. newInstructions.append(InstructionFactory.createDup(this.getReturnType().getSize()));
  1667. }
  1668. // store the return value into this var
  1669. returnValueVar.appendStore(newInstructions, getFactory());
  1670. }
  1671. if (!isLastInstructionInRange(returnHandle, range)) {
  1672. newInstructions.append(InstructionFactory.createBranchInstruction(Constants.GOTO, gotoTarget));
  1673. }
  1674. if (newInstructions.isEmpty()) {
  1675. newInstructions.append(InstructionConstants.NOP);
  1676. }
  1677. Utility.replaceInstruction(returnHandle, newInstructions, enclosingMethod);
  1678. }
  1679. private boolean isLastInstructionInRange(InstructionHandle ih, ShadowRange aRange) {
  1680. return ih.getNext() == aRange.getEnd();
  1681. }
  1682. public void weaveAfterThrowing(BcelAdvice munger, UnresolvedType catchType) {
  1683. // a good optimization would be not to generate anything here
  1684. // if the shadow is GUARANTEED empty (i.e., there's NOTHING, not even
  1685. // a shadow, inside me).
  1686. if (getRange().getStart().getNext() == getRange().getEnd()) {
  1687. return;
  1688. }
  1689. InstructionFactory fact = getFactory();
  1690. InstructionList handler = new InstructionList();
  1691. BcelVar exceptionVar = genTempVar(catchType);
  1692. exceptionVar.appendStore(handler, fact);
  1693. // pr62642
  1694. // I will now jump through some firey BCEL hoops to generate a trivial bit of code:
  1695. // if (exc instanceof ExceptionInInitializerError)
  1696. // throw (ExceptionInInitializerError)exc;
  1697. if (this.getEnclosingMethod().getName().equals("<clinit>")) {
  1698. ResolvedType eiieType = world.resolve("java.lang.ExceptionInInitializerError");
  1699. ObjectType eiieBcelType = (ObjectType) BcelWorld.makeBcelType(eiieType);
  1700. InstructionList ih = new InstructionList(InstructionConstants.NOP);
  1701. handler.append(exceptionVar.createLoad(fact));
  1702. handler.append(fact.createInstanceOf(eiieBcelType));
  1703. InstructionBranch bi = InstructionFactory.createBranchInstruction(Constants.IFEQ, ih.getStart());
  1704. handler.append(bi);
  1705. handler.append(exceptionVar.createLoad(fact));
  1706. handler.append(fact.createCheckCast(eiieBcelType));
  1707. handler.append(InstructionConstants.ATHROW);
  1708. handler.append(ih);
  1709. }
  1710. InstructionList endHandler = new InstructionList(exceptionVar.createLoad(fact));
  1711. handler.append(munger.getAdviceInstructions(this, exceptionVar, endHandler.getStart()));
  1712. handler.append(endHandler);
  1713. handler.append(InstructionConstants.ATHROW);
  1714. InstructionHandle handlerStart = handler.getStart();
  1715. if (isFallsThrough()) {
  1716. InstructionHandle jumpTarget = handler.append(InstructionConstants.NOP);
  1717. handler.insert(InstructionFactory.createBranchInstruction(Constants.GOTO, jumpTarget));
  1718. }
  1719. InstructionHandle protectedEnd = handler.getStart();
  1720. range.insert(handler, Range.InsideAfter);
  1721. enclosingMethod.addExceptionHandler(range.getStart().getNext(), protectedEnd.getPrev(), handlerStart,
  1722. (ObjectType) BcelWorld.makeBcelType(catchType), // ???Type.THROWABLE,
  1723. // high priority if our args are on the stack
  1724. getKind().hasHighPriorityExceptions());
  1725. }
  1726. // ??? this shares a lot of code with the above weaveAfterThrowing
  1727. // ??? would be nice to abstract that to say things only once
  1728. public void weaveSoftener(BcelAdvice munger, UnresolvedType catchType) {
  1729. // a good optimization would be not to generate anything here
  1730. // if the shadow is GUARANTEED empty (i.e., there's NOTHING, not even
  1731. // a shadow, inside me).
  1732. if (getRange().getStart().getNext() == getRange().getEnd()) {
  1733. return;
  1734. }
  1735. InstructionFactory fact = getFactory();
  1736. InstructionList handler = new InstructionList();
  1737. InstructionList rtExHandler = new InstructionList();
  1738. BcelVar exceptionVar = genTempVar(catchType);
  1739. handler.append(fact.createNew(NameMangler.SOFT_EXCEPTION_TYPE));
  1740. handler.append(InstructionFactory.createDup(1));
  1741. handler.append(exceptionVar.createLoad(fact));
  1742. handler.append(fact.createInvoke(NameMangler.SOFT_EXCEPTION_TYPE, "<init>", Type.VOID, new Type[] { Type.THROWABLE },
  1743. Constants.INVOKESPECIAL)); // ??? special
  1744. handler.append(InstructionConstants.ATHROW);
  1745. // ENH 42737
  1746. exceptionVar.appendStore(rtExHandler, fact);
  1747. // aload_1
  1748. rtExHandler.append(exceptionVar.createLoad(fact));
  1749. // instanceof class java/lang/RuntimeException
  1750. rtExHandler.append(fact.createInstanceOf(new ObjectType("java.lang.RuntimeException")));
  1751. // ifeq go to new SOFT_EXCEPTION_TYPE instruction
  1752. rtExHandler.append(InstructionFactory.createBranchInstruction(Constants.IFEQ, handler.getStart()));
  1753. // aload_1
  1754. rtExHandler.append(exceptionVar.createLoad(fact));
  1755. // athrow
  1756. rtExHandler.append(InstructionFactory.ATHROW);
  1757. InstructionHandle handlerStart = rtExHandler.getStart();
  1758. if (isFallsThrough()) {
  1759. InstructionHandle jumpTarget = range.getEnd();// handler.append(fact.NOP);
  1760. rtExHandler.insert(InstructionFactory.createBranchInstruction(Constants.GOTO, jumpTarget));
  1761. }
  1762. rtExHandler.append(handler);
  1763. InstructionHandle protectedEnd = rtExHandler.getStart();
  1764. range.insert(rtExHandler, Range.InsideAfter);
  1765. enclosingMethod.addExceptionHandler(range.getStart().getNext(), protectedEnd.getPrev(), handlerStart,
  1766. (ObjectType) BcelWorld.makeBcelType(catchType),
  1767. // high priority if our args are on the stack
  1768. getKind().hasHighPriorityExceptions());
  1769. }
  1770. public void weavePerObjectEntry(final BcelAdvice munger, final BcelVar onVar) {
  1771. final InstructionFactory fact = getFactory();
  1772. InstructionList entryInstructions = new InstructionList();
  1773. InstructionList entrySuccessInstructions = new InstructionList();
  1774. onVar.appendLoad(entrySuccessInstructions, fact);
  1775. entrySuccessInstructions
  1776. .append(Utility.createInvoke(fact, world, AjcMemberMaker.perObjectBind(munger.getConcreteAspect())));
  1777. InstructionList testInstructions = munger.getTestInstructions(this, entrySuccessInstructions.getStart(),
  1778. range.getRealStart(), entrySuccessInstructions.getStart());
  1779. entryInstructions.append(testInstructions);
  1780. entryInstructions.append(entrySuccessInstructions);
  1781. range.insert(entryInstructions, Range.InsideBefore);
  1782. }
  1783. // PTWIMPL Create static initializer to call the aspect factory
  1784. /**
  1785. * Causes the aspect instance to be *set* for later retrievable through localAspectof()/aspectOf()
  1786. */
  1787. public void weavePerTypeWithinAspectInitialization(final BcelAdvice munger, UnresolvedType t) {
  1788. ResolvedType tResolved = t.resolve(world);
  1789. if (tResolved.isInterface()) {
  1790. return; // Don't initialize statics in interfaces
  1791. }
  1792. ResolvedType aspectRT = munger.getConcreteAspect();
  1793. BcelWorld.getBcelObjectType(aspectRT);
  1794. // Although matched, if the visibility rules prevent the aspect from seeing this type, don't
  1795. // insert any code (easier to do it here than try to affect the matching logic, unfortunately)
  1796. if (!(tResolved.canBeSeenBy(aspectRT) || aspectRT.isPrivilegedAspect())) {
  1797. return;
  1798. }
  1799. final InstructionFactory fact = getFactory();
  1800. InstructionList entryInstructions = new InstructionList();
  1801. InstructionList entrySuccessInstructions = new InstructionList();
  1802. String aspectname = munger.getConcreteAspect().getName();
  1803. String ptwField = NameMangler.perTypeWithinFieldForTarget(munger.getConcreteAspect());
  1804. entrySuccessInstructions.append(InstructionFactory.PUSH(fact.getConstantPool(), t.getName()));
  1805. entrySuccessInstructions.append(fact.createInvoke(aspectname, "ajc$createAspectInstance", new ObjectType(aspectname),
  1806. new Type[] { new ObjectType("java.lang.String") }, Constants.INVOKESTATIC));
  1807. entrySuccessInstructions.append(fact.createPutStatic(t.getName(), ptwField, new ObjectType(aspectname)));
  1808. entryInstructions.append(entrySuccessInstructions);
  1809. range.insert(entryInstructions, Range.InsideBefore);
  1810. }
  1811. public void weaveCflowEntry(final BcelAdvice munger, final Member cflowField) {
  1812. final boolean isPer = munger.getKind() == AdviceKind.PerCflowBelowEntry || munger.getKind() == AdviceKind.PerCflowEntry;
  1813. if (!isPer && getKind() == PreInitialization) {
  1814. return;
  1815. }
  1816. final Type objectArrayType = new ArrayType(Type.OBJECT, 1);
  1817. final InstructionFactory fact = getFactory();
  1818. final BcelVar testResult = genTempVar(UnresolvedType.BOOLEAN);
  1819. InstructionList entryInstructions = new InstructionList();
  1820. {
  1821. InstructionList entrySuccessInstructions = new InstructionList();
  1822. if (munger.hasDynamicTests()) {
  1823. entryInstructions.append(Utility.createConstant(fact, 0));
  1824. testResult.appendStore(entryInstructions, fact);
  1825. entrySuccessInstructions.append(Utility.createConstant(fact, 1));
  1826. testResult.appendStore(entrySuccessInstructions, fact);
  1827. }
  1828. if (isPer) {
  1829. entrySuccessInstructions.append(fact.createInvoke(munger.getConcreteAspect().getName(),
  1830. NameMangler.PERCFLOW_PUSH_METHOD, Type.VOID, new Type[] {}, Constants.INVOKESTATIC));
  1831. } else {
  1832. BcelVar[] cflowStateVars = munger.getExposedStateAsBcelVars(false);
  1833. if (cflowStateVars.length == 0) {
  1834. // This should be getting managed by a counter - lets make sure.
  1835. if (!cflowField.getType().getName().endsWith("CFlowCounter")) {
  1836. throw new RuntimeException("Incorrectly attempting counter operation on stacked cflow");
  1837. }
  1838. entrySuccessInstructions.append(Utility.createGet(fact, cflowField));
  1839. // arrayVar.appendLoad(entrySuccessInstructions, fact);
  1840. entrySuccessInstructions.append(fact.createInvoke(NameMangler.CFLOW_COUNTER_TYPE, "inc", Type.VOID,
  1841. new Type[] {}, Constants.INVOKEVIRTUAL));
  1842. } else {
  1843. BcelVar arrayVar = genTempVar(UnresolvedType.OBJECTARRAY);
  1844. int alen = cflowStateVars.length;
  1845. entrySuccessInstructions.append(Utility.createConstant(fact, alen));
  1846. entrySuccessInstructions.append(fact.createNewArray(Type.OBJECT, (short) 1));
  1847. arrayVar.appendStore(entrySuccessInstructions, fact);
  1848. for (int i = 0; i < alen; i++) {
  1849. arrayVar.appendConvertableArrayStore(entrySuccessInstructions, fact, i, cflowStateVars[i]);
  1850. }
  1851. entrySuccessInstructions.append(Utility.createGet(fact, cflowField));
  1852. arrayVar.appendLoad(entrySuccessInstructions, fact);
  1853. entrySuccessInstructions.append(fact.createInvoke(NameMangler.CFLOW_STACK_TYPE, "push", Type.VOID,
  1854. new Type[] { objectArrayType }, Constants.INVOKEVIRTUAL));
  1855. }
  1856. }
  1857. InstructionList testInstructions = munger.getTestInstructions(this, entrySuccessInstructions.getStart(),
  1858. range.getRealStart(), entrySuccessInstructions.getStart());
  1859. entryInstructions.append(testInstructions);
  1860. entryInstructions.append(entrySuccessInstructions);
  1861. }
  1862. BcelAdvice exitAdvice = new BcelAdvice(null, null, null, 0, 0, 0, null, munger.getConcreteAspect()) {
  1863. @Override
  1864. public InstructionList getAdviceInstructions(BcelShadow s, BcelVar extraArgVar, InstructionHandle ifNoAdvice) {
  1865. InstructionList exitInstructions = new InstructionList();
  1866. if (munger.hasDynamicTests()) {
  1867. testResult.appendLoad(exitInstructions, fact);
  1868. exitInstructions.append(InstructionFactory.createBranchInstruction(Constants.IFEQ, ifNoAdvice));
  1869. }
  1870. exitInstructions.append(Utility.createGet(fact, cflowField));
  1871. if (munger.getKind() != AdviceKind.PerCflowEntry && munger.getKind() != AdviceKind.PerCflowBelowEntry
  1872. && munger.getExposedStateAsBcelVars(false).length == 0) {
  1873. exitInstructions.append(fact.createInvoke(NameMangler.CFLOW_COUNTER_TYPE, "dec", Type.VOID, new Type[] {},
  1874. Constants.INVOKEVIRTUAL));
  1875. } else {
  1876. exitInstructions.append(fact.createInvoke(NameMangler.CFLOW_STACK_TYPE, "pop", Type.VOID, new Type[] {},
  1877. Constants.INVOKEVIRTUAL));
  1878. }
  1879. return exitInstructions;
  1880. }
  1881. };
  1882. // if (getKind() == PreInitialization) {
  1883. // weaveAfterReturning(exitAdvice);
  1884. // }
  1885. // else {
  1886. weaveAfter(exitAdvice);
  1887. // }
  1888. range.insert(entryInstructions, Range.InsideBefore);
  1889. }
  1890. /*
  1891. * Implementation notes:
  1892. *
  1893. * AroundInline still extracts the instructions of the original shadow into an extracted method. This allows inlining of even
  1894. * that advice that doesn't call proceed or calls proceed more than once.
  1895. *
  1896. * It extracts the instructions of the original shadow into a method.
  1897. *
  1898. * Then it extracts the instructions of the advice into a new method defined on this enclosing class. This new method can then
  1899. * be specialized as below.
  1900. *
  1901. * Then it searches in the instructions of the advice for any call to the proceed method.
  1902. *
  1903. * At such a call, there is stuff on the stack representing the arguments to proceed. Pop these into the frame.
  1904. *
  1905. * Now build the stack for the call to the extracted method, taking values either from the join point state or from the new
  1906. * frame locs from proceed. Now call the extracted method. The right return value should be on the stack, so no cast is
  1907. * necessary.
  1908. *
  1909. * If only one call to proceed is made, we can re-inline the original shadow. We are not doing that presently.
  1910. *
  1911. * 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.
  1912. * method-execution, then the new method for the advice can also be re-lined. We are not doing that presently.
  1913. */
  1914. public void weaveAroundInline(BcelAdvice munger, boolean hasDynamicTest) {
  1915. // !!! THIS BLOCK OF CODE SHOULD BE IN A METHOD CALLED weaveAround(...);
  1916. Member mungerSig = munger.getSignature();
  1917. // Member originalSig = mungerSig; // If mungerSig is on a parameterized type, originalSig is the member on the generic type
  1918. if (mungerSig instanceof ResolvedMember) {
  1919. ResolvedMember rm = (ResolvedMember) mungerSig;
  1920. if (rm.hasBackingGenericMember()) {
  1921. mungerSig = rm.getBackingGenericMember();
  1922. }
  1923. }
  1924. ResolvedType declaringAspectType = world.resolve(mungerSig.getDeclaringType(), true);
  1925. if (declaringAspectType.isMissing()) {
  1926. world.getLint().cantFindType.signal(
  1927. new String[] { WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE,
  1928. declaringAspectType.getClassName()) }, getSourceLocation(),
  1929. new ISourceLocation[] { munger.getSourceLocation() });
  1930. }
  1931. // ??? might want some checks here to give better errors
  1932. ResolvedType rt = (declaringAspectType.isParameterizedType() ? declaringAspectType.getGenericType() : declaringAspectType);
  1933. BcelObjectType ot = BcelWorld.getBcelObjectType(rt);
  1934. LazyMethodGen adviceMethod = ot.getLazyClassGen().getLazyMethodGen(mungerSig);
  1935. if (!adviceMethod.getCanInline()) {
  1936. weaveAroundClosure(munger, hasDynamicTest);
  1937. return;
  1938. }
  1939. // specific test for @AJ proceedInInners
  1940. if (isAnnotationStylePassingProceedingJoinPointOutOfAdvice(munger, hasDynamicTest, adviceMethod)) {
  1941. return;
  1942. }
  1943. // We can't inline around methods if they have around advice on them, this
  1944. // is because the weaving will extract the body and hence the proceed call.
  1945. // TODO should consider optimizations to recognize simple cases that don't require body extraction
  1946. enclosingMethod.setCanInline(false);
  1947. LazyClassGen shadowClass = getEnclosingClass();
  1948. // Extract the shadow into a new method. For example:
  1949. // "private static final void method_aroundBody0(M, M, String, org.aspectj.lang.JoinPoint)"
  1950. // Parameters are: this if there is one, target if there is one and its different to this, then original arguments
  1951. // at the shadow, then tjp
  1952. String extractedShadowMethodName = NameMangler.aroundShadowMethodName(getSignature(), shadowClass.getNewGeneratedNameTag());
  1953. List<String> parameterNames = new ArrayList<String>();
  1954. boolean shadowClassIsInterface = shadowClass.isInterface();
  1955. LazyMethodGen extractedShadowMethod = extractShadowInstructionsIntoNewMethod(extractedShadowMethodName,
  1956. shadowClassIsInterface?Modifier.PUBLIC:Modifier.PRIVATE,
  1957. munger.getSourceLocation(), parameterNames,shadowClassIsInterface);
  1958. List<BcelVar> argsToCallLocalAdviceMethodWith = new ArrayList<BcelVar>();
  1959. List<BcelVar> proceedVarList = new ArrayList<BcelVar>();
  1960. int extraParamOffset = 0;
  1961. // Create the extra parameters that are needed for passing to proceed
  1962. // This code is very similar to that found in makeCallToCallback and should
  1963. // be rationalized in the future
  1964. if (thisVar != null) {
  1965. argsToCallLocalAdviceMethodWith.add(thisVar);
  1966. proceedVarList.add(new BcelVar(thisVar.getType(), extraParamOffset));
  1967. extraParamOffset += thisVar.getType().getSize();
  1968. }
  1969. if (targetVar != null && targetVar != thisVar) {
  1970. argsToCallLocalAdviceMethodWith.add(targetVar);
  1971. proceedVarList.add(new BcelVar(targetVar.getType(), extraParamOffset));
  1972. extraParamOffset += targetVar.getType().getSize();
  1973. }
  1974. for (int i = 0, len = getArgCount(); i < len; i++) {
  1975. argsToCallLocalAdviceMethodWith.add(argVars[i]);
  1976. proceedVarList.add(new BcelVar(argVars[i].getType(), extraParamOffset));
  1977. extraParamOffset += argVars[i].getType().getSize();
  1978. }
  1979. if (thisJoinPointVar != null) {
  1980. argsToCallLocalAdviceMethodWith.add(thisJoinPointVar);
  1981. proceedVarList.add(new BcelVar(thisJoinPointVar.getType(), extraParamOffset));
  1982. extraParamOffset += thisJoinPointVar.getType().getSize();
  1983. }
  1984. // We use the munger signature here because it allows for any parameterization of the mungers pointcut that
  1985. // 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
  1986. // then here the munger signature will have 'Foo' as an argument in it whilst the adviceMethod argument type will be
  1987. // 'Object' - since it represents the advice method in the superaspect which uses the erasure of the type variable p(Object
  1988. // t) - see pr174449.
  1989. Type[] adviceParameterTypes = BcelWorld.makeBcelTypes(munger.getSignature().getParameterTypes());
  1990. // forces initialization ... dont like this but seems to be required for some tests to pass, I think that means there
  1991. // is a LazyMethodGen method that is not correctly setup to call initialize() when it is invoked - but I dont have
  1992. // time right now to discover which
  1993. adviceMethod.getArgumentTypes();
  1994. Type[] extractedMethodParameterTypes = extractedShadowMethod.getArgumentTypes();
  1995. Type[] parameterTypes = new Type[extractedMethodParameterTypes.length + adviceParameterTypes.length + 1];
  1996. int parameterIndex = 0;
  1997. System.arraycopy(extractedMethodParameterTypes, 0, parameterTypes, parameterIndex, extractedMethodParameterTypes.length);
  1998. parameterIndex += extractedMethodParameterTypes.length;
  1999. parameterTypes[parameterIndex++] = BcelWorld.makeBcelType(adviceMethod.getEnclosingClass().getType());
  2000. System.arraycopy(adviceParameterTypes, 0, parameterTypes, parameterIndex, adviceParameterTypes.length);
  2001. // Extract the advice into a new method. This will go in the same type as the shadow
  2002. // name will be something like foo_aroundBody1$advice
  2003. String localAdviceMethodName = NameMangler.aroundAdviceMethodName(getSignature(), shadowClass.getNewGeneratedNameTag());
  2004. int localAdviceMethodModifiers = Modifier.PRIVATE | (world.useFinal() & !shadowClassIsInterface ? Modifier.FINAL : 0) | Modifier.STATIC;
  2005. LazyMethodGen localAdviceMethod = new LazyMethodGen(localAdviceMethodModifiers, BcelWorld.makeBcelType(mungerSig.getReturnType()), localAdviceMethodName, parameterTypes,
  2006. NoDeclaredExceptions, shadowClass);
  2007. // Doesnt work properly, so leave it out:
  2008. // String aspectFilename = adviceMethod.getEnclosingClass().getInternalFileName();
  2009. // String shadowFilename = shadowClass.getInternalFileName();
  2010. // if (!aspectFilename.equals(shadowFilename)) {
  2011. // localAdviceMethod.fromFilename = aspectFilename;
  2012. // shadowClass.addInlinedSourceFileInfo(aspectFilename, adviceMethod.highestLineNumber);
  2013. // }
  2014. shadowClass.addMethodGen(localAdviceMethod);
  2015. // create a map that will move all slots in advice method forward by extraParamOffset
  2016. // in order to make room for the new proceed-required arguments that are added at
  2017. // the beginning of the parameter list
  2018. int nVars = adviceMethod.getMaxLocals() + extraParamOffset;
  2019. IntMap varMap = IntMap.idMap(nVars);
  2020. for (int i = extraParamOffset; i < nVars; i++) {
  2021. varMap.put(i - extraParamOffset, i);
  2022. }
  2023. final InstructionFactory fact = getFactory();
  2024. localAdviceMethod.getBody().insert(
  2025. BcelClassWeaver.genInlineInstructions(adviceMethod, localAdviceMethod, varMap, fact, true));
  2026. localAdviceMethod.setMaxLocals(nVars);
  2027. // the shadow is now empty. First, create a correct call
  2028. // to the around advice. This includes both the call (which may involve
  2029. // value conversion of the advice arguments) and the return
  2030. // (which may involve value conversion of the return value). Right now
  2031. // we push a null for the unused closure. It's sad, but there it is.
  2032. InstructionList advice = new InstructionList();
  2033. // InstructionHandle adviceMethodInvocation;
  2034. {
  2035. for (Iterator<BcelVar> i = argsToCallLocalAdviceMethodWith.iterator(); i.hasNext();) {
  2036. BcelVar var = i.next();
  2037. var.appendLoad(advice, fact);
  2038. }
  2039. // ??? we don't actually need to push NULL for the closure if we take care
  2040. boolean isAnnoStyleConcreteAspect = munger.getConcreteAspect().isAnnotationStyleAspect();
  2041. boolean isAnnoStyleDeclaringAspect = munger.getDeclaringAspect() != null ? munger.getDeclaringAspect().resolve(world)
  2042. .isAnnotationStyleAspect() : false;
  2043. InstructionList iList = null;
  2044. if (isAnnoStyleConcreteAspect && isAnnoStyleDeclaringAspect) {
  2045. iList = this.loadThisJoinPoint();
  2046. iList.append(Utility.createConversion(getFactory(), LazyClassGen.tjpType, LazyClassGen.proceedingTjpType));
  2047. } else {
  2048. iList = new InstructionList(InstructionConstants.ACONST_NULL);
  2049. }
  2050. advice.append(munger.getAdviceArgSetup(this, null, iList));
  2051. // adviceMethodInvocation =
  2052. advice.append(Utility.createInvoke(fact, localAdviceMethod)); // (fact, getWorld(), munger.getSignature()));
  2053. advice.append(Utility.createConversion(getFactory(), BcelWorld.makeBcelType(mungerSig.getReturnType()),
  2054. extractedShadowMethod.getReturnType(), world.isInJava5Mode()));
  2055. if (!isFallsThrough()) {
  2056. advice.append(InstructionFactory.createReturn(extractedShadowMethod.getReturnType()));
  2057. }
  2058. }
  2059. // now, situate the call inside the possible dynamic tests,
  2060. // and actually add the whole mess to the shadow
  2061. if (!hasDynamicTest) {
  2062. range.append(advice);
  2063. } else {
  2064. InstructionList afterThingie = new InstructionList(InstructionConstants.NOP);
  2065. InstructionList callback = makeCallToCallback(extractedShadowMethod);
  2066. if (terminatesWithReturn()) {
  2067. callback.append(InstructionFactory.createReturn(extractedShadowMethod.getReturnType()));
  2068. } else {
  2069. // InstructionHandle endNop = range.insert(fact.NOP, Range.InsideAfter);
  2070. advice.append(InstructionFactory.createBranchInstruction(Constants.GOTO, afterThingie.getStart()));
  2071. }
  2072. range.append(munger.getTestInstructions(this, advice.getStart(), callback.getStart(), advice.getStart()));
  2073. range.append(advice);
  2074. range.append(callback);
  2075. range.append(afterThingie);
  2076. }
  2077. // now search through the advice, looking for a call to PROCEED.
  2078. // Then we replace the call to proceed with some argument setup, and a
  2079. // call to the extracted method.
  2080. // inlining support for code style aspects
  2081. if (!munger.getDeclaringType().isAnnotationStyleAspect()) {
  2082. String proceedName = NameMangler.proceedMethodName(munger.getSignature().getName());
  2083. InstructionHandle curr = localAdviceMethod.getBody().getStart();
  2084. InstructionHandle end = localAdviceMethod.getBody().getEnd();
  2085. ConstantPool cpg = localAdviceMethod.getEnclosingClass().getConstantPool();
  2086. while (curr != end) {
  2087. InstructionHandle next = curr.getNext();
  2088. Instruction inst = curr.getInstruction();
  2089. if ((inst.opcode == Constants.INVOKESTATIC) && proceedName.equals(((InvokeInstruction) inst).getMethodName(cpg))) {
  2090. localAdviceMethod.getBody().append(curr,
  2091. getRedoneProceedCall(fact, extractedShadowMethod, munger, localAdviceMethod, proceedVarList));
  2092. Utility.deleteInstruction(curr, localAdviceMethod);
  2093. }
  2094. curr = next;
  2095. }
  2096. // and that's it.
  2097. } else {
  2098. // ATAJ inlining support for @AJ aspects
  2099. // [TODO document @AJ code rule: don't manipulate 2 jps proceed at the same time.. in an advice body]
  2100. InstructionHandle curr = localAdviceMethod.getBody().getStart();
  2101. InstructionHandle end = localAdviceMethod.getBody().getEnd();
  2102. ConstantPool cpg = localAdviceMethod.getEnclosingClass().getConstantPool();
  2103. while (curr != end) {
  2104. InstructionHandle next = curr.getNext();
  2105. Instruction inst = curr.getInstruction();
  2106. if ((inst instanceof INVOKEINTERFACE) && "proceed".equals(((INVOKEINTERFACE) inst).getMethodName(cpg))) {
  2107. final boolean isProceedWithArgs;
  2108. if (((INVOKEINTERFACE) inst).getArgumentTypes(cpg).length == 1) {
  2109. // proceed with args as a boxed Object[]
  2110. isProceedWithArgs = true;
  2111. } else {
  2112. isProceedWithArgs = false;
  2113. }
  2114. InstructionList insteadProceedIl = getRedoneProceedCallForAnnotationStyle(fact, extractedShadowMethod, munger,
  2115. localAdviceMethod, proceedVarList, isProceedWithArgs);
  2116. localAdviceMethod.getBody().append(curr, insteadProceedIl);
  2117. Utility.deleteInstruction(curr, localAdviceMethod);
  2118. }
  2119. curr = next;
  2120. }
  2121. }
  2122. // if (parameterNames.size() == 0) {
  2123. // On return we have inserted the advice body into the local advice method. We have remapped all the local variables
  2124. // that were referenced in the advice as we did the copy, and so the local variable table for localAdviceMethod is
  2125. // now lacking any information about all the initial variables.
  2126. InstructionHandle start = localAdviceMethod.getBody().getStart();
  2127. InstructionHandle end = localAdviceMethod.getBody().getEnd();
  2128. // Find the real start and end
  2129. while (start.getInstruction().opcode == Constants.IMPDEP1) {
  2130. start = start.getNext();
  2131. }
  2132. while (end.getInstruction().opcode == Constants.IMPDEP1) {
  2133. end = end.getPrev();
  2134. }
  2135. Type[] args = localAdviceMethod.getArgumentTypes();
  2136. int argNumber = 0;
  2137. for (int slot = 0; slot < extraParamOffset; argNumber++) { // slot will increase by the argument size each time
  2138. String argumentName = null;
  2139. if (argNumber >= args.length || parameterNames.size() == 0 || argNumber >= parameterNames.size()) {
  2140. // this should be unnecessary as I think all known joinpoints and helper methods
  2141. // propagate the parameter names around correctly - but just in case let us do this
  2142. // rather than fail. If a bug is raised reporting unknown as a local variable name
  2143. // then investigate the joinpoint giving rise to the ResolvedMember and why it has
  2144. // no parameter names specified
  2145. argumentName = new StringBuffer("unknown").append(argNumber).toString();
  2146. } else {
  2147. argumentName = parameterNames.get(argNumber);
  2148. }
  2149. String argumentSignature = args[argNumber].getSignature();
  2150. LocalVariableTag lvt = new LocalVariableTag(argumentSignature, argumentName, slot, 0);
  2151. start.addTargeter(lvt);
  2152. end.addTargeter(lvt);
  2153. slot += args[argNumber].getSize();
  2154. }
  2155. }
  2156. /**
  2157. * Check if the advice method passes a pjp parameter out via an invoke instruction - if so we can't risk inlining.
  2158. */
  2159. private boolean isAnnotationStylePassingProceedingJoinPointOutOfAdvice(BcelAdvice munger, boolean hasDynamicTest,
  2160. LazyMethodGen adviceMethod) {
  2161. if (munger.getConcreteAspect().isAnnotationStyleAspect()) {
  2162. // if we can't find one proceed() we suspect that the call
  2163. // is happening in an inner class so we don't inline it.
  2164. // Note: for code style, this is done at Aspect compilation time.
  2165. boolean canSeeProceedPassedToOther = false;
  2166. InstructionHandle curr = adviceMethod.getBody().getStart();
  2167. InstructionHandle end = adviceMethod.getBody().getEnd();
  2168. ConstantPool cpg = adviceMethod.getEnclosingClass().getConstantPool();
  2169. while (curr != end) {
  2170. InstructionHandle next = curr.getNext();
  2171. Instruction inst = curr.getInstruction();
  2172. if ((inst instanceof InvokeInstruction)
  2173. && ((InvokeInstruction) inst).getSignature(cpg).indexOf("Lorg/aspectj/lang/ProceedingJoinPoint;") > 0) {
  2174. // we may want to refine to exclude stuff returning jp ?
  2175. // does code style skip inline if i write dump(thisJoinPoint) ?
  2176. canSeeProceedPassedToOther = true;// we see one pjp passed around - dangerous
  2177. break;
  2178. }
  2179. curr = next;
  2180. }
  2181. if (canSeeProceedPassedToOther) {
  2182. // remember this decision to avoid re-analysis
  2183. adviceMethod.setCanInline(false);
  2184. weaveAroundClosure(munger, hasDynamicTest);
  2185. return true;
  2186. }
  2187. }
  2188. return false;
  2189. }
  2190. private InstructionList getRedoneProceedCall(InstructionFactory fact, LazyMethodGen callbackMethod, BcelAdvice munger,
  2191. LazyMethodGen localAdviceMethod, List<BcelVar> argVarList) {
  2192. InstructionList ret = new InstructionList();
  2193. // we have on stack all the arguments for the ADVICE call.
  2194. // we have in frame somewhere all the arguments for the non-advice call.
  2195. BcelVar[] adviceVars = munger.getExposedStateAsBcelVars(true);
  2196. IntMap proceedMap = makeProceedArgumentMap(adviceVars);
  2197. // System.out.println(proceedMap + " for " + this);
  2198. // System.out.println(argVarList);
  2199. ResolvedType[] proceedParamTypes = world.resolve(munger.getSignature().getParameterTypes());
  2200. // remove this*JoinPoint* as arguments to proceed
  2201. if (munger.getBaseParameterCount() + 1 < proceedParamTypes.length) {
  2202. int len = munger.getBaseParameterCount() + 1;
  2203. ResolvedType[] newTypes = new ResolvedType[len];
  2204. System.arraycopy(proceedParamTypes, 0, newTypes, 0, len);
  2205. proceedParamTypes = newTypes;
  2206. }
  2207. // System.out.println("stateTypes: " + Arrays.asList(stateTypes));
  2208. BcelVar[] proceedVars = Utility.pushAndReturnArrayOfVars(proceedParamTypes, ret, fact, localAdviceMethod);
  2209. Type[] stateTypes = callbackMethod.getArgumentTypes();
  2210. // System.out.println("stateTypes: " + Arrays.asList(stateTypes));
  2211. for (int i = 0, len = stateTypes.length; i < len; i++) {
  2212. Type stateType = stateTypes[i];
  2213. ResolvedType stateTypeX = BcelWorld.fromBcel(stateType).resolve(world);
  2214. if (proceedMap.hasKey(i)) {
  2215. // throw new RuntimeException("unimplemented");
  2216. proceedVars[proceedMap.get(i)].appendLoadAndConvert(ret, fact, stateTypeX);
  2217. } else {
  2218. argVarList.get(i).appendLoad(ret, fact);
  2219. }
  2220. }
  2221. ret.append(Utility.createInvoke(fact, callbackMethod));
  2222. ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(),
  2223. BcelWorld.makeBcelType(munger.getSignature().getReturnType()), world.isInJava5Mode()));
  2224. return ret;
  2225. }
  2226. // private static boolean bindsThisOrTarget(Pointcut pointcut) {
  2227. // ThisTargetFinder visitor = new ThisTargetFinder();
  2228. // pointcut.accept(visitor, null);
  2229. // return visitor.bindsThisOrTarget;
  2230. // }
  2231. // private static class ThisTargetFinder extends IdentityPointcutVisitor {
  2232. // boolean bindsThisOrTarget = false;
  2233. //
  2234. // public Object visit(ThisOrTargetPointcut node, Object data) {
  2235. // if (node.isBinding()) {
  2236. // bindsThisOrTarget = true;
  2237. // }
  2238. // return node;
  2239. // }
  2240. //
  2241. // public Object visit(AndPointcut node, Object data) {
  2242. // if (!bindsThisOrTarget) node.getLeft().accept(this, data);
  2243. // if (!bindsThisOrTarget) node.getRight().accept(this, data);
  2244. // return node;
  2245. // }
  2246. //
  2247. // public Object visit(NotPointcut node, Object data) {
  2248. // if (!bindsThisOrTarget) node.getNegatedPointcut().accept(this, data);
  2249. // return node;
  2250. // }
  2251. //
  2252. // public Object visit(OrPointcut node, Object data) {
  2253. // if (!bindsThisOrTarget) node.getLeft().accept(this, data);
  2254. // if (!bindsThisOrTarget) node.getRight().accept(this, data);
  2255. // return node;
  2256. // }
  2257. // }
  2258. /**
  2259. * Annotation style handling for inlining.
  2260. *
  2261. * Note: The proceedingjoinpoint is already on the stack (since the user was calling pjp.proceed(...)
  2262. *
  2263. * The proceed map is ignored (in terms of argument repositioning) since we have a fixed expected format for annotation style.
  2264. * The aim here is to change the proceed() call into a call to the xxx_aroundBody0 method.
  2265. *
  2266. *
  2267. */
  2268. private InstructionList getRedoneProceedCallForAnnotationStyle(InstructionFactory fact, LazyMethodGen callbackMethod,
  2269. BcelAdvice munger, LazyMethodGen localAdviceMethod, List<BcelVar> argVarList, boolean isProceedWithArgs) {
  2270. InstructionList ret = new InstructionList();
  2271. // store the Object[] array on stack if proceed with args
  2272. if (isProceedWithArgs) {
  2273. // STORE the Object[] into a local variable
  2274. Type objectArrayType = Type.OBJECT_ARRAY;
  2275. int theObjectArrayLocalNumber = localAdviceMethod.allocateLocal(objectArrayType);
  2276. ret.append(InstructionFactory.createStore(objectArrayType, theObjectArrayLocalNumber));
  2277. // STORE the ProceedingJoinPoint instance into a local variable
  2278. Type proceedingJpType = Type.getType("Lorg/aspectj/lang/ProceedingJoinPoint;");
  2279. int pjpLocalNumber = localAdviceMethod.allocateLocal(proceedingJpType);
  2280. ret.append(InstructionFactory.createStore(proceedingJpType, pjpLocalNumber));
  2281. // Aim here initially is to determine whether the user will have provided a new
  2282. // this/target in the object array and consume them if they have, leaving us the rest of
  2283. // the arguments to process as regular arguments to the invocation at the original join point
  2284. boolean pointcutBindsThis = bindsThis(munger);
  2285. boolean pointcutBindsTarget = bindsTarget(munger);
  2286. boolean targetIsSameAsThis = getKind().isTargetSameAsThis();
  2287. int nextArgumentToProvideForCallback = 0;
  2288. if (hasThis()) {
  2289. if (!(pointcutBindsTarget && targetIsSameAsThis)) {
  2290. if (pointcutBindsThis) {
  2291. // they have supplied new this as first entry in object array, consume it
  2292. ret.append(InstructionFactory.createLoad(objectArrayType, theObjectArrayLocalNumber));
  2293. ret.append(Utility.createConstant(fact, 0));
  2294. ret.append(InstructionFactory.createArrayLoad(Type.OBJECT));
  2295. ret.append(Utility.createConversion(fact, Type.OBJECT, callbackMethod.getArgumentTypes()[0]));
  2296. } else {
  2297. // use local variable 0
  2298. ret.append(InstructionFactory.createALOAD(0));
  2299. }
  2300. nextArgumentToProvideForCallback++;
  2301. }
  2302. }
  2303. if (hasTarget()) {
  2304. if (pointcutBindsTarget) {
  2305. if (getKind().isTargetSameAsThis()) {
  2306. ret.append(InstructionFactory.createLoad(objectArrayType, theObjectArrayLocalNumber));
  2307. ret.append(Utility.createConstant(fact, pointcutBindsThis ? 1 : 0));
  2308. ret.append(InstructionFactory.createArrayLoad(Type.OBJECT));
  2309. ret.append(Utility.createConversion(fact, Type.OBJECT, callbackMethod.getArgumentTypes()[0]));
  2310. } else {
  2311. int position = (hasThis() && pointcutBindsThis)? 1 : 0;
  2312. ret.append(InstructionFactory.createLoad(objectArrayType, theObjectArrayLocalNumber));
  2313. ret.append(Utility.createConstant(fact, position));
  2314. ret.append(InstructionFactory.createArrayLoad(Type.OBJECT));
  2315. ret.append(Utility.createConversion(fact, Type.OBJECT, callbackMethod.getArgumentTypes()[nextArgumentToProvideForCallback]));
  2316. }
  2317. nextArgumentToProvideForCallback++;
  2318. } else {
  2319. if (getKind().isTargetSameAsThis()) {
  2320. // ret.append(new ALOAD(0));
  2321. } else {
  2322. ret.append(InstructionFactory.createLoad(localAdviceMethod.getArgumentTypes()[0], hasThis() ? 1 : 0));
  2323. nextArgumentToProvideForCallback++;
  2324. }
  2325. }
  2326. }
  2327. // Where to start in the object array in order to pick up arguments
  2328. int indexIntoObjectArrayForArguments = (pointcutBindsThis ? 1 : 0) + (pointcutBindsTarget ? 1 : 0);
  2329. int len = callbackMethod.getArgumentTypes().length;
  2330. for (int i = nextArgumentToProvideForCallback; i < len; i++) {
  2331. Type stateType = callbackMethod.getArgumentTypes()[i];
  2332. BcelWorld.fromBcel(stateType).resolve(world);
  2333. if ("Lorg/aspectj/lang/JoinPoint;".equals(stateType.getSignature())) {
  2334. ret.append(new InstructionLV(Constants.ALOAD, pjpLocalNumber));
  2335. } else {
  2336. ret.append(InstructionFactory.createLoad(objectArrayType, theObjectArrayLocalNumber));
  2337. ret.append(Utility
  2338. .createConstant(fact, i - nextArgumentToProvideForCallback + indexIntoObjectArrayForArguments));
  2339. ret.append(InstructionFactory.createArrayLoad(Type.OBJECT));
  2340. ret.append(Utility.createConversion(fact, Type.OBJECT, stateType));
  2341. }
  2342. }
  2343. } else {
  2344. Type proceedingJpType = Type.getType("Lorg/aspectj/lang/ProceedingJoinPoint;");
  2345. int localJp = localAdviceMethod.allocateLocal(proceedingJpType);
  2346. ret.append(InstructionFactory.createStore(proceedingJpType, localJp));
  2347. int idx = 0;
  2348. for (int i = 0, len = callbackMethod.getArgumentTypes().length; i < len; i++) {
  2349. Type stateType = callbackMethod.getArgumentTypes()[i];
  2350. /* ResolvedType stateTypeX = */
  2351. BcelWorld.fromBcel(stateType).resolve(world);
  2352. if ("Lorg/aspectj/lang/JoinPoint;".equals(stateType.getSignature())) {
  2353. ret.append(InstructionFactory.createALOAD(localJp));// from localAdvice signature
  2354. // } else if ("Lorg/aspectj/lang/ProceedingJoinPoint;".equals(stateType.getSignature())) {
  2355. // //FIXME ALEX?
  2356. // ret.append(new ALOAD(localJp));// from localAdvice signature
  2357. // // ret.append(fact.createCheckCast(
  2358. // // (ReferenceType) BcelWorld.makeBcelType(stateTypeX)
  2359. // // ));
  2360. // // cast ?
  2361. //
  2362. idx++;
  2363. } else {
  2364. ret.append(InstructionFactory.createLoad(stateType, idx));
  2365. idx += stateType.getSize();
  2366. }
  2367. }
  2368. }
  2369. // do the callback invoke
  2370. ret.append(Utility.createInvoke(fact, callbackMethod));
  2371. // box it again. Handles cases where around advice does return something else than Object
  2372. if (!UnresolvedType.OBJECT.equals(munger.getSignature().getReturnType())) {
  2373. ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(), Type.OBJECT));
  2374. }
  2375. ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(),
  2376. BcelWorld.makeBcelType(munger.getSignature().getReturnType()), world.isInJava5Mode()));
  2377. return ret;
  2378. //
  2379. //
  2380. //
  2381. // if (proceedMap.hasKey(i)) {
  2382. // ret.append(new ALOAD(i));
  2383. // //throw new RuntimeException("unimplemented");
  2384. // //proceedVars[proceedMap.get(i)].appendLoadAndConvert(ret, fact, stateTypeX);
  2385. // } else {
  2386. // //((BcelVar) argVarList.get(i)).appendLoad(ret, fact);
  2387. // //ret.append(new ALOAD(i));
  2388. // if ("Lorg/aspectj/lang/JoinPoint;".equals(stateType.getSignature())) {
  2389. // ret.append(new ALOAD(i));
  2390. // } else {
  2391. // ret.append(new ALOAD(i));
  2392. // }
  2393. // }
  2394. // }
  2395. //
  2396. // ret.append(Utility.createInvoke(fact, callbackMethod));
  2397. // ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(),
  2398. // BcelWorld.makeBcelType(munger.getSignature().getReturnType())));
  2399. //
  2400. // //ret.append(new ACONST_NULL());//will be POPed
  2401. // if (true) return ret;
  2402. //
  2403. //
  2404. //
  2405. // // we have on stack all the arguments for the ADVICE call.
  2406. // // we have in frame somewhere all the arguments for the non-advice call.
  2407. //
  2408. // BcelVar[] adviceVars = munger.getExposedStateAsBcelVars();
  2409. // IntMap proceedMap = makeProceedArgumentMap(adviceVars);
  2410. //
  2411. // System.out.println(proceedMap + " for " + this);
  2412. // System.out.println(argVarList);
  2413. //
  2414. // ResolvedType[] proceedParamTypes =
  2415. // world.resolve(munger.getSignature().getParameterTypes());
  2416. // // remove this*JoinPoint* as arguments to proceed
  2417. // if (munger.getBaseParameterCount()+1 < proceedParamTypes.length) {
  2418. // int len = munger.getBaseParameterCount()+1;
  2419. // ResolvedType[] newTypes = new ResolvedType[len];
  2420. // System.arraycopy(proceedParamTypes, 0, newTypes, 0, len);
  2421. // proceedParamTypes = newTypes;
  2422. // }
  2423. //
  2424. // //System.out.println("stateTypes: " + Arrays.asList(stateTypes));
  2425. // BcelVar[] proceedVars =
  2426. // Utility.pushAndReturnArrayOfVars(proceedParamTypes, ret, fact, localAdviceMethod);
  2427. //
  2428. // Type[] stateTypes = callbackMethod.getArgumentTypes();
  2429. // // System.out.println("stateTypes: " + Arrays.asList(stateTypes));
  2430. //
  2431. // for (int i=0, len=stateTypes.length; i < len; i++) {
  2432. // Type stateType = stateTypes[i];
  2433. // ResolvedType stateTypeX = BcelWorld.fromBcel(stateType).resolve(world);
  2434. // if (proceedMap.hasKey(i)) {
  2435. // //throw new RuntimeException("unimplemented");
  2436. // proceedVars[proceedMap.get(i)].appendLoadAndConvert(ret, fact, stateTypeX);
  2437. // } else {
  2438. // ((BcelVar) argVarList.get(i)).appendLoad(ret, fact);
  2439. // }
  2440. // }
  2441. //
  2442. // ret.append(Utility.createInvoke(fact, callbackMethod));
  2443. // ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(),
  2444. // BcelWorld.makeBcelType(munger.getSignature().getReturnType())));
  2445. // return ret;
  2446. }
  2447. private boolean bindsThis(BcelAdvice munger) {
  2448. UsesThisVisitor utv = new UsesThisVisitor();
  2449. munger.getPointcut().accept(utv, null);
  2450. return utv.usesThis;
  2451. }
  2452. private boolean bindsTarget(BcelAdvice munger) {
  2453. UsesTargetVisitor utv = new UsesTargetVisitor();
  2454. munger.getPointcut().accept(utv, null);
  2455. return utv.usesTarget;
  2456. }
  2457. private static class UsesThisVisitor extends AbstractPatternNodeVisitor {
  2458. boolean usesThis = false;
  2459. @Override
  2460. public Object visit(ThisOrTargetPointcut node, Object data) {
  2461. if (node.isThis() && node.isBinding()) {
  2462. usesThis = true;
  2463. }
  2464. return node;
  2465. }
  2466. @Override
  2467. public Object visit(AndPointcut node, Object data) {
  2468. if (!usesThis) {
  2469. node.getLeft().accept(this, data);
  2470. }
  2471. if (!usesThis) {
  2472. node.getRight().accept(this, data);
  2473. }
  2474. return node;
  2475. }
  2476. @Override
  2477. public Object visit(NotPointcut node, Object data) {
  2478. if (!usesThis) {
  2479. node.getNegatedPointcut().accept(this, data);
  2480. }
  2481. return node;
  2482. }
  2483. @Override
  2484. public Object visit(OrPointcut node, Object data) {
  2485. if (!usesThis) {
  2486. node.getLeft().accept(this, data);
  2487. }
  2488. if (!usesThis) {
  2489. node.getRight().accept(this, data);
  2490. }
  2491. return node;
  2492. }
  2493. }
  2494. private static class UsesTargetVisitor extends AbstractPatternNodeVisitor {
  2495. boolean usesTarget = false;
  2496. @Override
  2497. public Object visit(ThisOrTargetPointcut node, Object data) {
  2498. if (!node.isThis() && node.isBinding()) {
  2499. usesTarget = true;
  2500. }
  2501. return node;
  2502. }
  2503. @Override
  2504. public Object visit(AndPointcut node, Object data) {
  2505. if (!usesTarget) {
  2506. node.getLeft().accept(this, data);
  2507. }
  2508. if (!usesTarget) {
  2509. node.getRight().accept(this, data);
  2510. }
  2511. return node;
  2512. }
  2513. @Override
  2514. public Object visit(NotPointcut node, Object data) {
  2515. if (!usesTarget) {
  2516. node.getNegatedPointcut().accept(this, data);
  2517. }
  2518. return node;
  2519. }
  2520. @Override
  2521. public Object visit(OrPointcut node, Object data) {
  2522. if (!usesTarget) {
  2523. node.getLeft().accept(this, data);
  2524. }
  2525. if (!usesTarget) {
  2526. node.getRight().accept(this, data);
  2527. }
  2528. return node;
  2529. }
  2530. }
  2531. public void weaveAroundClosure(BcelAdvice munger, boolean hasDynamicTest) {
  2532. InstructionFactory fact = getFactory();
  2533. enclosingMethod.setCanInline(false);
  2534. int linenumber = getSourceLine();
  2535. // MOVE OUT ALL THE INSTRUCTIONS IN MY SHADOW INTO ANOTHER METHOD!
  2536. // callbackMethod will be something like: "static final void m_aroundBody0(I)"
  2537. boolean shadowClassIsInterface = getEnclosingClass().isInterface();
  2538. LazyMethodGen callbackMethod = extractShadowInstructionsIntoNewMethod(
  2539. NameMangler.aroundShadowMethodName(getSignature(), getEnclosingClass().getNewGeneratedNameTag()), shadowClassIsInterface?Modifier.PUBLIC:0,
  2540. munger.getSourceLocation(), new ArrayList<String>(),shadowClassIsInterface);
  2541. BcelVar[] adviceVars = munger.getExposedStateAsBcelVars(true);
  2542. String closureClassName = NameMangler.makeClosureClassName(getEnclosingClass().getType(), getEnclosingClass()
  2543. .getNewGeneratedNameTag());
  2544. Member constructorSig = new MemberImpl(Member.CONSTRUCTOR, UnresolvedType.forName(closureClassName), 0, "<init>",
  2545. "([Ljava/lang/Object;)V");
  2546. BcelVar closureHolder = null;
  2547. // This is not being used currently since getKind() == preinitializaiton
  2548. // cannot happen in around advice
  2549. if (getKind() == PreInitialization) {
  2550. closureHolder = genTempVar(AjcMemberMaker.AROUND_CLOSURE_TYPE);
  2551. }
  2552. InstructionList closureInstantiation = makeClosureInstantiation(constructorSig, closureHolder);
  2553. /* LazyMethodGen constructor = */
  2554. makeClosureClassAndReturnConstructor(closureClassName, callbackMethod, makeProceedArgumentMap(adviceVars));
  2555. InstructionList returnConversionCode;
  2556. if (getKind() == PreInitialization) {
  2557. returnConversionCode = new InstructionList();
  2558. BcelVar stateTempVar = genTempVar(UnresolvedType.OBJECTARRAY);
  2559. closureHolder.appendLoad(returnConversionCode, fact);
  2560. returnConversionCode.append(Utility.createInvoke(fact, world, AjcMemberMaker.aroundClosurePreInitializationGetter()));
  2561. stateTempVar.appendStore(returnConversionCode, fact);
  2562. Type[] stateTypes = getSuperConstructorParameterTypes();
  2563. returnConversionCode.append(InstructionConstants.ALOAD_0); // put "this" back on the stack
  2564. for (int i = 0, len = stateTypes.length; i < len; i++) {
  2565. UnresolvedType bcelTX = BcelWorld.fromBcel(stateTypes[i]);
  2566. ResolvedType stateRTX = world.resolve(bcelTX, true);
  2567. if (stateRTX.isMissing()) {
  2568. world.getLint().cantFindType.signal(
  2569. new String[] { WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE_PREINIT,
  2570. bcelTX.getClassName()) }, getSourceLocation(),
  2571. new ISourceLocation[] { munger.getSourceLocation() });
  2572. // IMessage msg = new Message(
  2573. // WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE_PREINIT,bcelTX.getClassName()),
  2574. // "",IMessage.ERROR,getSourceLocation(),null,
  2575. // new ISourceLocation[]{ munger.getSourceLocation()});
  2576. // world.getMessageHandler().handleMessage(msg);
  2577. }
  2578. stateTempVar.appendConvertableArrayLoad(returnConversionCode, fact, i, stateRTX);
  2579. }
  2580. } else {
  2581. // pr226201
  2582. Member mungerSignature = munger.getSignature();
  2583. if (munger.getSignature() instanceof ResolvedMember) {
  2584. if (((ResolvedMember) mungerSignature).hasBackingGenericMember()) {
  2585. mungerSignature = ((ResolvedMember) mungerSignature).getBackingGenericMember();
  2586. }
  2587. }
  2588. UnresolvedType returnType = mungerSignature.getReturnType();
  2589. returnConversionCode = Utility.createConversion(getFactory(), BcelWorld.makeBcelType(returnType),
  2590. callbackMethod.getReturnType(), world.isInJava5Mode());
  2591. if (!isFallsThrough()) {
  2592. returnConversionCode.append(InstructionFactory.createReturn(callbackMethod.getReturnType()));
  2593. }
  2594. }
  2595. // initialize the bit flags for this shadow
  2596. int bitflags = 0x000000;
  2597. if (getKind().isTargetSameAsThis()) {
  2598. bitflags |= 0x010000;
  2599. }
  2600. if (hasThis()) {
  2601. bitflags |= 0x001000;
  2602. }
  2603. if (bindsThis(munger)) {
  2604. bitflags |= 0x000100;
  2605. }
  2606. if (hasTarget()) {
  2607. bitflags |= 0x000010;
  2608. }
  2609. if (bindsTarget(munger)) {
  2610. bitflags |= 0x000001;
  2611. }
  2612. // ATAJ for @AJ aspect we need to link the closure with the joinpoint instance
  2613. if (munger.getConcreteAspect() != null && munger.getConcreteAspect().isAnnotationStyleAspect()
  2614. && munger.getDeclaringAspect() != null && munger.getDeclaringAspect().resolve(world).isAnnotationStyleAspect()) {
  2615. // stick the bitflags on the stack and call the variant of linkClosureAndJoinPoint that takes an int
  2616. closureInstantiation.append(fact.createConstant(Integer.valueOf(bitflags)));
  2617. closureInstantiation.append(Utility.createInvoke(getFactory(), getWorld(),
  2618. new MemberImpl(Member.METHOD, UnresolvedType.forName("org.aspectj.runtime.internal.AroundClosure"),
  2619. Modifier.PUBLIC, "linkClosureAndJoinPoint", String.format("%s%s", "(I)", "Lorg/aspectj/lang/ProceedingJoinPoint;"))));
  2620. }
  2621. InstructionList advice = new InstructionList();
  2622. advice.append(munger.getAdviceArgSetup(this, null, closureInstantiation));
  2623. // invoke the advice
  2624. advice.append(munger.getNonTestAdviceInstructions(this));
  2625. advice.append(returnConversionCode);
  2626. if (getKind() == Shadow.MethodExecution && linenumber > 0) {
  2627. advice.getStart().addTargeter(new LineNumberTag(linenumber));
  2628. }
  2629. if (!hasDynamicTest) {
  2630. range.append(advice);
  2631. } else {
  2632. InstructionList callback = makeCallToCallback(callbackMethod);
  2633. InstructionList postCallback = new InstructionList();
  2634. if (terminatesWithReturn()) {
  2635. callback.append(InstructionFactory.createReturn(callbackMethod.getReturnType()));
  2636. } else {
  2637. advice.append(InstructionFactory.createBranchInstruction(Constants.GOTO,
  2638. postCallback.append(InstructionConstants.NOP)));
  2639. }
  2640. range.append(munger.getTestInstructions(this, advice.getStart(), callback.getStart(), advice.getStart()));
  2641. range.append(advice);
  2642. range.append(callback);
  2643. range.append(postCallback);
  2644. }
  2645. }
  2646. // exposed for testing
  2647. InstructionList makeCallToCallback(LazyMethodGen callbackMethod) {
  2648. InstructionFactory fact = getFactory();
  2649. InstructionList callback = new InstructionList();
  2650. if (thisVar != null) {
  2651. callback.append(InstructionConstants.ALOAD_0);
  2652. }
  2653. if (targetVar != null && targetVar != thisVar) {
  2654. callback.append(BcelRenderer.renderExpr(fact, world, targetVar));
  2655. }
  2656. callback.append(BcelRenderer.renderExprs(fact, world, argVars));
  2657. // remember to render tjps
  2658. if (thisJoinPointVar != null) {
  2659. callback.append(BcelRenderer.renderExpr(fact, world, thisJoinPointVar));
  2660. }
  2661. callback.append(Utility.createInvoke(fact, callbackMethod));
  2662. return callback;
  2663. }
  2664. /** side-effect-free */
  2665. private InstructionList makeClosureInstantiation(Member constructor, BcelVar holder) {
  2666. // LazyMethodGen constructor) {
  2667. InstructionFactory fact = getFactory();
  2668. BcelVar arrayVar = genTempVar(UnresolvedType.OBJECTARRAY);
  2669. // final Type objectArrayType = new ArrayType(Type.OBJECT, 1);
  2670. final InstructionList il = new InstructionList();
  2671. int alen = getArgCount() + (thisVar == null ? 0 : 1) + ((targetVar != null && targetVar != thisVar) ? 1 : 0)
  2672. + (thisJoinPointVar == null ? 0 : 1);
  2673. il.append(Utility.createConstant(fact, alen));
  2674. il.append(fact.createNewArray(Type.OBJECT, (short) 1));
  2675. arrayVar.appendStore(il, fact);
  2676. int stateIndex = 0;
  2677. if (thisVar != null) {
  2678. arrayVar.appendConvertableArrayStore(il, fact, stateIndex, thisVar);
  2679. thisVar.setPositionInAroundState(stateIndex);
  2680. stateIndex++;
  2681. }
  2682. if (targetVar != null && targetVar != thisVar) {
  2683. arrayVar.appendConvertableArrayStore(il, fact, stateIndex, targetVar);
  2684. targetVar.setPositionInAroundState(stateIndex);
  2685. stateIndex++;
  2686. }
  2687. for (int i = 0, len = getArgCount(); i < len; i++) {
  2688. arrayVar.appendConvertableArrayStore(il, fact, stateIndex, argVars[i]);
  2689. argVars[i].setPositionInAroundState(stateIndex);
  2690. stateIndex++;
  2691. }
  2692. if (thisJoinPointVar != null) {
  2693. arrayVar.appendConvertableArrayStore(il, fact, stateIndex, thisJoinPointVar);
  2694. thisJoinPointVar.setPositionInAroundState(stateIndex);
  2695. stateIndex++;
  2696. }
  2697. il.append(fact.createNew(new ObjectType(constructor.getDeclaringType().getName())));
  2698. il.append(InstructionConstants.DUP);
  2699. arrayVar.appendLoad(il, fact);
  2700. il.append(Utility.createInvoke(fact, world, constructor));
  2701. if (getKind() == PreInitialization) {
  2702. il.append(InstructionConstants.DUP);
  2703. holder.appendStore(il, fact);
  2704. }
  2705. return il;
  2706. }
  2707. private IntMap makeProceedArgumentMap(BcelVar[] adviceArgs) {
  2708. // System.err.println("coming in with " + Arrays.asList(adviceArgs));
  2709. IntMap ret = new IntMap();
  2710. for (int i = 0, len = adviceArgs.length; i < len; i++) {
  2711. BcelVar v = adviceArgs[i];
  2712. if (v == null) {
  2713. continue; // XXX we don't know why this is required
  2714. }
  2715. int pos = v.getPositionInAroundState();
  2716. if (pos >= 0) { // need this test to avoid args bound via cflow
  2717. ret.put(pos, i);
  2718. }
  2719. }
  2720. // System.err.println("returning " + ret);
  2721. return ret;
  2722. }
  2723. /**
  2724. *
  2725. * @param callbackMethod the method we will call back to when our run method gets called.
  2726. * @param proceedMap A map from state position to proceed argument position. May be non covering on state position.
  2727. */
  2728. private LazyMethodGen makeClosureClassAndReturnConstructor(String closureClassName, LazyMethodGen callbackMethod,
  2729. IntMap proceedMap) {
  2730. String superClassName = "org.aspectj.runtime.internal.AroundClosure";
  2731. Type objectArrayType = new ArrayType(Type.OBJECT, 1);
  2732. LazyClassGen closureClass = new LazyClassGen(closureClassName, superClassName, getEnclosingClass().getFileName(),
  2733. Modifier.PUBLIC, new String[] {}, getWorld());
  2734. closureClass.setMajorMinor(getEnclosingClass().getMajor(), getEnclosingClass().getMinor());
  2735. InstructionFactory fact = new InstructionFactory(closureClass.getConstantPool());
  2736. // constructor
  2737. LazyMethodGen constructor = new LazyMethodGen(Modifier.PUBLIC, Type.VOID, "<init>", new Type[] { objectArrayType },
  2738. new String[] {}, closureClass);
  2739. InstructionList cbody = constructor.getBody();
  2740. cbody.append(InstructionFactory.createLoad(Type.OBJECT, 0));
  2741. cbody.append(InstructionFactory.createLoad(objectArrayType, 1));
  2742. cbody.append(fact
  2743. .createInvoke(superClassName, "<init>", Type.VOID, new Type[] { objectArrayType }, Constants.INVOKESPECIAL));
  2744. cbody.append(InstructionFactory.createReturn(Type.VOID));
  2745. closureClass.addMethodGen(constructor);
  2746. // Create the 'Object run(Object[])' method
  2747. LazyMethodGen runMethod = new LazyMethodGen(Modifier.PUBLIC, Type.OBJECT, "run", new Type[] { objectArrayType },
  2748. new String[] {}, closureClass);
  2749. InstructionList mbody = runMethod.getBody();
  2750. BcelVar proceedVar = new BcelVar(UnresolvedType.OBJECTARRAY.resolve(world), 1);
  2751. // int proceedVarIndex = 1;
  2752. BcelVar stateVar = new BcelVar(UnresolvedType.OBJECTARRAY.resolve(world), runMethod.allocateLocal(1));
  2753. // int stateVarIndex = runMethod.allocateLocal(1);
  2754. mbody.append(InstructionFactory.createThis());
  2755. mbody.append(fact.createGetField(superClassName, "state", objectArrayType));
  2756. mbody.append(stateVar.createStore(fact));
  2757. // mbody.append(fact.createStore(objectArrayType, stateVarIndex));
  2758. Type[] stateTypes = callbackMethod.getArgumentTypes();
  2759. for (int i = 0, len = stateTypes.length; i < len; i++) {
  2760. ResolvedType resolvedStateType = BcelWorld.fromBcel(stateTypes[i]).resolve(world);
  2761. if (proceedMap.hasKey(i)) {
  2762. mbody.append(proceedVar.createConvertableArrayLoad(fact, proceedMap.get(i), resolvedStateType));
  2763. } else {
  2764. mbody.append(stateVar.createConvertableArrayLoad(fact, i, resolvedStateType));
  2765. }
  2766. }
  2767. mbody.append(Utility.createInvoke(fact, callbackMethod));
  2768. if (getKind() == PreInitialization) {
  2769. mbody.append(Utility.createSet(fact, AjcMemberMaker.aroundClosurePreInitializationField()));
  2770. mbody.append(InstructionConstants.ACONST_NULL);
  2771. } else {
  2772. mbody.append(Utility.createConversion(fact, callbackMethod.getReturnType(), Type.OBJECT));
  2773. }
  2774. mbody.append(InstructionFactory.createReturn(Type.OBJECT));
  2775. closureClass.addMethodGen(runMethod);
  2776. // class
  2777. getEnclosingClass().addGeneratedInner(closureClass);
  2778. return constructor;
  2779. }
  2780. // ---- extraction methods
  2781. /**
  2782. * Extract the instructions in the shadow to a new method.
  2783. *
  2784. * @param extractedMethodName name for the new method
  2785. * @param extractedMethodVisibilityModifier visibility modifiers for the new method
  2786. * @param adviceSourceLocation source location of the advice affecting the shadow
  2787. * @param beingPlacedInInterface is this new method going into an interface
  2788. */
  2789. LazyMethodGen extractShadowInstructionsIntoNewMethod(String extractedMethodName, int extractedMethodVisibilityModifier,
  2790. ISourceLocation adviceSourceLocation, List<String> parameterNames, boolean beingPlacedInInterface) {
  2791. // LazyMethodGen.assertGoodBody(range.getBody(), extractedMethodName);
  2792. if (!getKind().allowsExtraction()) {
  2793. throw new BCException("Attempt to extract method from a shadow kind (" + getKind()
  2794. + ") that does not support this operation");
  2795. }
  2796. LazyMethodGen newMethod = createShadowMethodGen(extractedMethodName, extractedMethodVisibilityModifier, parameterNames, beingPlacedInInterface);
  2797. IntMap remapper = makeRemap();
  2798. range.extractInstructionsInto(newMethod, remapper, (getKind() != PreInitialization) && isFallsThrough());
  2799. if (getKind() == PreInitialization) {
  2800. addPreInitializationReturnCode(newMethod, getSuperConstructorParameterTypes());
  2801. }
  2802. getEnclosingClass().addMethodGen(newMethod, adviceSourceLocation);
  2803. return newMethod;
  2804. }
  2805. private void addPreInitializationReturnCode(LazyMethodGen extractedMethod, Type[] superConstructorTypes) {
  2806. InstructionList body = extractedMethod.getBody();
  2807. final InstructionFactory fact = getFactory();
  2808. BcelVar arrayVar = new BcelVar(world.getCoreType(UnresolvedType.OBJECTARRAY), extractedMethod.allocateLocal(1));
  2809. int len = superConstructorTypes.length;
  2810. body.append(Utility.createConstant(fact, len));
  2811. body.append(fact.createNewArray(Type.OBJECT, (short) 1));
  2812. arrayVar.appendStore(body, fact);
  2813. for (int i = len - 1; i >= 0; i++) {
  2814. // convert thing on top of stack to object
  2815. body.append(Utility.createConversion(fact, superConstructorTypes[i], Type.OBJECT));
  2816. // push object array
  2817. arrayVar.appendLoad(body, fact);
  2818. // swap
  2819. body.append(InstructionConstants.SWAP);
  2820. // do object array store.
  2821. body.append(Utility.createConstant(fact, i));
  2822. body.append(InstructionConstants.SWAP);
  2823. body.append(InstructionFactory.createArrayStore(Type.OBJECT));
  2824. }
  2825. arrayVar.appendLoad(body, fact);
  2826. body.append(InstructionConstants.ARETURN);
  2827. }
  2828. private Type[] getSuperConstructorParameterTypes() {
  2829. // assert getKind() == PreInitialization
  2830. InstructionHandle superCallHandle = getRange().getEnd().getNext();
  2831. InvokeInstruction superCallInstruction = (InvokeInstruction) superCallHandle.getInstruction();
  2832. return superCallInstruction.getArgumentTypes(getEnclosingClass().getConstantPool());
  2833. }
  2834. /**
  2835. * make a map from old frame location to new frame location. Any unkeyed frame location picks out a copied local
  2836. */
  2837. private IntMap makeRemap() {
  2838. IntMap ret = new IntMap(5);
  2839. int reti = 0;
  2840. if (thisVar != null) {
  2841. ret.put(0, reti++); // thisVar guaranteed to be 0
  2842. }
  2843. if (targetVar != null && targetVar != thisVar) {
  2844. ret.put(targetVar.getSlot(), reti++);
  2845. }
  2846. for (int i = 0, len = argVars.length; i < len; i++) {
  2847. ret.put(argVars[i].getSlot(), reti);
  2848. reti += argVars[i].getType().getSize();
  2849. }
  2850. if (thisJoinPointVar != null) {
  2851. ret.put(thisJoinPointVar.getSlot(), reti++);
  2852. }
  2853. // we not only need to put the arguments, we also need to remap their
  2854. // aliases, which we so helpfully put into temps at the beginning of this join
  2855. // point.
  2856. if (!getKind().argsOnStack()) {
  2857. int oldi = 0;
  2858. int newi = 0;
  2859. // if we're passing in a this and we're not argsOnStack we're always
  2860. // passing in a target too
  2861. if (arg0HoldsThis()) {
  2862. ret.put(0, 0);
  2863. oldi++;
  2864. newi += 1;
  2865. }
  2866. // assert targetVar == thisVar
  2867. for (int i = 0; i < getArgCount(); i++) {
  2868. UnresolvedType type = getArgType(i);
  2869. ret.put(oldi, newi);
  2870. oldi += type.getSize();
  2871. newi += type.getSize();
  2872. }
  2873. }
  2874. // System.err.println("making remap for : " + this);
  2875. // if (targetVar != null) System.err.println("target slot : " + targetVar.getSlot());
  2876. // if (thisVar != null) System.err.println(" this slot : " + thisVar.getSlot());
  2877. // System.err.println(ret);
  2878. return ret;
  2879. }
  2880. /**
  2881. * The new method always static. It may take some extra arguments: this, target. If it's argsOnStack, then it must take both
  2882. * this/target If it's argsOnFrame, it shares this and target. ??? rewrite this to do less array munging, please
  2883. */
  2884. private LazyMethodGen createShadowMethodGen(String newMethodName, int visibilityModifier, List<String> parameterNames, boolean beingPlacedInInterface) {
  2885. Type[] shadowParameterTypes = BcelWorld.makeBcelTypes(getArgTypes());
  2886. int modifiers = (world.useFinal() && !beingPlacedInInterface ? Modifier.FINAL : 0) | Modifier.STATIC | visibilityModifier;
  2887. if (targetVar != null && targetVar != thisVar) {
  2888. UnresolvedType targetType = getTargetType();
  2889. targetType = ensureTargetTypeIsCorrect(targetType);
  2890. // see pr109728,pr229910 - this fixes the case when the declaring class is sometype 'X' but the (gs)etfield
  2891. // in the bytecode refers to a subtype of 'X'. This makes sure we use the type originally
  2892. // mentioned in the fieldget instruction as the method parameter and *not* the type upon which the
  2893. // field is declared because when the instructions are extracted into the new around body,
  2894. // they will still refer to the subtype.
  2895. if ((getKind() == FieldGet || getKind() == FieldSet) && getActualTargetType() != null
  2896. && !getActualTargetType().equals(targetType.getName())) {
  2897. targetType = UnresolvedType.forName(getActualTargetType()).resolve(world);
  2898. }
  2899. ResolvedMember resolvedMember = getSignature().resolve(world);
  2900. // pr230075, pr197719
  2901. if (resolvedMember != null && Modifier.isProtected(resolvedMember.getModifiers())
  2902. && !samePackage(resolvedMember.getDeclaringType().getPackageName(), getEnclosingType().getPackageName())
  2903. && !resolvedMember.getName().equals("clone")) {
  2904. if (!hasThis()) { // pr197719 - static accessor has been created to handle the call
  2905. if (Modifier.isStatic(enclosingMethod.getAccessFlags()) && enclosingMethod.getName().startsWith("access$")) {
  2906. targetType = BcelWorld.fromBcel(enclosingMethod.getArgumentTypes()[0]);
  2907. }
  2908. } else {
  2909. if (!targetType.resolve(world).isAssignableFrom(getThisType().resolve(world))) {
  2910. throw new BCException("bad bytecode");
  2911. }
  2912. targetType = getThisType();
  2913. }
  2914. }
  2915. parameterNames.add("target");
  2916. // There is a 'target' and it is not the same as 'this', so add it to the parameter list
  2917. shadowParameterTypes = addTypeToFront(BcelWorld.makeBcelType(targetType), shadowParameterTypes);
  2918. }
  2919. if (thisVar != null) {
  2920. UnresolvedType thisType = getThisType();
  2921. parameterNames.add(0, "ajc$this");
  2922. shadowParameterTypes = addTypeToFront(BcelWorld.makeBcelType(thisType), shadowParameterTypes);
  2923. }
  2924. if (this.getKind() == Shadow.FieldSet || this.getKind() == Shadow.FieldGet) {
  2925. parameterNames.add(getSignature().getName());
  2926. } else {
  2927. String[] pnames = getSignature().getParameterNames(world);
  2928. if (pnames != null) {
  2929. for (int i = 0; i < pnames.length; i++) {
  2930. if (i == 0 && pnames[i].equals("this")) {
  2931. parameterNames.add("ajc$this");
  2932. } else {
  2933. parameterNames.add(pnames[i]);
  2934. }
  2935. }
  2936. }
  2937. }
  2938. // We always want to pass down thisJoinPoint in case we have already woven
  2939. // some advice in here. If we only have a single piece of around advice on a
  2940. // join point, it is unnecessary to accept (and pass) tjp.
  2941. if (thisJoinPointVar != null) {
  2942. parameterNames.add("thisJoinPoint");
  2943. shadowParameterTypes = addTypeToEnd(LazyClassGen.tjpType, shadowParameterTypes);
  2944. }
  2945. UnresolvedType returnType;
  2946. if (getKind() == PreInitialization) {
  2947. returnType = UnresolvedType.OBJECTARRAY;
  2948. } else {
  2949. if (getKind() == ConstructorCall) {
  2950. returnType = getSignature().getDeclaringType();
  2951. } else if (getKind() == FieldSet) {
  2952. returnType = UnresolvedType.VOID;
  2953. } else {
  2954. returnType = getSignature().getReturnType().resolve(world);
  2955. // returnType = getReturnType(); // for this and above lines, see pr137496
  2956. }
  2957. }
  2958. return new LazyMethodGen(modifiers, BcelWorld.makeBcelType(returnType), newMethodName, shadowParameterTypes,
  2959. NoDeclaredExceptions, getEnclosingClass());
  2960. }
  2961. private boolean samePackage(String p1, String p2) {
  2962. if (p1 == null) {
  2963. return p2 == null;
  2964. }
  2965. if (p2 == null) {
  2966. return false;
  2967. }
  2968. return p1.equals(p2);
  2969. }
  2970. private Type[] addTypeToFront(Type type, Type[] types) {
  2971. int len = types.length;
  2972. Type[] ret = new Type[len + 1];
  2973. ret[0] = type;
  2974. System.arraycopy(types, 0, ret, 1, len);
  2975. return ret;
  2976. }
  2977. private Type[] addTypeToEnd(Type type, Type[] types) {
  2978. int len = types.length;
  2979. Type[] ret = new Type[len + 1];
  2980. ret[len] = type;
  2981. System.arraycopy(types, 0, ret, 0, len);
  2982. return ret;
  2983. }
  2984. public BcelVar genTempVar(UnresolvedType utype) {
  2985. ResolvedType rtype = utype.resolve(world);
  2986. return new BcelVar(rtype, genTempVarIndex(rtype.getSize()));
  2987. }
  2988. // public static final boolean CREATE_TEMP_NAMES = true;
  2989. public BcelVar genTempVar(UnresolvedType typeX, String localName) {
  2990. BcelVar tv = genTempVar(typeX);
  2991. // if (CREATE_TEMP_NAMES) {
  2992. // for (InstructionHandle ih = range.getStart(); ih != range.getEnd(); ih = ih.getNext()) {
  2993. // if (Range.isRangeHandle(ih)) continue;
  2994. // ih.addTargeter(new LocalVariableTag(typeX, localName, tv.getSlot()));
  2995. // }
  2996. // }
  2997. return tv;
  2998. }
  2999. // eh doesn't think we need to garbage collect these (64K is a big number...)
  3000. private int genTempVarIndex(int size) {
  3001. return enclosingMethod.allocateLocal(size);
  3002. }
  3003. public InstructionFactory getFactory() {
  3004. return getEnclosingClass().getFactory();
  3005. }
  3006. @Override
  3007. public ISourceLocation getSourceLocation() {
  3008. int sourceLine = getSourceLine();
  3009. if (sourceLine == 0 || sourceLine == -1) {
  3010. // Thread.currentThread().dumpStack();
  3011. // System.err.println(this + ": " + range);
  3012. return getEnclosingClass().getType().getSourceLocation();
  3013. } else {
  3014. // For staticinitialization, if we have a nice offset, don't build a new source loc
  3015. if (getKind() == Shadow.StaticInitialization && getEnclosingClass().getType().getSourceLocation().getOffset() != 0) {
  3016. return getEnclosingClass().getType().getSourceLocation();
  3017. } else {
  3018. int offset = 0;
  3019. Kind kind = getKind();
  3020. if ((kind == MethodExecution) || (kind == ConstructorExecution) || (kind == AdviceExecution)
  3021. || (kind == StaticInitialization) || (kind == PreInitialization) || (kind == Initialization)) {
  3022. if (getEnclosingMethod().hasDeclaredLineNumberInfo()) {
  3023. offset = getEnclosingMethod().getDeclarationOffset();
  3024. }
  3025. }
  3026. return getEnclosingClass().getType().getSourceContext().makeSourceLocation(sourceLine, offset);
  3027. }
  3028. }
  3029. }
  3030. public Shadow getEnclosingShadow() {
  3031. return enclosingShadow;
  3032. }
  3033. public LazyMethodGen getEnclosingMethod() {
  3034. return enclosingMethod;
  3035. }
  3036. public boolean isFallsThrough() {
  3037. return !terminatesWithReturn();
  3038. }
  3039. public void setActualTargetType(String className) {
  3040. this.actualInstructionTargetType = className;
  3041. }
  3042. public String getActualTargetType() {
  3043. return actualInstructionTargetType;
  3044. }
  3045. }