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.

LazyMethodGen.java 61KB

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