Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

LazyMethodGen.java 61KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868
  1. /* *******************************************************************
  2. * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
  3. * All rights reserved.
  4. * This program and the accompanying materials are made available
  5. * under the terms of the Eclipse Public License v1.0
  6. * which accompanies this distribution and is available at
  7. * http://www.eclipse.org/legal/epl-v10.html
  8. *
  9. * Contributors:
  10. * PARC initial implementation
  11. * ******************************************************************/
  12. package org.aspectj.weaver.bcel;
  13. import java.io.ByteArrayOutputStream;
  14. import java.io.PrintStream;
  15. import java.lang.reflect.Modifier;
  16. import java.util.ArrayList;
  17. import java.util.HashMap;
  18. import java.util.HashSet;
  19. import java.util.Iterator;
  20. import java.util.LinkedList;
  21. import java.util.List;
  22. import java.util.ListIterator;
  23. import java.util.Map;
  24. import java.util.Set;
  25. import org.aspectj.apache.bcel.Constants;
  26. import org.aspectj.apache.bcel.classfile.Attribute;
  27. import org.aspectj.apache.bcel.classfile.ConstantPool;
  28. import org.aspectj.apache.bcel.classfile.Method;
  29. import org.aspectj.apache.bcel.classfile.Synthetic;
  30. import org.aspectj.apache.bcel.classfile.annotation.AnnotationGen;
  31. import org.aspectj.apache.bcel.generic.BranchHandle;
  32. import org.aspectj.apache.bcel.generic.ClassGenException;
  33. import org.aspectj.apache.bcel.generic.CodeExceptionGen;
  34. import org.aspectj.apache.bcel.generic.Instruction;
  35. import org.aspectj.apache.bcel.generic.InstructionBranch;
  36. import org.aspectj.apache.bcel.generic.InstructionHandle;
  37. import org.aspectj.apache.bcel.generic.InstructionList;
  38. import org.aspectj.apache.bcel.generic.InstructionSelect;
  39. import org.aspectj.apache.bcel.generic.InstructionTargeter;
  40. import org.aspectj.apache.bcel.generic.LineNumberTag;
  41. import org.aspectj.apache.bcel.generic.LocalVariableTag;
  42. import org.aspectj.apache.bcel.generic.MethodGen;
  43. import org.aspectj.apache.bcel.generic.ObjectType;
  44. import org.aspectj.apache.bcel.generic.Tag;
  45. import org.aspectj.apache.bcel.generic.TargetLostException;
  46. import org.aspectj.apache.bcel.generic.Type;
  47. import org.aspectj.bridge.IMessage;
  48. import org.aspectj.bridge.ISourceLocation;
  49. import org.aspectj.weaver.AjAttribute;
  50. import org.aspectj.weaver.AjAttribute.WeaverVersionInfo;
  51. import org.aspectj.weaver.AnnotationAJ;
  52. import org.aspectj.weaver.BCException;
  53. import org.aspectj.weaver.ISourceContext;
  54. import org.aspectj.weaver.MemberImpl;
  55. import org.aspectj.weaver.NameMangler;
  56. import org.aspectj.weaver.ResolvedMember;
  57. import org.aspectj.weaver.ResolvedType;
  58. import org.aspectj.weaver.Shadow;
  59. import org.aspectj.weaver.UnresolvedType;
  60. import org.aspectj.weaver.WeaverMessages;
  61. import org.aspectj.weaver.World;
  62. import org.aspectj.weaver.tools.Traceable;
  63. /**
  64. * A LazyMethodGen should be treated as a MethodGen. It's our way of abstracting over the low-level Method objects. It converts
  65. * through {@link MethodGen} to create and to serialize, but that's it.
  66. *
  67. * <p>
  68. * At any rate, there are two ways to create LazyMethodGens. One is from a method, which does work through MethodGen to do the
  69. * correct thing. The other is the creation of a completely empty LazyMethodGen, and it is used when we're constructing code from
  70. * scratch.
  71. *
  72. * <p>
  73. * We stay away from targeters for rangey things like Shadows and Exceptions.
  74. */
  75. public final class LazyMethodGen implements Traceable {
  76. private static final AnnotationAJ[] NO_ANNOTATIONAJ = new AnnotationAJ[] {};
  77. private int modifiers;
  78. private Type returnType;
  79. private final String name;
  80. private Type[] argumentTypes;
  81. // private final String[] argumentNames;
  82. private String[] declaredExceptions;
  83. private InstructionList body;
  84. private List<Attribute> attributes;
  85. private List<AnnotationAJ> newAnnotations;
  86. private List<ResolvedType> annotationsForRemoval;
  87. private AnnotationAJ[][] newParameterAnnotations;
  88. private final LazyClassGen enclosingClass;
  89. private BcelMethod memberView;
  90. private AjAttribute.EffectiveSignatureAttribute effectiveSignature;
  91. int highestLineNumber = 0;
  92. boolean wasPackedOptimally = false;
  93. private Method savedMethod = null;
  94. // Some tools that may post process the output bytecode do not long local variable tables
  95. // to be generated as one reason the tables may be missing in the first place is because
  96. // the bytecode is odd. See https://bugs.eclipse.org/bugs/show_bug.cgi?id=470658
  97. private final boolean originalMethodHasLocalVariableTable;
  98. /*
  99. * We use LineNumberTags and not Gens.
  100. *
  101. * This option specifies whether we let the BCEL classes create LineNumberGens and LocalVariableGens or if we make it create
  102. * LineNumberTags and LocalVariableTags. Up until 1.5.1 we always created Gens - then on return from the MethodGen ctor we took
  103. * them apart, reprocessed them all and created Tags. (see unpackLocals/unpackLineNumbers). As we have our own copy of Bcel, why
  104. * not create the right thing straightaway? So setting this to true will call the MethodGen ctor() in such a way that it creates
  105. * Tags - removing the need for unpackLocals/unpackLineNumbers - HOWEVER see the ensureAllLineNumberSetup() method for some
  106. * other relevant info.
  107. *
  108. * Whats the difference between a Tag and a Gen? A Tag is more lightweight, it doesn't know which instructions it targets, it
  109. * relies on the instructions targettingit - this reduces the amount of targeter manipulation we have to do.
  110. */
  111. /**
  112. * This is nonnull if this method is the result of an "inlining". We currently copy methods into other classes for around
  113. * advice. We add this field so we can get JSR45 information correct. If/when we do _actual_ inlining, we'll need to subtype
  114. * LineNumberTag to have external line numbers.
  115. */
  116. String fromFilename = null;
  117. private int maxLocals;
  118. private boolean canInline = true;
  119. private boolean isSynthetic = false;
  120. List<BcelShadow> matchedShadows;
  121. // Used for interface introduction - this is the type of the interface the method is technically on
  122. public ResolvedType definingType = null;
  123. static class LightweightBcelMethod extends BcelMethod {
  124. LightweightBcelMethod(BcelObjectType declaringType, Method method) {
  125. super(declaringType, method);
  126. // TODO Auto-generated constructor stub
  127. }
  128. }
  129. public LazyMethodGen(int modifiers, Type returnType, String name, Type[] paramTypes, String[] declaredExceptions,
  130. LazyClassGen enclosingClass) {
  131. // enclosingClass.getName() + ", " + returnType);
  132. this.memberView = null; // should be okay, since constructed ones aren't woven into
  133. this.modifiers = modifiers;
  134. this.returnType = returnType;
  135. this.name = name;
  136. this.argumentTypes = paramTypes;
  137. // this.argumentNames = Utility.makeArgNames(paramTypes.length);
  138. this.declaredExceptions = declaredExceptions;
  139. if (!Modifier.isAbstract(modifiers)) {
  140. body = new InstructionList();
  141. setMaxLocals(calculateMaxLocals());
  142. } else {
  143. body = null;
  144. }
  145. this.attributes = new ArrayList<Attribute>();
  146. this.enclosingClass = enclosingClass;
  147. assertGoodBody();
  148. this.originalMethodHasLocalVariableTable = true; // it is a new method, we want an lvar table
  149. // @AJ advice are not inlined by default since requires further analysis and weaving ordering control
  150. // TODO AV - improve - note: no room for improvement as long as aspects are reweavable
  151. // since the inlined version with wrappers and an to be done annotation to keep
  152. // inline state will be garbaged due to reweavable impl
  153. if (memberView != null && isAdviceMethod()) {
  154. if (enclosingClass.getType().isAnnotationStyleAspect()) {
  155. // TODO we could check for @Around advice as well
  156. this.canInline = false;
  157. }
  158. }
  159. }
  160. private int calculateMaxLocals() {
  161. int ret = Modifier.isStatic(modifiers) ? 0 : 1; // will there be a 'this'?
  162. for (Type type : argumentTypes) {
  163. ret += type.getSize();
  164. }
  165. return ret;
  166. }
  167. // build from an existing method, lazy build saves most work for
  168. // initialization
  169. public LazyMethodGen(Method m, LazyClassGen enclosingClass) {
  170. savedMethod = m;
  171. this.enclosingClass = enclosingClass;
  172. if (!(m.isAbstract() || m.isNative()) && m.getCode() == null) {
  173. throw new RuntimeException("bad non-abstract method with no code: " + m + " on " + enclosingClass);
  174. }
  175. if ((m.isAbstract() || m.isNative()) && m.getCode() != null) {
  176. throw new RuntimeException("bad abstract method with code: " + m + " on " + enclosingClass);
  177. }
  178. this.memberView = new BcelMethod(enclosingClass.getBcelObjectType(), m);
  179. this.originalMethodHasLocalVariableTable = savedMethod.getLocalVariableTable()!=null;
  180. this.modifiers = m.getModifiers();
  181. this.name = m.getName();
  182. // @AJ advice are not inlined by default since requires further analysis
  183. // and weaving ordering control
  184. // TODO AV - improve - note: no room for improvement as long as aspects
  185. // are reweavable
  186. // since the inlined version with wrappers and an to be done annotation
  187. // to keep
  188. // inline state will be garbaged due to reweavable impl
  189. if (memberView != null && isAdviceMethod()) {
  190. if (enclosingClass.getType().isAnnotationStyleAspect()) {
  191. // TODO we could check for @Around advice as well
  192. this.canInline = false;
  193. }
  194. }
  195. }
  196. private boolean isAbstractOrNative(int modifiers) {
  197. return Modifier.isAbstract(modifiers) || Modifier.isNative(modifiers);
  198. }
  199. public LazyMethodGen(BcelMethod m, LazyClassGen enclosingClass) {
  200. savedMethod = m.getMethod();
  201. this.enclosingClass = enclosingClass;
  202. if (!isAbstractOrNative(m.getModifiers()) && savedMethod.getCode() == null) {
  203. throw new RuntimeException("bad non-abstract method with no code: " + m + " on " + enclosingClass);
  204. }
  205. if (isAbstractOrNative(m.getModifiers()) && savedMethod.getCode() != null) {
  206. throw new RuntimeException("bad abstract method with code: " + m + " on " + enclosingClass);
  207. }
  208. // this.memberView = new BcelMethod(enclosingClass.getBcelObjectType(),
  209. // m);
  210. this.memberView = m;
  211. this.modifiers = savedMethod.getModifiers();
  212. this.name = m.getName();
  213. this.originalMethodHasLocalVariableTable = savedMethod.getLocalVariableTable() != null;
  214. // @AJ advice are not inlined by default since requires further analysis
  215. // and weaving ordering control
  216. // TODO AV - improve - note: no room for improvement as long as aspects
  217. // are reweavable
  218. // since the inlined version with wrappers and an to be done annotation
  219. // to keep
  220. // inline state will be garbaged due to reweavable impl
  221. if (memberView != null && isAdviceMethod()) {
  222. if (enclosingClass.getType().isAnnotationStyleAspect()) {
  223. // TODO we could check for @Around advice as well
  224. this.canInline = false;
  225. }
  226. }
  227. }
  228. public boolean hasDeclaredLineNumberInfo() {
  229. return (memberView != null && memberView.hasDeclarationLineNumberInfo());
  230. }
  231. public int getDeclarationLineNumber() {
  232. if (hasDeclaredLineNumberInfo()) {
  233. return memberView.getDeclarationLineNumber();
  234. } else {
  235. return -1;
  236. }
  237. }
  238. public int getDeclarationOffset() {
  239. if (hasDeclaredLineNumberInfo()) {
  240. return memberView.getDeclarationOffset();
  241. } else {
  242. return 0;
  243. }
  244. }
  245. public void addAnnotation(AnnotationAJ ax) {
  246. initialize();
  247. if (memberView == null) {
  248. // If member view is null, we manage them in newAnnotations
  249. if (newAnnotations == null) {
  250. newAnnotations = new ArrayList<AnnotationAJ>();
  251. }
  252. newAnnotations.add(ax);
  253. } else {
  254. memberView.addAnnotation(ax);
  255. }
  256. }
  257. public void removeAnnotation(ResolvedType annotationType) {
  258. initialize();
  259. if (memberView == null) {
  260. // If member view is null, we manage them in newAnnotations
  261. if (annotationsForRemoval == null) {
  262. annotationsForRemoval = new ArrayList<ResolvedType>();
  263. }
  264. annotationsForRemoval.add(annotationType);
  265. } else {
  266. memberView.removeAnnotation(annotationType);
  267. }
  268. }
  269. public void addParameterAnnotation(int parameterNumber, AnnotationAJ anno) {
  270. initialize();
  271. if (memberView == null) {
  272. if (newParameterAnnotations == null) {
  273. // time to create it
  274. int pcount = getArgumentTypes().length;
  275. newParameterAnnotations = new AnnotationAJ[pcount][];
  276. for (int i = 0; i < pcount; i++) {
  277. if (i == parameterNumber) {
  278. newParameterAnnotations[i] = new AnnotationAJ[1];
  279. newParameterAnnotations[i][0] = anno;
  280. } else {
  281. newParameterAnnotations[i] = NO_ANNOTATIONAJ;
  282. }
  283. }
  284. } else {
  285. AnnotationAJ[] currentAnnoArray = newParameterAnnotations[parameterNumber];
  286. AnnotationAJ[] newAnnoArray = new AnnotationAJ[currentAnnoArray.length + 1];
  287. System.arraycopy(currentAnnoArray, 0, newAnnoArray, 0, currentAnnoArray.length);
  288. newAnnoArray[currentAnnoArray.length] = anno;
  289. newParameterAnnotations[parameterNumber] = newAnnoArray;
  290. }
  291. } else {
  292. memberView.addParameterAnnotation(parameterNumber, anno);
  293. }
  294. }
  295. public ResolvedType[] getAnnotationTypes() {
  296. initialize();
  297. if (memberView == null && newAnnotations!=null && newAnnotations.size()!=0) {
  298. // TODO Ignoring removed annotations for now
  299. ResolvedType[] annotationTypes = new ResolvedType[newAnnotations.size()];
  300. for (int a=0,len=newAnnotations.size();a<len;a++) {
  301. annotationTypes[a] = newAnnotations.get(a).getType();
  302. }
  303. return annotationTypes;
  304. }
  305. return null;
  306. }
  307. public AnnotationAJ[] getAnnotations() {
  308. initialize();
  309. if (memberView == null && newAnnotations!=null && newAnnotations.size()!=0) {
  310. return newAnnotations.toArray(new AnnotationAJ[newAnnotations.size()]);
  311. }
  312. return null;
  313. }
  314. public boolean hasAnnotation(UnresolvedType annotationType) {
  315. initialize();
  316. if (memberView == null) {
  317. if (annotationsForRemoval != null) {
  318. for (ResolvedType at : annotationsForRemoval) {
  319. if (at.equals(annotationType)) {
  320. return false;
  321. }
  322. }
  323. }
  324. // Check local annotations first
  325. if (newAnnotations != null) {
  326. for (AnnotationAJ annotation : newAnnotations) {
  327. if (annotation.getTypeSignature().equals(annotationType.getSignature())) {
  328. return true;
  329. }
  330. }
  331. }
  332. memberView = new BcelMethod(getEnclosingClass().getBcelObjectType(), getMethod());
  333. return memberView.hasAnnotation(annotationType);
  334. }
  335. return memberView.hasAnnotation(annotationType);
  336. }
  337. private void initialize() {
  338. if (returnType != null) {
  339. return;
  340. }
  341. MethodGen gen = new MethodGen(savedMethod, enclosingClass.getName(), enclosingClass.getConstantPool(), true);
  342. this.returnType = gen.getReturnType();
  343. this.argumentTypes = gen.getArgumentTypes();
  344. this.declaredExceptions = gen.getExceptions();
  345. this.attributes = gen.getAttributes();
  346. // this.annotations = gen.getAnnotations();
  347. this.maxLocals = gen.getMaxLocals();
  348. // this.returnType = BcelWorld.makeBcelType(memberView.getReturnType());
  349. // this.argumentTypes =
  350. // BcelWorld.makeBcelTypes(memberView.getParameterTypes());
  351. //
  352. // this.declaredExceptions =
  353. // UnresolvedType.getNames(memberView.getExceptions());
  354. // //gen.getExceptions();
  355. // this.attributes = new Attribute[0]; //gen.getAttributes();
  356. // this.maxLocals = savedMethod.getCode().getMaxLocals();
  357. if (gen.isAbstract() || gen.isNative()) {
  358. body = null;
  359. } else {
  360. // body = new InstructionList(savedMethod.getCode().getCode());
  361. body = gen.getInstructionList();
  362. unpackHandlers(gen);
  363. ensureAllLineNumberSetup();
  364. highestLineNumber = gen.getHighestlinenumber();
  365. }
  366. assertGoodBody();
  367. }
  368. // XXX we're relying on the javac promise I've just made up that we won't
  369. // have an early exception
  370. // in the list mask a later exception: That is, for two exceptions E and F,
  371. // if E preceeds F, then either E \cup F = {}, or E \nonstrictsubset F. So
  372. // when we add F,
  373. // we add it on the _OUTSIDE_ of any handlers that share starts or ends with
  374. // it.
  375. // with that in mind, we merrily go adding ranges for exceptions.
  376. private void unpackHandlers(MethodGen gen) {
  377. CodeExceptionGen[] exns = gen.getExceptionHandlers();
  378. if (exns != null) {
  379. int len = exns.length;
  380. // if (len > 0) hasExceptionHandlers = true;
  381. int priority = len - 1;
  382. for (int i = 0; i < len; i++, priority--) {
  383. CodeExceptionGen exn = exns[i];
  384. InstructionHandle start = Range.genStart(body, getOutermostExceptionStart(exn.getStartPC()));
  385. InstructionHandle end = Range.genEnd(body, getOutermostExceptionEnd(exn.getEndPC()));
  386. // this doesn't necessarily handle overlapping correctly!!!
  387. ExceptionRange er = new ExceptionRange(body, exn.getCatchType() == null ? null : BcelWorld.fromBcel(exn
  388. .getCatchType()), priority);
  389. er.associateWithTargets(start, end, exn.getHandlerPC());
  390. exn.setStartPC(null); // also removes from target
  391. exn.setEndPC(null); // also removes from target
  392. exn.setHandlerPC(null); // also removes from target
  393. }
  394. gen.removeExceptionHandlers();
  395. }
  396. }
  397. private InstructionHandle getOutermostExceptionStart(InstructionHandle ih) {
  398. while (true) {
  399. if (ExceptionRange.isExceptionStart(ih.getPrev())) {
  400. ih = ih.getPrev();
  401. } else {
  402. return ih;
  403. }
  404. }
  405. }
  406. private InstructionHandle getOutermostExceptionEnd(InstructionHandle ih) {
  407. while (true) {
  408. if (ExceptionRange.isExceptionEnd(ih.getNext())) {
  409. ih = ih.getNext();
  410. } else {
  411. return ih;
  412. }
  413. }
  414. }
  415. /**
  416. * On entry to this method we have a method whose instruction stream contains a few instructions that have line numbers assigned
  417. * to them (LineNumberTags). The aim is to ensure every instruction has the right line number. This is necessary because some of
  418. * them may be extracted out into other methods - and it'd be useful for them to maintain the source line number for debugging.
  419. */
  420. public void ensureAllLineNumberSetup() {
  421. LineNumberTag lastKnownLineNumberTag = null;
  422. boolean skip = false;
  423. for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) {
  424. skip = false;
  425. for (InstructionTargeter targeter : ih.getTargeters()) {
  426. if (targeter instanceof LineNumberTag) {
  427. lastKnownLineNumberTag = (LineNumberTag) targeter;
  428. skip = true;
  429. }
  430. }
  431. if (lastKnownLineNumberTag != null && !skip) {
  432. ih.addTargeter(lastKnownLineNumberTag);
  433. }
  434. }
  435. }
  436. // ===============
  437. public int allocateLocal(Type type) {
  438. return allocateLocal(type.getSize());
  439. }
  440. public int allocateLocal(int slots) {
  441. int max = getMaxLocals();
  442. setMaxLocals(max + slots);
  443. return max;
  444. }
  445. public Method getMethod() {
  446. if (savedMethod != null) {
  447. return savedMethod; // ??? this relies on gentle treatment of
  448. // constant pool
  449. }
  450. try {
  451. MethodGen gen = pack();
  452. savedMethod = gen.getMethod();
  453. return savedMethod;
  454. } catch (ClassGenException e) {
  455. enclosingClass
  456. .getBcelObjectType()
  457. .getResolvedTypeX()
  458. .getWorld()
  459. .showMessage(
  460. IMessage.ERROR,
  461. WeaverMessages.format(WeaverMessages.PROBLEM_GENERATING_METHOD, this.getClassName(), this.getName(),
  462. e.getMessage()),
  463. this.getMemberView() == null ? null : this.getMemberView().getSourceLocation(), null);
  464. // throw e; PR 70201.... let the normal problem reporting
  465. // infrastructure deal with this rather than crashing.
  466. body = null;
  467. MethodGen gen = pack();
  468. return gen.getMethod();
  469. } catch (RuntimeException re) {
  470. if (re.getCause() instanceof ClassGenException) {
  471. enclosingClass
  472. .getBcelObjectType()
  473. .getResolvedTypeX()
  474. .getWorld()
  475. .showMessage(
  476. IMessage.ERROR,
  477. WeaverMessages.format(WeaverMessages.PROBLEM_GENERATING_METHOD, this.getClassName(),
  478. this.getName(), re.getCause().getMessage()),
  479. this.getMemberView() == null ? null : this.getMemberView().getSourceLocation(), null);
  480. // throw e; PR 70201.... let the normal problem reporting
  481. // infrastructure deal with this rather than crashing.
  482. body = null;
  483. MethodGen gen = pack();
  484. return gen.getMethod();
  485. }
  486. throw re;
  487. }
  488. }
  489. public void markAsChanged() {
  490. if (wasPackedOptimally) {
  491. throw new RuntimeException("Already packed method is being re-modified: " + getClassName() + " " + toShortString());
  492. }
  493. initialize();
  494. savedMethod = null;
  495. }
  496. // =============================
  497. @Override
  498. public String toString() {
  499. BcelObjectType bot = enclosingClass.getBcelObjectType();
  500. WeaverVersionInfo weaverVersion = (bot == null ? WeaverVersionInfo.CURRENT : bot.getWeaverVersionAttribute());
  501. return toLongString(weaverVersion);
  502. }
  503. public String toShortString() {
  504. String access = org.aspectj.apache.bcel.classfile.Utility.accessToString(getAccessFlags());
  505. StringBuffer buf = new StringBuffer();
  506. if (!access.equals("")) {
  507. buf.append(access);
  508. buf.append(" ");
  509. }
  510. buf.append(org.aspectj.apache.bcel.classfile.Utility.signatureToString(getReturnType().getSignature(), true));
  511. buf.append(" ");
  512. buf.append(getName());
  513. buf.append("(");
  514. {
  515. int len = argumentTypes.length;
  516. if (len > 0) {
  517. buf.append(org.aspectj.apache.bcel.classfile.Utility.signatureToString(argumentTypes[0].getSignature(), true));
  518. for (int i = 1; i < argumentTypes.length; i++) {
  519. buf.append(", ");
  520. buf.append(org.aspectj.apache.bcel.classfile.Utility.signatureToString(argumentTypes[i].getSignature(), true));
  521. }
  522. }
  523. }
  524. buf.append(")");
  525. {
  526. int len = declaredExceptions != null ? declaredExceptions.length : 0;
  527. if (len > 0) {
  528. buf.append(" throws ");
  529. buf.append(declaredExceptions[0]);
  530. for (int i = 1; i < declaredExceptions.length; i++) {
  531. buf.append(", ");
  532. buf.append(declaredExceptions[i]);
  533. }
  534. }
  535. }
  536. return buf.toString();
  537. }
  538. public String toLongString(WeaverVersionInfo weaverVersion) {
  539. ByteArrayOutputStream s = new ByteArrayOutputStream();
  540. print(new PrintStream(s), weaverVersion);
  541. return new String(s.toByteArray());
  542. }
  543. public void print(WeaverVersionInfo weaverVersion) {
  544. print(System.out, weaverVersion);
  545. }
  546. public void print(PrintStream out, WeaverVersionInfo weaverVersion) {
  547. out.print(" " + toShortString());
  548. printAspectAttributes(out, weaverVersion);
  549. InstructionList body = getBody();
  550. if (body == null) {
  551. out.println(";");
  552. return;
  553. }
  554. out.println(":");
  555. new BodyPrinter(out).run();
  556. out.println(" end " + toShortString());
  557. }
  558. private void printAspectAttributes(PrintStream out, WeaverVersionInfo weaverVersion) {
  559. ISourceContext context = null;
  560. if (enclosingClass != null && enclosingClass.getType() != null) {
  561. context = enclosingClass.getType().getSourceContext();
  562. }
  563. List<AjAttribute> as = Utility.readAjAttributes(getClassName(), attributes.toArray(new Attribute[] {}), context, null, weaverVersion,
  564. new BcelConstantPoolReader(this.enclosingClass.getConstantPool()));
  565. if (!as.isEmpty()) {
  566. out.println(" " + as.get(0)); // XXX assuming exactly one
  567. // attribute, munger...
  568. }
  569. }
  570. private class BodyPrinter {
  571. Map<InstructionHandle, String> labelMap = new HashMap<InstructionHandle, String>();
  572. InstructionList body;
  573. PrintStream out;
  574. ConstantPool pool;
  575. BodyPrinter(PrintStream out) {
  576. this.pool = enclosingClass.getConstantPool();
  577. this.body = getBodyForPrint();
  578. this.out = out;
  579. }
  580. BodyPrinter(PrintStream out, InstructionList il) {
  581. this.pool = enclosingClass.getConstantPool();
  582. this.body = il;
  583. this.out = out;
  584. }
  585. void run() {
  586. // killNops();
  587. assignLabels();
  588. print();
  589. }
  590. // label assignment
  591. void assignLabels() {
  592. LinkedList<ExceptionRange> exnTable = new LinkedList<ExceptionRange>();
  593. String pendingLabel = null;
  594. // boolean hasPendingTargeters = false;
  595. int lcounter = 0;
  596. for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) {
  597. // targeters
  598. for (InstructionTargeter t : ih.getTargeters()) {
  599. // [
  600. // i
  601. // ]
  602. // ;
  603. if (t instanceof ExceptionRange) {
  604. // assert isRangeHandle(h);
  605. ExceptionRange r = (ExceptionRange) t;
  606. if (r.getStart() == ih) {
  607. insertHandler(r, exnTable);
  608. }
  609. } else if (t instanceof InstructionBranch) {
  610. if (pendingLabel == null) {
  611. pendingLabel = "L" + lcounter++;
  612. }
  613. } else {
  614. // assert isRangeHandle(h)
  615. }
  616. }
  617. if (pendingLabel != null) {
  618. labelMap.put(ih, pendingLabel);
  619. if (!Range.isRangeHandle(ih)) {
  620. pendingLabel = null;
  621. }
  622. }
  623. }
  624. int ecounter = 0;
  625. for (ExceptionRange er: exnTable) {
  626. String exceptionLabel = "E" + ecounter++;
  627. labelMap.put(Range.getRealStart(er.getHandler()), exceptionLabel);
  628. labelMap.put(er.getHandler(), exceptionLabel);
  629. }
  630. }
  631. // printing
  632. void print() {
  633. int depth = 0;
  634. int currLine = -1;
  635. bodyPrint: for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) {
  636. if (Range.isRangeHandle(ih)) {
  637. Range r = Range.getRange(ih);
  638. // don't print empty ranges, that is, ranges who contain no
  639. // actual instructions
  640. for (InstructionHandle xx = r.getStart(); Range.isRangeHandle(xx); xx = xx.getNext()) {
  641. if (xx == r.getEnd()) {
  642. continue bodyPrint;
  643. }
  644. }
  645. // doesn't handle nested: if (r.getStart().getNext() ==
  646. // r.getEnd()) continue;
  647. if (r.getStart() == ih) {
  648. printRangeString(r, depth++);
  649. } else {
  650. if (r.getEnd() != ih) {
  651. throw new RuntimeException("bad");
  652. }
  653. printRangeString(r, --depth);
  654. }
  655. } else {
  656. printInstruction(ih, depth);
  657. int line = getLineNumber(ih, currLine);
  658. if (line != currLine) {
  659. currLine = line;
  660. out.println(" (line " + line + ")");
  661. } else {
  662. out.println();
  663. }
  664. }
  665. }
  666. }
  667. void printRangeString(Range r, int depth) {
  668. printDepth(depth);
  669. out.println(getRangeString(r, labelMap));
  670. }
  671. String getRangeString(Range r, Map<InstructionHandle, String> labelMap) {
  672. if (r instanceof ExceptionRange) {
  673. ExceptionRange er = (ExceptionRange) r;
  674. return er.toString() + " -> " + labelMap.get(er.getHandler());
  675. //
  676. // + " PRI " + er.getPriority();
  677. } else {
  678. return r.toString();
  679. }
  680. }
  681. void printDepth(int depth) {
  682. pad(BODY_INDENT);
  683. while (depth > 0) {
  684. out.print("| ");
  685. depth--;
  686. }
  687. }
  688. void printLabel(String s, int depth) {
  689. int space = Math.max(CODE_INDENT - depth * 2, 0);
  690. if (s == null) {
  691. pad(space);
  692. } else {
  693. space = Math.max(space - (s.length() + 2), 0);
  694. pad(space);
  695. out.print(s);
  696. out.print(": ");
  697. }
  698. }
  699. void printInstruction(InstructionHandle h, int depth) {
  700. printDepth(depth);
  701. printLabel(labelMap.get(h), depth);
  702. Instruction inst = h.getInstruction();
  703. if (inst.isConstantPoolInstruction()) {
  704. out.print(Constants.OPCODE_NAMES[inst.opcode].toUpperCase());
  705. out.print(" ");
  706. out.print(pool.constantToString(pool.getConstant(inst.getIndex())));
  707. } else if (inst instanceof InstructionSelect) {
  708. InstructionSelect sinst = (InstructionSelect) inst;
  709. out.println(Constants.OPCODE_NAMES[sinst.opcode].toUpperCase());
  710. int[] matches = sinst.getMatchs();
  711. InstructionHandle[] targets = sinst.getTargets();
  712. InstructionHandle defaultTarget = sinst.getTarget();
  713. for (int i = 0, len = matches.length; i < len; i++) {
  714. printDepth(depth);
  715. printLabel(null, depth);
  716. out.print(" ");
  717. out.print(matches[i]);
  718. out.print(": \t");
  719. out.println(labelMap.get(targets[i]));
  720. }
  721. printDepth(depth);
  722. printLabel(null, depth);
  723. out.print(" ");
  724. out.print("default: \t");
  725. out.print(labelMap.get(defaultTarget));
  726. } else if (inst instanceof InstructionBranch) {
  727. InstructionBranch brinst = (InstructionBranch) inst;
  728. out.print(Constants.OPCODE_NAMES[brinst.getOpcode()].toUpperCase());
  729. out.print(" ");
  730. out.print(labelMap.get(brinst.getTarget()));
  731. } else if (inst.isLocalVariableInstruction()) {
  732. // LocalVariableInstruction lvinst = (LocalVariableInstruction)
  733. // inst;
  734. out.print(inst.toString(false).toUpperCase());
  735. int index = inst.getIndex();
  736. LocalVariableTag tag = getLocalVariableTag(h, index);
  737. if (tag != null) {
  738. out.print(" // ");
  739. out.print(tag.getType());
  740. out.print(" ");
  741. out.print(tag.getName());
  742. }
  743. } else {
  744. out.print(inst.toString(false).toUpperCase());
  745. }
  746. }
  747. static final int BODY_INDENT = 4;
  748. static final int CODE_INDENT = 16;
  749. void pad(int size) {
  750. for (int i = 0; i < size; i++) {
  751. out.print(" ");
  752. }
  753. }
  754. }
  755. static LocalVariableTag getLocalVariableTag(InstructionHandle ih, int index) {
  756. for (InstructionTargeter t : ih.getTargeters()) {
  757. if (t instanceof LocalVariableTag) {
  758. LocalVariableTag lvt = (LocalVariableTag) t;
  759. if (lvt.getSlot() == index) {
  760. return lvt;
  761. }
  762. }
  763. }
  764. return null;
  765. }
  766. static int getLineNumber(InstructionHandle ih, int prevLine) {
  767. for (InstructionTargeter t : ih.getTargeters()) {
  768. if (t instanceof LineNumberTag) {
  769. return ((LineNumberTag) t).getLineNumber();
  770. }
  771. }
  772. return prevLine;
  773. }
  774. public boolean isStatic() {
  775. return Modifier.isStatic(getAccessFlags());
  776. }
  777. public boolean isAbstract() {
  778. return Modifier.isAbstract(getAccessFlags());
  779. }
  780. public boolean isBridgeMethod() {
  781. return (getAccessFlags() & Constants.ACC_BRIDGE) != 0;
  782. }
  783. public void addExceptionHandler(InstructionHandle start, InstructionHandle end, InstructionHandle handlerStart,
  784. ObjectType catchType, boolean highPriority) {
  785. InstructionHandle start1 = Range.genStart(body, start);
  786. InstructionHandle end1 = Range.genEnd(body, end);
  787. ExceptionRange er = new ExceptionRange(body, (catchType == null ? null : BcelWorld.fromBcel(catchType)), highPriority);
  788. er.associateWithTargets(start1, end1, handlerStart);
  789. }
  790. public int getAccessFlags() {
  791. return modifiers;
  792. }
  793. public int getAccessFlagsWithoutSynchronized() {
  794. if (isSynchronized()) {
  795. return modifiers - Modifier.SYNCHRONIZED;
  796. }
  797. return modifiers;
  798. }
  799. public boolean isSynchronized() {
  800. return (modifiers & Modifier.SYNCHRONIZED) != 0;
  801. }
  802. public void setAccessFlags(int newFlags) {
  803. this.modifiers = newFlags;
  804. }
  805. public Type[] getArgumentTypes() {
  806. initialize();
  807. return argumentTypes;
  808. }
  809. public LazyClassGen getEnclosingClass() {
  810. return enclosingClass;
  811. }
  812. public int getMaxLocals() {
  813. return maxLocals;
  814. }
  815. public String getName() {
  816. return name;
  817. }
  818. public String getGenericReturnTypeSignature() {
  819. if (memberView == null) {
  820. return getReturnType().getSignature();
  821. } else {
  822. return memberView.getGenericReturnType().getSignature();
  823. }
  824. }
  825. public Type getReturnType() {
  826. initialize();
  827. return returnType;
  828. }
  829. public void setMaxLocals(int maxLocals) {
  830. this.maxLocals = maxLocals;
  831. }
  832. public InstructionList getBody() {
  833. markAsChanged();
  834. return body;
  835. }
  836. public InstructionList getBodyForPrint() {
  837. return body;
  838. }
  839. public boolean hasBody() {
  840. if (savedMethod != null) {
  841. return savedMethod.getCode() != null;
  842. }
  843. return body != null;
  844. }
  845. public List<Attribute> getAttributes() {
  846. return attributes;
  847. }
  848. public String[] getDeclaredExceptions() {
  849. return declaredExceptions;
  850. }
  851. public String getClassName() {
  852. return enclosingClass.getName();
  853. }
  854. // ---- packing!
  855. public MethodGen pack() {
  856. forceSyntheticForAjcMagicMembers();
  857. // killNops();
  858. int flags = getAccessFlags();
  859. if (enclosingClass.getWorld().isJoinpointSynchronizationEnabled()
  860. && enclosingClass.getWorld().areSynchronizationPointcutsInUse()) {
  861. flags = getAccessFlagsWithoutSynchronized();
  862. }
  863. MethodGen gen = new MethodGen(flags, getReturnType(), getArgumentTypes(), null, // getArgumentNames(),
  864. getName(), getEnclosingClass().getName(), new InstructionList(), getEnclosingClass().getConstantPool());
  865. for (String declaredException : declaredExceptions) {
  866. gen.addException(declaredException);
  867. }
  868. for (Attribute attr : attributes) {
  869. gen.addAttribute(attr);
  870. }
  871. if (newAnnotations != null) {
  872. for (AnnotationAJ element : newAnnotations) {
  873. gen.addAnnotation(new AnnotationGen(((BcelAnnotation) element).getBcelAnnotation(), gen.getConstantPool(), true));
  874. }
  875. }
  876. if (newParameterAnnotations != null) {
  877. for (int i = 0; i < newParameterAnnotations.length; i++) {
  878. AnnotationAJ[] annos = newParameterAnnotations[i];
  879. for (AnnotationAJ anno : annos) {
  880. gen.addParameterAnnotation(i,
  881. new AnnotationGen(((BcelAnnotation) anno).getBcelAnnotation(), gen.getConstantPool(), true));
  882. }
  883. }
  884. }
  885. if (memberView != null && memberView.getAnnotations() != null && memberView.getAnnotations().length != 0) {
  886. AnnotationAJ[] ans = memberView.getAnnotations();
  887. for (AnnotationAJ an : ans) {
  888. AnnotationGen a = ((BcelAnnotation) an).getBcelAnnotation();
  889. gen.addAnnotation(new AnnotationGen(a, gen.getConstantPool(), true));
  890. }
  891. }
  892. if (isSynthetic) {
  893. if (enclosingClass.getWorld().isInJava5Mode()) {
  894. gen.setModifiers(gen.getModifiers() | Constants.ACC_SYNTHETIC);
  895. }
  896. if (!hasAttribute("Synthetic")) {
  897. // belt and braces, do the attribute even on Java 5 in addition to the modifier flag
  898. ConstantPool cpg = gen.getConstantPool();
  899. int index = cpg.addUtf8("Synthetic");
  900. gen.addAttribute(new Synthetic(index, 0, new byte[0], cpg));
  901. }
  902. }
  903. if (hasBody()) {
  904. if (this.enclosingClass.getWorld().shouldFastPackMethods()) {
  905. if (isAdviceMethod() || getName().equals("<clinit>")) {
  906. packBody(gen);
  907. } else {
  908. optimizedPackBody(gen);
  909. }
  910. } else {
  911. packBody(gen);
  912. }
  913. gen.setMaxLocals(true);
  914. gen.setMaxStack();
  915. } else {
  916. gen.setInstructionList(null);
  917. }
  918. return gen;
  919. }
  920. private boolean hasAttribute(String attributeName) {
  921. for (Attribute attr: attributes) {
  922. if (attr.getName().equals(attributeName)) {
  923. return true;
  924. }
  925. }
  926. return false;
  927. }
  928. private void forceSyntheticForAjcMagicMembers() {
  929. if (NameMangler.isSyntheticMethod(getName(), inAspect())) {
  930. makeSynthetic();
  931. }
  932. }
  933. private boolean inAspect() {
  934. BcelObjectType objectType = enclosingClass.getBcelObjectType();
  935. return (objectType == null ? false : objectType.isAspect());
  936. }
  937. public void makeSynthetic() {
  938. isSynthetic = true;
  939. }
  940. private static class LVPosition {
  941. InstructionHandle start = null;
  942. InstructionHandle end = null;
  943. }
  944. /**
  945. * fill the newly created method gen with our body, inspired by InstructionList.copy()
  946. */
  947. public void packBody(MethodGen gen) {
  948. InstructionList fresh = gen.getInstructionList();
  949. Map<InstructionHandle, InstructionHandle> map = copyAllInstructionsExceptRangeInstructionsInto(fresh);
  950. // at this point, no rangeHandles are in fresh. Let's use that...
  951. /*
  952. * Update branch targets and insert various attributes. Insert our exceptionHandlers into a sorted list, so they can be
  953. * added in order later.
  954. */
  955. InstructionHandle oldInstructionHandle = getBody().getStart();
  956. InstructionHandle newInstructionHandle = fresh.getStart();
  957. LinkedList<ExceptionRange> exceptionList = new LinkedList<ExceptionRange>();
  958. Map<LocalVariableTag, LVPosition> localVariables = new HashMap<LocalVariableTag, LVPosition>();
  959. int currLine = -1;
  960. int lineNumberOffset = (fromFilename == null) ? 0 : getEnclosingClass().getSourceDebugExtensionOffset(fromFilename);
  961. while (oldInstructionHandle != null) {
  962. if (map.get(oldInstructionHandle) == null) {
  963. // must be a range instruction since they're the only things we
  964. // didn't copy across
  965. handleRangeInstruction(oldInstructionHandle, exceptionList);
  966. // just increment ih.
  967. oldInstructionHandle = oldInstructionHandle.getNext();
  968. } else {
  969. // assert map.get(ih) == jh
  970. Instruction oldInstruction = oldInstructionHandle.getInstruction();
  971. Instruction newInstruction = newInstructionHandle.getInstruction();
  972. if (oldInstruction instanceof InstructionBranch) {
  973. handleBranchInstruction(map, oldInstruction, newInstruction);
  974. }
  975. // now deal with line numbers
  976. // and store up info for local variables
  977. for (InstructionTargeter targeter : oldInstructionHandle.getTargeters()) {
  978. if (targeter instanceof LineNumberTag) {
  979. int line = ((LineNumberTag) targeter).getLineNumber();
  980. if (line != currLine) {
  981. gen.addLineNumber(newInstructionHandle, line + lineNumberOffset);
  982. currLine = line;
  983. }
  984. } else if (targeter instanceof LocalVariableTag) {
  985. LocalVariableTag lvt = (LocalVariableTag) targeter;
  986. LVPosition p = localVariables.get(lvt);
  987. // If we don't know about it, create a new position and
  988. // store
  989. // If we do know about it - update its end position
  990. if (p == null) {
  991. LVPosition newp = new LVPosition();
  992. newp.start = newp.end = newInstructionHandle;
  993. localVariables.put(lvt, newp);
  994. } else {
  995. p.end = newInstructionHandle;
  996. }
  997. }
  998. }
  999. // now continue
  1000. oldInstructionHandle = oldInstructionHandle.getNext();
  1001. newInstructionHandle = newInstructionHandle.getNext();
  1002. }
  1003. }
  1004. addExceptionHandlers(gen, map, exceptionList);
  1005. if (originalMethodHasLocalVariableTable || enclosingClass
  1006. .getBcelObjectType()
  1007. .getResolvedTypeX()
  1008. .getWorld().generateNewLvts) {
  1009. if (localVariables.size() == 0) {
  1010. // Might be a case of 173978 where around advice on an execution join point
  1011. // has caused everything to be extracted from the method and thus we
  1012. // are left with no local variables, not even the ones for 'this' and
  1013. // parameters passed to the method
  1014. createNewLocalVariables(gen);
  1015. } else {
  1016. addLocalVariables(gen, localVariables);
  1017. }
  1018. }
  1019. // JAVAC adds line number tables (with just one entry) to generated
  1020. // accessor methods - this
  1021. // keeps some tools that rely on finding at least some form of
  1022. // linenumbertable happy.
  1023. // Let's check if we have one - if we don't then let's add one.
  1024. // TODO Could be made conditional on whether line debug info is being
  1025. // produced
  1026. if (gen.getLineNumbers().length == 0) {
  1027. gen.addLineNumber(gen.getInstructionList().getStart(), 1);
  1028. }
  1029. }
  1030. private void createNewLocalVariables(MethodGen gen) {
  1031. gen.removeLocalVariables();
  1032. // ignore <clinit> or <init> for now
  1033. if (!getName().startsWith("<")) {
  1034. int slot = 0;
  1035. InstructionHandle start = gen.getInstructionList().getStart();
  1036. InstructionHandle end = gen.getInstructionList().getEnd();
  1037. // Add a 'this' if non-static
  1038. if (!isStatic()) {
  1039. String cname = this.enclosingClass.getClassName();
  1040. if (cname == null) {
  1041. return; // give up for now
  1042. }
  1043. Type enclosingType = BcelWorld.makeBcelType(UnresolvedType.forName(cname));
  1044. gen.addLocalVariable("this", enclosingType, slot++, start, end);
  1045. }
  1046. // Add entries for the method arguments
  1047. String[] paramNames = (memberView == null ? null : memberView.getParameterNames());
  1048. if (paramNames != null) {
  1049. for (int i = 0; i < argumentTypes.length; i++) {
  1050. String pname = paramNames[i];
  1051. if (pname == null) {
  1052. pname = "arg" + i;
  1053. }
  1054. gen.addLocalVariable(pname, argumentTypes[i], slot, start, end);
  1055. slot += argumentTypes[i].getSize();
  1056. }
  1057. }
  1058. }
  1059. }
  1060. private World getWorld() {
  1061. return enclosingClass.getBcelObjectType().getResolvedTypeX().getWorld();
  1062. }
  1063. /*
  1064. * Optimized packing that does a 'local packing' of the code rather than building a brand new method and packing into it. Only
  1065. * usable when the packing is going to be done just once.
  1066. */
  1067. public void optimizedPackBody(MethodGen gen) {
  1068. InstructionList theBody = getBody();
  1069. InstructionHandle iHandle = theBody.getStart();
  1070. int currLine = -1;
  1071. int lineNumberOffset = (fromFilename == null) ? 0 : getEnclosingClass().getSourceDebugExtensionOffset(fromFilename);
  1072. Map<LocalVariableTag, LVPosition> localVariables = new HashMap<LocalVariableTag, LVPosition>();
  1073. LinkedList<ExceptionRange> exceptionList = new LinkedList<ExceptionRange>();
  1074. Set<InstructionHandle> forDeletion = new HashSet<InstructionHandle>();
  1075. Set<BranchHandle> branchInstructions = new HashSet<BranchHandle>();
  1076. // OPTIMIZE sort out in here: getRange()/insertHandler() and type of
  1077. // exceptionList
  1078. while (iHandle != null) {
  1079. Instruction inst = iHandle.getInstruction();
  1080. // InstructionHandle nextInst = iHandle.getNext();
  1081. // OPTIMIZE remove this instructionhandle as it now points to
  1082. // nowhere?
  1083. if (inst == Range.RANGEINSTRUCTION) {
  1084. Range r = Range.getRange(iHandle);
  1085. if (r instanceof ExceptionRange) {
  1086. ExceptionRange er = (ExceptionRange) r;
  1087. if (er.getStart() == iHandle) {
  1088. if (!er.isEmpty()) {
  1089. // order is important, insert handlers in order of start
  1090. insertHandler(er, exceptionList);
  1091. }
  1092. }
  1093. }
  1094. forDeletion.add(iHandle);
  1095. } else {
  1096. if (inst instanceof InstructionBranch) {
  1097. branchInstructions.add((BranchHandle) iHandle);
  1098. }
  1099. for (InstructionTargeter targeter : iHandle.getTargetersCopy()) {
  1100. if (targeter instanceof LineNumberTag) {
  1101. int line = ((LineNumberTag) targeter).getLineNumber();
  1102. if (line != currLine) {
  1103. gen.addLineNumber(iHandle, line + lineNumberOffset);
  1104. currLine = line;
  1105. }
  1106. } else if (targeter instanceof LocalVariableTag) {
  1107. LocalVariableTag lvt = (LocalVariableTag) targeter;
  1108. LVPosition p = localVariables.get(lvt);
  1109. // If we don't know about it, create a new position
  1110. // and store
  1111. // If we do know about it - update its end position
  1112. if (p == null) {
  1113. LVPosition newp = new LVPosition();
  1114. newp.start = newp.end = iHandle;
  1115. localVariables.put(lvt, newp);
  1116. } else {
  1117. p.end = iHandle;
  1118. }
  1119. }
  1120. }
  1121. }
  1122. iHandle = iHandle.getNext();
  1123. }
  1124. for (BranchHandle branchHandle : branchInstructions) {
  1125. handleBranchInstruction(branchHandle, forDeletion);
  1126. }
  1127. // now add exception handlers
  1128. for (ExceptionRange r : exceptionList) {
  1129. if (r.isEmpty()) {
  1130. continue;
  1131. }
  1132. gen.addExceptionHandler(jumpForward(r.getRealStart(), forDeletion), jumpForward(r.getRealEnd(), forDeletion),
  1133. jumpForward(r.getHandler(), forDeletion),
  1134. (r.getCatchType() == null) ? null : (ObjectType) BcelWorld.makeBcelType(r.getCatchType()));
  1135. }
  1136. for (InstructionHandle handle : forDeletion) {
  1137. try {
  1138. theBody.delete(handle);
  1139. } catch (TargetLostException e) {
  1140. e.printStackTrace();
  1141. }
  1142. }
  1143. gen.setInstructionList(theBody);
  1144. if (originalMethodHasLocalVariableTable || getWorld().generateNewLvts) {
  1145. if (localVariables.size() == 0) {
  1146. // Might be a case of 173978 where around advice on an execution join point
  1147. // has caused everything to be extracted from the method and thus we
  1148. // are left with no local variables, not even the ones for 'this' and
  1149. // parameters passed to the method
  1150. createNewLocalVariables(gen);
  1151. } else {
  1152. addLocalVariables(gen, localVariables);
  1153. }
  1154. }
  1155. // JAVAC adds line number tables (with just one entry) to generated
  1156. // accessor methods - this
  1157. // keeps some tools that rely on finding at least some form of
  1158. // linenumbertable happy.
  1159. // Let's check if we have one - if we don't then let's add one.
  1160. // TODO Could be made conditional on whether line debug info is being
  1161. // produced
  1162. if (gen.getLineNumbers().length == 0) {
  1163. gen.addLineNumber(gen.getInstructionList().getStart(), 1);
  1164. }
  1165. wasPackedOptimally = true;
  1166. }
  1167. private void addLocalVariables(MethodGen gen, Map<LocalVariableTag, LVPosition> localVariables) {
  1168. // now add local variables
  1169. gen.removeLocalVariables();
  1170. // this next iteration _might_ be overkill, but we had problems with
  1171. // bcel before with duplicate local variables. Now that we're patching
  1172. // bcel we should be able to do without it if we're paranoid enough
  1173. // through the rest of the compiler.
  1174. InstructionHandle methodStart = gen.getInstructionList().getStart();
  1175. InstructionHandle methodEnd = gen.getInstructionList().getEnd();
  1176. // Determine how many 'slots' are used by parameters to the method.
  1177. // Then below we can determine if a local variable is a parameter variable, if it is
  1178. // we force its range to from the method start (as it may have been shuffled down
  1179. // due to insertion of advice like cflow entry)
  1180. int paramSlots = gen.isStatic() ? 0 : 1;
  1181. Type[] argTypes = gen.getArgumentTypes();
  1182. if (argTypes != null) {
  1183. for (Type argType : argTypes) {
  1184. if (argType.getSize() == 2) {
  1185. paramSlots += 2;
  1186. } else {
  1187. paramSlots += 1;
  1188. }
  1189. }
  1190. }
  1191. if (!this.enclosingClass.getWorld().generateNewLvts) {
  1192. // Here the generateNewLvts option is used to control "Do not damage unusually positioned local
  1193. // variables that represent method parameters". Strictly speaking local variables that represent
  1194. // method parameters effectively have a bytecode range from 0..end_of_method - however some
  1195. // tools generate bytecode that specifies a compressed range. The code below would normally
  1196. // extend the parameter local variables to cover the full method but by setting paramSlots to -1
  1197. // here we cause the code below to avoid modifying any local vars that represent method
  1198. // parameters.
  1199. paramSlots = -1;
  1200. }
  1201. Map<InstructionHandle, Set<Integer>> duplicatedLocalMap = new HashMap<InstructionHandle, Set<Integer>>();
  1202. for (LocalVariableTag tag : localVariables.keySet()) {
  1203. // have we already added one with the same slot number and start
  1204. // location?
  1205. // if so, just continue.
  1206. LVPosition lvpos = localVariables.get(tag);
  1207. InstructionHandle start = (tag.getSlot() < paramSlots ? methodStart : lvpos.start);
  1208. InstructionHandle end = (tag.getSlot() < paramSlots ? methodEnd : lvpos.end);
  1209. Set<Integer> slots = duplicatedLocalMap.get(start);
  1210. if (slots == null) {
  1211. slots = new HashSet<Integer>();
  1212. duplicatedLocalMap.put(start, slots);
  1213. } else if (slots.contains(new Integer(tag.getSlot()))) {
  1214. // we already have a var starting at this tag with this slot
  1215. continue;
  1216. }
  1217. slots.add(Integer.valueOf(tag.getSlot()));
  1218. Type t = tag.getRealType();
  1219. if (t == null) {
  1220. t = BcelWorld.makeBcelType(UnresolvedType.forSignature(tag.getType()));
  1221. }
  1222. gen.addLocalVariable(tag.getName(), t, tag.getSlot(), start, end);
  1223. }
  1224. }
  1225. private void addExceptionHandlers(MethodGen gen, Map<InstructionHandle, InstructionHandle> map,
  1226. LinkedList<ExceptionRange> exnList) {
  1227. // now add exception handlers
  1228. for (ExceptionRange r : exnList) {
  1229. if (r.isEmpty()) {
  1230. continue;
  1231. }
  1232. InstructionHandle rMappedStart = remap(r.getRealStart(), map);
  1233. InstructionHandle rMappedEnd = remap(r.getRealEnd(), map);
  1234. InstructionHandle rMappedHandler = remap(r.getHandler(), map);
  1235. gen.addExceptionHandler(rMappedStart, rMappedEnd, rMappedHandler, (r.getCatchType() == null) ? null
  1236. : (ObjectType) BcelWorld.makeBcelType(r.getCatchType()));
  1237. }
  1238. }
  1239. private void handleBranchInstruction(Map<InstructionHandle, InstructionHandle> map, Instruction oldInstruction,
  1240. Instruction newInstruction) {
  1241. InstructionBranch oldBranchInstruction = (InstructionBranch) oldInstruction;
  1242. InstructionBranch newBranchInstruction = (InstructionBranch) newInstruction;
  1243. InstructionHandle oldTarget = oldBranchInstruction.getTarget(); // old
  1244. // target
  1245. // New target is in hash map
  1246. newBranchInstruction.setTarget(remap(oldTarget, map));
  1247. if (oldBranchInstruction instanceof InstructionSelect) {
  1248. // Either LOOKUPSWITCH or TABLESWITCH
  1249. InstructionHandle[] oldTargets = ((InstructionSelect) oldBranchInstruction).getTargets();
  1250. InstructionHandle[] newTargets = ((InstructionSelect) newBranchInstruction).getTargets();
  1251. for (int k = oldTargets.length - 1; k >= 0; k--) {
  1252. // Update all targets
  1253. newTargets[k] = remap(oldTargets[k], map);
  1254. newTargets[k].addTargeter(newBranchInstruction);
  1255. }
  1256. }
  1257. }
  1258. private InstructionHandle jumpForward(InstructionHandle t, Set<InstructionHandle> handlesForDeletion) {
  1259. InstructionHandle target = t;
  1260. if (handlesForDeletion.contains(target)) {
  1261. do {
  1262. target = target.getNext();
  1263. } while (handlesForDeletion.contains(target));
  1264. }
  1265. return target;
  1266. }
  1267. /**
  1268. * Process a branch instruction with respect to instructions that are about to be deleted. If the target for the branch is a
  1269. * candidate for deletion, move it to the next valid instruction after the deleted target.
  1270. */
  1271. private void handleBranchInstruction(BranchHandle branchHandle, Set<InstructionHandle> handlesForDeletion) {
  1272. InstructionBranch branchInstruction = (InstructionBranch) branchHandle.getInstruction();
  1273. InstructionHandle target = branchInstruction.getTarget(); // old target
  1274. if (handlesForDeletion.contains(target)) {
  1275. do {
  1276. target = target.getNext();
  1277. } while (handlesForDeletion.contains(target));
  1278. branchInstruction.setTarget(target);
  1279. }
  1280. if (branchInstruction instanceof InstructionSelect) {
  1281. // Either LOOKUPSWITCH or TABLESWITCH
  1282. InstructionSelect iSelect = (InstructionSelect) branchInstruction;
  1283. InstructionHandle[] targets = iSelect.getTargets();
  1284. for (int k = targets.length - 1; k >= 0; k--) {
  1285. InstructionHandle oneTarget = targets[k];
  1286. if (handlesForDeletion.contains(oneTarget)) {
  1287. do {
  1288. oneTarget = oneTarget.getNext();
  1289. } while (handlesForDeletion.contains(oneTarget));
  1290. iSelect.setTarget(k, oneTarget);
  1291. oneTarget.addTargeter(branchInstruction);
  1292. }
  1293. }
  1294. }
  1295. }
  1296. private void handleRangeInstruction(InstructionHandle ih, LinkedList<ExceptionRange> exnList) {
  1297. // we're a range instruction
  1298. Range r = Range.getRange(ih);
  1299. if (r instanceof ExceptionRange) {
  1300. ExceptionRange er = (ExceptionRange) r;
  1301. if (er.getStart() == ih) {
  1302. // System.err.println("er " + er);
  1303. if (!er.isEmpty()) {
  1304. // order is important, insert handlers in order of start
  1305. insertHandler(er, exnList);
  1306. }
  1307. }
  1308. } else {
  1309. // we must be a shadow range or something equally useless,
  1310. // so forget about doing anything
  1311. }
  1312. }
  1313. /*
  1314. * Make copies of all instructions, append them to the new list and associate old instruction references with the new ones,
  1315. * i.e., a 1:1 mapping.
  1316. */
  1317. private Map<InstructionHandle, InstructionHandle> copyAllInstructionsExceptRangeInstructionsInto(InstructionList intoList) {
  1318. Map<InstructionHandle, InstructionHandle> map = new HashMap<InstructionHandle, InstructionHandle>();
  1319. for (InstructionHandle ih = getBody().getStart(); ih != null; ih = ih.getNext()) {
  1320. if (Range.isRangeHandle(ih)) {
  1321. continue;
  1322. }
  1323. Instruction inst = ih.getInstruction();
  1324. Instruction copy = Utility.copyInstruction(inst);
  1325. if (copy instanceof InstructionBranch) {
  1326. map.put(ih, intoList.append((InstructionBranch) copy));
  1327. } else {
  1328. map.put(ih, intoList.append(copy));
  1329. }
  1330. }
  1331. return map;
  1332. }
  1333. /**
  1334. * This procedure should not currently be used.
  1335. */
  1336. // public void killNops() {
  1337. // InstructionHandle curr = body.getStart();
  1338. // while (true) {
  1339. // if (curr == null) break;
  1340. // InstructionHandle next = curr.getNext();
  1341. // if (curr.getInstruction() instanceof NOP) {
  1342. // InstructionTargeter[] targeters = curr.getTargeters();
  1343. // if (targeters != null) {
  1344. // for (int i = 0, len = targeters.length; i < len; i++) {
  1345. // InstructionTargeter targeter = targeters[i];
  1346. // targeter.updateTarget(curr, next);
  1347. // }
  1348. // }
  1349. // try {
  1350. // body.delete(curr);
  1351. // } catch (TargetLostException e) {
  1352. // }
  1353. // }
  1354. // curr = next;
  1355. // }
  1356. // }
  1357. // private static InstructionHandle fNext(InstructionHandle ih) {
  1358. // while (true) {
  1359. // if (ih.getInstruction()==Range.RANGEINSTRUCTION) ih = ih.getNext();
  1360. // else return ih;
  1361. // }
  1362. // }
  1363. private static InstructionHandle remap(InstructionHandle handle, Map<InstructionHandle, InstructionHandle> map) {
  1364. while (true) {
  1365. InstructionHandle ret = map.get(handle);
  1366. if (ret == null) {
  1367. handle = handle.getNext();
  1368. } else {
  1369. return ret;
  1370. }
  1371. }
  1372. }
  1373. // Update to all these comments, ASC 11-01-2005
  1374. // The right thing to do may be to do more with priorities as
  1375. // we create new exception handlers, but that is a relatively
  1376. // complex task. In the meantime, just taking account of the
  1377. // priority here enables a couple of bugs to be fixed to do
  1378. // with using return or break in code that contains a finally
  1379. // block (pr78021,pr79554).
  1380. // exception ordering.
  1381. // What we should be doing is dealing with priority inversions way earlier
  1382. // than we are
  1383. // and counting on the tree structure. In which case, the below code is in
  1384. // fact right.
  1385. // XXX THIS COMMENT BELOW IS CURRENTLY WRONG.
  1386. // An exception A preceeds an exception B in the exception table iff:
  1387. // * A and B were in the original method, and A preceeded B in the original
  1388. // exception table
  1389. // * If A has a higher priority than B, than it preceeds B.
  1390. // * If A and B have the same priority, then the one whose START happens
  1391. // EARLIEST has LEAST priority.
  1392. // in short, the outermost exception has least priority.
  1393. // we implement this with a LinkedList. We could possibly implement this
  1394. // with a java.util.SortedSet,
  1395. // but I don't trust the only implementation, TreeSet, to do the right
  1396. // thing.
  1397. /* private */static void insertHandler(ExceptionRange fresh, LinkedList<ExceptionRange> l) {
  1398. // Old implementation, simply: l.add(0,fresh);
  1399. for (ListIterator<ExceptionRange> iter = l.listIterator(); iter.hasNext();) {
  1400. ExceptionRange r = iter.next();
  1401. // int freal = fresh.getRealStart().getPosition();
  1402. // int rreal = r.getRealStart().getPosition();
  1403. if (fresh.getPriority() >= r.getPriority()) {
  1404. iter.previous();
  1405. iter.add(fresh);
  1406. return;
  1407. }
  1408. }
  1409. // we have reached the end
  1410. l.add(fresh);
  1411. }
  1412. public boolean isPrivate() {
  1413. return Modifier.isPrivate(getAccessFlags());
  1414. }
  1415. public boolean isProtected() {
  1416. return Modifier.isProtected(getAccessFlags());
  1417. }
  1418. public boolean isDefault() {
  1419. return !(isProtected() || isPrivate() || isPublic());
  1420. }
  1421. public boolean isPublic() {
  1422. return Modifier.isPublic(getAccessFlags());
  1423. }
  1424. // ----
  1425. /**
  1426. * A good body is a body with the following properties:
  1427. *
  1428. * <ul>
  1429. * <li>For each branch instruction S in body, target T of S is in body.
  1430. * <li>For each branch instruction S in body, target T of S has S as a targeter.
  1431. * <li>For each instruction T in body, for each branch instruction S that is a targeter of T, S is in body.
  1432. * <li>For each non-range-handle instruction T in body, for each instruction S that is a targeter of T, S is either a branch
  1433. * instruction, an exception range or a tag
  1434. * <li>For each range-handle instruction T in body, there is exactly one targeter S that is a range.
  1435. * <li>For each range-handle instruction T in body, the range R targeting T is in body.
  1436. * <li>For each instruction T in body, for each exception range R targeting T, R is in body.
  1437. * <li>For each exception range R in body, let T := R.handler. T is in body, and R is one of T's targeters
  1438. * <li>All ranges are properly nested: For all ranges Q and R, if Q.start preceeds R.start, then R.end preceeds Q.end.
  1439. * </ul>
  1440. *
  1441. * Where the shorthand "R is in body" means "R.start is in body, R.end is in body, and any InstructionHandle stored in a field
  1442. * of R (such as an exception handle) is in body".
  1443. */
  1444. public void assertGoodBody() {
  1445. if (true) {
  1446. return; // only enable for debugging
  1447. }
  1448. assertGoodBody(getBody(), toString());
  1449. }
  1450. public static void assertGoodBody(InstructionList il, String from) {
  1451. if (true) {
  1452. return; // only to be enabled for debugging
  1453. }
  1454. // if (il == null) {
  1455. // return;
  1456. // }
  1457. // Set body = new HashSet();
  1458. // Stack<Range> ranges = new Stack<Range>();
  1459. // for (InstructionHandle ih = il.getStart(); ih != null; ih = ih.getNext()) {
  1460. // body.add(ih);
  1461. // if (ih.getInstruction() instanceof InstructionBranch) {
  1462. // body.add(ih.getInstruction());
  1463. // }
  1464. // }
  1465. //
  1466. // for (InstructionHandle ih = il.getStart(); ih != null; ih = ih.getNext()) {
  1467. // assertGoodHandle(ih, body, ranges, from);
  1468. // Iterator<InstructionTargeter> tIter = ih.getTargeters().iterator();
  1469. // while (tIter.hasNext()) {
  1470. // assertGoodTargeter(tIter.next(), ih, body, from);
  1471. // }
  1472. // }
  1473. }
  1474. // private static void assertGoodHandle(InstructionHandle ih, Set body, Stack<Range> ranges, String from) {
  1475. // Instruction inst = ih.getInstruction();
  1476. // if ((inst instanceof InstructionBranch) ^ (ih instanceof BranchHandle)) {
  1477. // throw new BCException("bad instruction/handle pair in " + from);
  1478. // }
  1479. // if (Range.isRangeHandle(ih)) {
  1480. // assertGoodRangeHandle(ih, body, ranges, from);
  1481. // } else if (inst instanceof InstructionBranch) {
  1482. // assertGoodBranchInstruction((BranchHandle) ih, (InstructionBranch) inst, body, ranges, from);
  1483. // }
  1484. // }
  1485. // private static void assertGoodBranchInstruction(BranchHandle ih, InstructionBranch inst, Set body, Stack<Range> ranges,
  1486. // String from) {
  1487. // if (ih.getTarget() != inst.getTarget()) {
  1488. // throw new BCException("bad branch instruction/handle pair in " + from);
  1489. // }
  1490. // InstructionHandle target = ih.getTarget();
  1491. // assertInBody(target, body, from);
  1492. // assertTargetedBy(target, inst, from);
  1493. // if (inst instanceof InstructionSelect) {
  1494. // InstructionSelect sel = (InstructionSelect) inst;
  1495. // InstructionHandle[] itargets = sel.getTargets();
  1496. // for (int k = itargets.length - 1; k >= 0; k--) {
  1497. // assertInBody(itargets[k], body, from);
  1498. // assertTargetedBy(itargets[k], inst, from);
  1499. // }
  1500. // }
  1501. // }
  1502. /** ih is an InstructionHandle or a BranchInstruction */
  1503. // private static void assertInBody(Object ih, Set body, String from) {
  1504. // if (!body.contains(ih)) {
  1505. // throw new BCException("thing not in body in " + from);
  1506. // }
  1507. // }
  1508. // private static void assertGoodRangeHandle(InstructionHandle ih, Set body, Stack ranges, String from) {
  1509. // Range r = getRangeAndAssertExactlyOne(ih, from);
  1510. // assertGoodRange(r, body, from);
  1511. // if (r.getStart() == ih) {
  1512. // ranges.push(r);
  1513. // } else if (r.getEnd() == ih) {
  1514. // if (ranges.peek() != r) {
  1515. // throw new BCException("bad range inclusion in " + from);
  1516. // }
  1517. // ranges.pop();
  1518. // }
  1519. // }
  1520. // private static void assertGoodRange(Range r, Set body, String from) {
  1521. // assertInBody(r.getStart(), body, from);
  1522. // assertRangeHandle(r.getStart(), from);
  1523. // assertTargetedBy(r.getStart(), r, from);
  1524. //
  1525. // assertInBody(r.getEnd(), body, from);
  1526. // assertRangeHandle(r.getEnd(), from);
  1527. // assertTargetedBy(r.getEnd(), r, from);
  1528. //
  1529. // if (r instanceof ExceptionRange) {
  1530. // ExceptionRange er = (ExceptionRange) r;
  1531. // assertInBody(er.getHandler(), body, from);
  1532. // assertTargetedBy(er.getHandler(), r, from);
  1533. // }
  1534. // }
  1535. // private static void assertRangeHandle(InstructionHandle ih, String from) {
  1536. // if (!Range.isRangeHandle(ih)) {
  1537. // throw new BCException("bad range handle " + ih + " in " + from);
  1538. // }
  1539. // }
  1540. private static void assertTargetedBy(InstructionHandle target, InstructionTargeter targeter, String from) {
  1541. for (InstructionTargeter instructionTargeter : target.getTargeters()) {
  1542. if (instructionTargeter == targeter) {
  1543. return;
  1544. }
  1545. }
  1546. throw new RuntimeException("bad targeting relationship in " + from);
  1547. }
  1548. private static void assertTargets(InstructionTargeter targeter, InstructionHandle target, String from) {
  1549. if (targeter instanceof Range) {
  1550. Range r = (Range) targeter;
  1551. if (r.getStart() == target || r.getEnd() == target) {
  1552. return;
  1553. }
  1554. if (r instanceof ExceptionRange) {
  1555. if (((ExceptionRange) r).getHandler() == target) {
  1556. return;
  1557. }
  1558. }
  1559. } else if (targeter instanceof InstructionBranch) {
  1560. InstructionBranch bi = (InstructionBranch) targeter;
  1561. if (bi.getTarget() == target) {
  1562. return;
  1563. }
  1564. if (targeter instanceof InstructionSelect) {
  1565. InstructionSelect sel = (InstructionSelect) targeter;
  1566. InstructionHandle[] itargets = sel.getTargets();
  1567. for (int k = itargets.length - 1; k >= 0; k--) {
  1568. if (itargets[k] == target) {
  1569. return;
  1570. }
  1571. }
  1572. }
  1573. } else if (targeter instanceof Tag) {
  1574. return;
  1575. }
  1576. throw new BCException(targeter + " doesn't target " + target + " in " + from);
  1577. }
  1578. private static Range getRangeAndAssertExactlyOne(InstructionHandle ih, String from) {
  1579. Range ret = null;
  1580. Iterator<InstructionTargeter> tIter = ih.getTargeters().iterator();
  1581. if (!tIter.hasNext()) {
  1582. throw new BCException("range handle with no range in " + from);
  1583. }
  1584. while (tIter.hasNext()) {
  1585. InstructionTargeter ts = tIter.next();
  1586. if (ts instanceof Range) {
  1587. if (ret != null) {
  1588. throw new BCException("range handle with multiple ranges in " + from);
  1589. }
  1590. ret = (Range) ts;
  1591. }
  1592. }
  1593. if (ret == null) {
  1594. throw new BCException("range handle with no range in " + from);
  1595. }
  1596. return ret;
  1597. }
  1598. // private static void assertGoodTargeter(InstructionTargeter t, InstructionHandle ih, Set body, String from) {
  1599. // assertTargets(t, ih, from);
  1600. // if (t instanceof Range) {
  1601. // assertGoodRange((Range) t, body, from);
  1602. // } else if (t instanceof InstructionBranch) {
  1603. // assertInBody(t, body, from);
  1604. // }
  1605. // }
  1606. // ----
  1607. boolean isAdviceMethod() {
  1608. if (memberView == null) {
  1609. return false;
  1610. }
  1611. return memberView.getAssociatedShadowMunger() != null;
  1612. }
  1613. boolean isAjSynthetic() {
  1614. if (memberView == null) {
  1615. return true;
  1616. }
  1617. return memberView.isAjSynthetic();
  1618. }
  1619. boolean isSynthetic() {
  1620. if (memberView == null) {
  1621. return false;
  1622. }
  1623. return memberView.isSynthetic();
  1624. }
  1625. public ISourceLocation getSourceLocation() {
  1626. if (memberView != null) {
  1627. return memberView.getSourceLocation();
  1628. }
  1629. return null;
  1630. }
  1631. public AjAttribute.EffectiveSignatureAttribute getEffectiveSignature() {
  1632. // if (memberView == null) return null;
  1633. if (effectiveSignature != null) {
  1634. return effectiveSignature;
  1635. }
  1636. return memberView.getEffectiveSignature();
  1637. }
  1638. public void setEffectiveSignature(ResolvedMember member, Shadow.Kind kind, boolean shouldWeave) {
  1639. this.effectiveSignature = new AjAttribute.EffectiveSignatureAttribute(member, kind, shouldWeave);
  1640. }
  1641. public String getSignature() {
  1642. if (memberView != null) {
  1643. return memberView.getSignature();
  1644. }
  1645. return MemberImpl.typesToSignature(BcelWorld.fromBcel(getReturnType()), BcelWorld.fromBcel(getArgumentTypes()), false);
  1646. }
  1647. public String getParameterSignature() {
  1648. if (memberView != null) {
  1649. return memberView.getParameterSignature();
  1650. }
  1651. return MemberImpl.typesToSignature(BcelWorld.fromBcel(getArgumentTypes()));
  1652. }
  1653. public BcelMethod getMemberView() {
  1654. return memberView;
  1655. }
  1656. public void forcePublic() {
  1657. markAsChanged();
  1658. modifiers = Utility.makePublic(modifiers);
  1659. }
  1660. public boolean getCanInline() {
  1661. return canInline;
  1662. }
  1663. public void setCanInline(boolean canInline) {
  1664. this.canInline = canInline;
  1665. }
  1666. public void addAttribute(Attribute attribute) {
  1667. attributes.add(attribute);
  1668. }
  1669. public String toTraceString() {
  1670. return toShortString();
  1671. }
  1672. public ConstantPool getConstantPool() {
  1673. return enclosingClass.getConstantPool();
  1674. }
  1675. public static boolean isConstructor(LazyMethodGen aMethod) {
  1676. return aMethod.getName().equals("<init>");
  1677. }
  1678. }