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

BcelClassWeaver.java 131KB

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