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

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