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.

CtBehavior.java 44KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213
  1. /*
  2. * Javassist, a Java-bytecode translator toolkit.
  3. * Copyright (C) 1999- Shigeru Chiba. All Rights Reserved.
  4. *
  5. * The contents of this file are subject to the Mozilla Public License Version
  6. * 1.1 (the "License"); you may not use this file except in compliance with
  7. * the License. Alternatively, the contents of this file may be used under
  8. * the terms of the GNU Lesser General Public License Version 2.1 or later,
  9. * or the Apache License Version 2.0.
  10. *
  11. * Software distributed under the License is distributed on an "AS IS" basis,
  12. * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  13. * for the specific language governing rights and limitations under the
  14. * License.
  15. */
  16. package javassist;
  17. import javassist.bytecode.*;
  18. import javassist.compiler.Javac;
  19. import javassist.compiler.CompileError;
  20. import javassist.expr.ExprEditor;
  21. /**
  22. * <code>CtBehavior</code> represents a method, a constructor,
  23. * or a static constructor (class initializer).
  24. * It is the abstract super class of
  25. * <code>CtMethod</code> and <code>CtConstructor</code>.
  26. *
  27. * <p>To directly read or modify bytecode, obtain <code>MethodInfo</code>
  28. * objects.
  29. *
  30. * @see #getMethodInfo()
  31. */
  32. public abstract class CtBehavior extends CtMember {
  33. protected MethodInfo methodInfo;
  34. protected CtBehavior(CtClass clazz, MethodInfo minfo) {
  35. super(clazz);
  36. methodInfo = minfo;
  37. }
  38. /**
  39. * @param isCons true if this is a constructor.
  40. */
  41. void copy(CtBehavior src, boolean isCons, ClassMap map)
  42. throws CannotCompileException
  43. {
  44. CtClass declaring = declaringClass;
  45. MethodInfo srcInfo = src.methodInfo;
  46. CtClass srcClass = src.getDeclaringClass();
  47. ConstPool cp = declaring.getClassFile2().getConstPool();
  48. map = new ClassMap(map);
  49. map.put(srcClass.getName(), declaring.getName());
  50. try {
  51. boolean patch = false;
  52. CtClass srcSuper = srcClass.getSuperclass();
  53. CtClass destSuper = declaring.getSuperclass();
  54. String destSuperName = null;
  55. if (srcSuper != null && destSuper != null) {
  56. String srcSuperName = srcSuper.getName();
  57. destSuperName = destSuper.getName();
  58. if (!srcSuperName.equals(destSuperName))
  59. if (srcSuperName.equals(CtClass.javaLangObject))
  60. patch = true;
  61. else
  62. map.putIfNone(srcSuperName, destSuperName);
  63. }
  64. // a stack map table is copied from srcInfo.
  65. methodInfo = new MethodInfo(cp, srcInfo.getName(), srcInfo, map);
  66. if (isCons && patch)
  67. methodInfo.setSuperclass(destSuperName);
  68. }
  69. catch (NotFoundException e) {
  70. throw new CannotCompileException(e);
  71. }
  72. catch (BadBytecode e) {
  73. throw new CannotCompileException(e);
  74. }
  75. }
  76. protected void extendToString(StringBuffer buffer) {
  77. buffer.append(' ');
  78. buffer.append(getName());
  79. buffer.append(' ');
  80. buffer.append(methodInfo.getDescriptor());
  81. }
  82. /**
  83. * Returns the method or constructor name followed by parameter types
  84. * such as <code>javassist.CtBehavior.stBody(String)</code>.
  85. *
  86. * @since 3.5
  87. */
  88. public abstract String getLongName();
  89. /**
  90. * Returns the <code>MethodInfo</code> representing this method/constructor in the
  91. * class file.
  92. *
  93. * <p>If you modify the bytecode through the returned
  94. * <code>MethodInfo</code> object, you might have to explicitly
  95. * rebuild a stack map table. Javassist does not automatically
  96. * rebuild it for avoiding unnecessary rebuilding.
  97. *
  98. * @see javassist.bytecode.MethodInfo#rebuildStackMap(ClassPool)
  99. */
  100. public MethodInfo getMethodInfo() {
  101. declaringClass.checkModify();
  102. return methodInfo;
  103. }
  104. /**
  105. * Returns the <code>MethodInfo</code> representing the method/constructor in the
  106. * class file (read only).
  107. * Normal applications do not need calling this method. Use
  108. * <code>getMethodInfo()</code>.
  109. *
  110. * <p>The <code>MethodInfo</code> object obtained by this method
  111. * is read only. Changes to this object might not be reflected
  112. * on a class file generated by <code>toBytecode()</code>,
  113. * <code>toClass()</code>, etc in <code>CtClass</code>.
  114. *
  115. * <p>This method is available even if the <code>CtClass</code>
  116. * containing this method is frozen. However, if the class is
  117. * frozen, the <code>MethodInfo</code> might be also pruned.
  118. *
  119. * @see #getMethodInfo()
  120. * @see CtClass#isFrozen()
  121. * @see CtClass#prune()
  122. */
  123. public MethodInfo getMethodInfo2() { return methodInfo; }
  124. /**
  125. * Obtains the modifiers of the method/constructor.
  126. *
  127. * @return modifiers encoded with
  128. * <code>javassist.Modifier</code>.
  129. * @see Modifier
  130. */
  131. public int getModifiers() {
  132. return AccessFlag.toModifier(methodInfo.getAccessFlags());
  133. }
  134. /**
  135. * Sets the encoded modifiers of the method/constructor.
  136. *
  137. * <p>Changing the modifiers may cause a problem.
  138. * For example, if a non-static method is changed to static,
  139. * the method will be rejected by the bytecode verifier.
  140. *
  141. * @see Modifier
  142. */
  143. public void setModifiers(int mod) {
  144. declaringClass.checkModify();
  145. methodInfo.setAccessFlags(AccessFlag.of(mod));
  146. }
  147. /**
  148. * Returns true if the class has the specified annotation class.
  149. *
  150. * @param clz the annotation class.
  151. * @return <code>true</code> if the annotation is found,
  152. * otherwise <code>false</code>.
  153. * @since 3.11
  154. */
  155. public boolean hasAnnotation(Class clz) {
  156. MethodInfo mi = getMethodInfo2();
  157. AnnotationsAttribute ainfo = (AnnotationsAttribute)
  158. mi.getAttribute(AnnotationsAttribute.invisibleTag);
  159. AnnotationsAttribute ainfo2 = (AnnotationsAttribute)
  160. mi.getAttribute(AnnotationsAttribute.visibleTag);
  161. return CtClassType.hasAnnotationType(clz,
  162. getDeclaringClass().getClassPool(),
  163. ainfo, ainfo2);
  164. }
  165. /**
  166. * Returns the annotation if the class has the specified annotation class.
  167. * For example, if an annotation <code>@Author</code> is associated
  168. * with this method/constructor, an <code>Author</code> object is returned.
  169. * The member values can be obtained by calling methods on
  170. * the <code>Author</code> object.
  171. *
  172. * @param clz the annotation class.
  173. * @return the annotation if found, otherwise <code>null</code>.
  174. * @since 3.11
  175. */
  176. public Object getAnnotation(Class clz) throws ClassNotFoundException {
  177. MethodInfo mi = getMethodInfo2();
  178. AnnotationsAttribute ainfo = (AnnotationsAttribute)
  179. mi.getAttribute(AnnotationsAttribute.invisibleTag);
  180. AnnotationsAttribute ainfo2 = (AnnotationsAttribute)
  181. mi.getAttribute(AnnotationsAttribute.visibleTag);
  182. return CtClassType.getAnnotationType(clz,
  183. getDeclaringClass().getClassPool(),
  184. ainfo, ainfo2);
  185. }
  186. /**
  187. * Returns the annotations associated with this method or constructor.
  188. *
  189. * @return an array of annotation-type objects.
  190. * @see #getAvailableAnnotations()
  191. * @since 3.1
  192. */
  193. public Object[] getAnnotations() throws ClassNotFoundException {
  194. return getAnnotations(false);
  195. }
  196. /**
  197. * Returns the annotations associated with this method or constructor.
  198. * If any annotations are not on the classpath, they are not included
  199. * in the returned array.
  200. *
  201. * @return an array of annotation-type objects.
  202. * @see #getAnnotations()
  203. * @since 3.3
  204. */
  205. public Object[] getAvailableAnnotations(){
  206. try{
  207. return getAnnotations(true);
  208. }
  209. catch (ClassNotFoundException e){
  210. throw new RuntimeException("Unexpected exception", e);
  211. }
  212. }
  213. private Object[] getAnnotations(boolean ignoreNotFound)
  214. throws ClassNotFoundException
  215. {
  216. MethodInfo mi = getMethodInfo2();
  217. AnnotationsAttribute ainfo = (AnnotationsAttribute)
  218. mi.getAttribute(AnnotationsAttribute.invisibleTag);
  219. AnnotationsAttribute ainfo2 = (AnnotationsAttribute)
  220. mi.getAttribute(AnnotationsAttribute.visibleTag);
  221. return CtClassType.toAnnotationType(ignoreNotFound,
  222. getDeclaringClass().getClassPool(),
  223. ainfo, ainfo2);
  224. }
  225. /**
  226. * Returns the parameter annotations associated with this method or constructor.
  227. *
  228. * @return an array of annotation-type objects. The length of the returned array is
  229. * equal to the number of the formal parameters. If each parameter has no
  230. * annotation, the elements of the returned array are empty arrays.
  231. *
  232. * @see #getAvailableParameterAnnotations()
  233. * @see #getAnnotations()
  234. * @since 3.1
  235. */
  236. public Object[][] getParameterAnnotations() throws ClassNotFoundException {
  237. return getParameterAnnotations(false);
  238. }
  239. /**
  240. * Returns the parameter annotations associated with this method or constructor.
  241. * If any annotations are not on the classpath, they are not included in the
  242. * returned array.
  243. *
  244. * @return an array of annotation-type objects. The length of the returned array is
  245. * equal to the number of the formal parameters. If each parameter has no
  246. * annotation, the elements of the returned array are empty arrays.
  247. *
  248. * @see #getParameterAnnotations()
  249. * @see #getAvailableAnnotations()
  250. * @since 3.3
  251. */
  252. public Object[][] getAvailableParameterAnnotations(){
  253. try {
  254. return getParameterAnnotations(true);
  255. }
  256. catch(ClassNotFoundException e) {
  257. throw new RuntimeException("Unexpected exception", e);
  258. }
  259. }
  260. Object[][] getParameterAnnotations(boolean ignoreNotFound)
  261. throws ClassNotFoundException
  262. {
  263. MethodInfo mi = getMethodInfo2();
  264. ParameterAnnotationsAttribute ainfo = (ParameterAnnotationsAttribute)
  265. mi.getAttribute(ParameterAnnotationsAttribute.invisibleTag);
  266. ParameterAnnotationsAttribute ainfo2 = (ParameterAnnotationsAttribute)
  267. mi.getAttribute(ParameterAnnotationsAttribute.visibleTag);
  268. return CtClassType.toAnnotationType(ignoreNotFound,
  269. getDeclaringClass().getClassPool(),
  270. ainfo, ainfo2, mi);
  271. }
  272. /**
  273. * Obtains parameter types of this method/constructor.
  274. */
  275. public CtClass[] getParameterTypes() throws NotFoundException {
  276. return Descriptor.getParameterTypes(methodInfo.getDescriptor(),
  277. declaringClass.getClassPool());
  278. }
  279. /**
  280. * Obtains the type of the returned value.
  281. */
  282. CtClass getReturnType0() throws NotFoundException {
  283. return Descriptor.getReturnType(methodInfo.getDescriptor(),
  284. declaringClass.getClassPool());
  285. }
  286. /**
  287. * Returns the method signature (the parameter types
  288. * and the return type).
  289. * The method signature is represented by a character string
  290. * called method descriptor, which is defined in the JVM specification.
  291. * If two methods/constructors have
  292. * the same parameter types
  293. * and the return type, <code>getSignature()</code> returns the
  294. * same string (the return type of constructors is <code>void</code>).
  295. *
  296. * <p>Note that the returned string is not the type signature
  297. * contained in the <code>SignatureAttirbute</code>. It is
  298. * a descriptor.
  299. *
  300. * @see javassist.bytecode.Descriptor
  301. * @see #getGenericSignature()
  302. */
  303. public String getSignature() {
  304. return methodInfo.getDescriptor();
  305. }
  306. /**
  307. * Returns the generic signature of the method.
  308. * It represents parameter types including type variables.
  309. *
  310. * @see SignatureAttribute#toMethodSignature(String)
  311. * @since 3.17
  312. */
  313. public String getGenericSignature() {
  314. SignatureAttribute sa
  315. = (SignatureAttribute)methodInfo.getAttribute(SignatureAttribute.tag);
  316. return sa == null ? null : sa.getSignature();
  317. }
  318. /**
  319. * Set the generic signature of the method.
  320. * It represents parameter types including type variables.
  321. * See {@link javassist.CtClass#setGenericSignature(String)}
  322. * for a code sample.
  323. *
  324. * @param sig a new generic signature.
  325. * @see javassist.bytecode.SignatureAttribute.MethodSignature#encode()
  326. * @since 3.17
  327. */
  328. public void setGenericSignature(String sig) {
  329. declaringClass.checkModify();
  330. methodInfo.addAttribute(new SignatureAttribute(methodInfo.getConstPool(), sig));
  331. }
  332. /**
  333. * Obtains exceptions that this method/constructor may throw.
  334. *
  335. * @return a zero-length array if there is no throws clause.
  336. */
  337. public CtClass[] getExceptionTypes() throws NotFoundException {
  338. String[] exceptions;
  339. ExceptionsAttribute ea = methodInfo.getExceptionsAttribute();
  340. if (ea == null)
  341. exceptions = null;
  342. else
  343. exceptions = ea.getExceptions();
  344. return declaringClass.getClassPool().get(exceptions);
  345. }
  346. /**
  347. * Sets exceptions that this method/constructor may throw.
  348. */
  349. public void setExceptionTypes(CtClass[] types) throws NotFoundException {
  350. declaringClass.checkModify();
  351. if (types == null || types.length == 0) {
  352. methodInfo.removeExceptionsAttribute();
  353. return;
  354. }
  355. String[] names = new String[types.length];
  356. for (int i = 0; i < types.length; ++i)
  357. names[i] = types[i].getName();
  358. ExceptionsAttribute ea = methodInfo.getExceptionsAttribute();
  359. if (ea == null) {
  360. ea = new ExceptionsAttribute(methodInfo.getConstPool());
  361. methodInfo.setExceptionsAttribute(ea);
  362. }
  363. ea.setExceptions(names);
  364. }
  365. /**
  366. * Returns true if the body is empty.
  367. */
  368. public abstract boolean isEmpty();
  369. /**
  370. * Sets a method/constructor body.
  371. *
  372. * @param src the source code representing the body.
  373. * It must be a single statement or block.
  374. * If it is <code>null</code>, the substituted
  375. * body does nothing except returning zero or null.
  376. */
  377. public void setBody(String src) throws CannotCompileException {
  378. setBody(src, null, null);
  379. }
  380. /**
  381. * Sets a method/constructor body.
  382. *
  383. * @param src the source code representing the body.
  384. * It must be a single statement or block.
  385. * If it is <code>null</code>, the substituted
  386. * body does nothing except returning zero or null.
  387. * @param delegateObj the source text specifying the object
  388. * that is called on by <code>$proceed()</code>.
  389. * @param delegateMethod the name of the method
  390. * that is called by <code>$proceed()</code>.
  391. */
  392. public void setBody(String src,
  393. String delegateObj, String delegateMethod)
  394. throws CannotCompileException
  395. {
  396. CtClass cc = declaringClass;
  397. cc.checkModify();
  398. try {
  399. Javac jv = new Javac(cc);
  400. if (delegateMethod != null)
  401. jv.recordProceed(delegateObj, delegateMethod);
  402. Bytecode b = jv.compileBody(this, src);
  403. methodInfo.setCodeAttribute(b.toCodeAttribute());
  404. methodInfo.setAccessFlags(methodInfo.getAccessFlags()
  405. & ~AccessFlag.ABSTRACT);
  406. methodInfo.rebuildStackMapIf6(cc.getClassPool(), cc.getClassFile2());
  407. declaringClass.rebuildClassFile();
  408. }
  409. catch (CompileError e) {
  410. throw new CannotCompileException(e);
  411. } catch (BadBytecode e) {
  412. throw new CannotCompileException(e);
  413. }
  414. }
  415. static void setBody0(CtClass srcClass, MethodInfo srcInfo,
  416. CtClass destClass, MethodInfo destInfo,
  417. ClassMap map)
  418. throws CannotCompileException
  419. {
  420. destClass.checkModify();
  421. map = new ClassMap(map);
  422. map.put(srcClass.getName(), destClass.getName());
  423. try {
  424. CodeAttribute cattr = srcInfo.getCodeAttribute();
  425. if (cattr != null) {
  426. ConstPool cp = destInfo.getConstPool();
  427. CodeAttribute ca = (CodeAttribute)cattr.copy(cp, map);
  428. destInfo.setCodeAttribute(ca);
  429. // a stack map table is copied to destInfo.
  430. }
  431. }
  432. catch (CodeAttribute.RuntimeCopyException e) {
  433. /* the exception may be thrown by copy() in CodeAttribute.
  434. */
  435. throw new CannotCompileException(e);
  436. }
  437. destInfo.setAccessFlags(destInfo.getAccessFlags()
  438. & ~AccessFlag.ABSTRACT);
  439. destClass.rebuildClassFile();
  440. }
  441. /**
  442. * Obtains an attribute with the given name.
  443. * If that attribute is not found in the class file, this
  444. * method returns null.
  445. *
  446. * <p>Note that an attribute is a data block specified by
  447. * the class file format. It is not an annotation.
  448. * See {@link javassist.bytecode.AttributeInfo}.
  449. *
  450. * @param name attribute name
  451. */
  452. public byte[] getAttribute(String name) {
  453. AttributeInfo ai = methodInfo.getAttribute(name);
  454. if (ai == null)
  455. return null;
  456. else
  457. return ai.get();
  458. }
  459. /**
  460. * Adds an attribute. The attribute is saved in the class file.
  461. *
  462. * <p>Note that an attribute is a data block specified by
  463. * the class file format. It is not an annotation.
  464. * See {@link javassist.bytecode.AttributeInfo}.
  465. *
  466. * @param name attribute name
  467. * @param data attribute value
  468. */
  469. public void setAttribute(String name, byte[] data) {
  470. declaringClass.checkModify();
  471. methodInfo.addAttribute(new AttributeInfo(methodInfo.getConstPool(),
  472. name, data));
  473. }
  474. /**
  475. * Declares to use <code>$cflow</code> for this method/constructor.
  476. * If <code>$cflow</code> is used, the class files modified
  477. * with Javassist requires a support class
  478. * <code>javassist.runtime.Cflow</code> at runtime
  479. * (other Javassist classes are not required at runtime).
  480. *
  481. * <p>Every <code>$cflow</code> variable is given a unique name.
  482. * For example, if the given name is <code>"Point.paint"</code>,
  483. * then the variable is indicated by <code>$cflow(Point.paint)</code>.
  484. *
  485. * @param name <code>$cflow</code> name. It can include
  486. * alphabets, numbers, <code>_</code>,
  487. * <code>$</code>, and <code>.</code> (dot).
  488. *
  489. * @see javassist.runtime.Cflow
  490. */
  491. public void useCflow(String name) throws CannotCompileException {
  492. CtClass cc = declaringClass;
  493. cc.checkModify();
  494. ClassPool pool = cc.getClassPool();
  495. String fname;
  496. int i = 0;
  497. while (true) {
  498. fname = "_cflow$" + i++;
  499. try {
  500. cc.getDeclaredField(fname);
  501. }
  502. catch(NotFoundException e) {
  503. break;
  504. }
  505. }
  506. pool.recordCflow(name, declaringClass.getName(), fname);
  507. try {
  508. CtClass type = pool.get("javassist.runtime.Cflow");
  509. CtField field = new CtField(type, fname, cc);
  510. field.setModifiers(Modifier.PUBLIC | Modifier.STATIC);
  511. cc.addField(field, CtField.Initializer.byNew(type));
  512. insertBefore(fname + ".enter();", false);
  513. String src = fname + ".exit();";
  514. insertAfter(src, true);
  515. }
  516. catch (NotFoundException e) {
  517. throw new CannotCompileException(e);
  518. }
  519. }
  520. /**
  521. * Declares a new local variable. The scope of this variable is the
  522. * whole method body. The initial value of that variable is not set.
  523. * The declared variable can be accessed in the code snippet inserted
  524. * by <code>insertBefore()</code>, <code>insertAfter()</code>, etc.
  525. *
  526. * <p>If the second parameter <code>asFinally</code> to
  527. * <code>insertAfter()</code> is true, the declared local variable
  528. * is not visible from the code inserted by <code>insertAfter()</code>.
  529. *
  530. * @param name the name of the variable
  531. * @param type the type of the variable
  532. * @see #insertBefore(String)
  533. * @see #insertAfter(String)
  534. */
  535. public void addLocalVariable(String name, CtClass type)
  536. throws CannotCompileException
  537. {
  538. declaringClass.checkModify();
  539. ConstPool cp = methodInfo.getConstPool();
  540. CodeAttribute ca = methodInfo.getCodeAttribute();
  541. if (ca == null)
  542. throw new CannotCompileException("no method body");
  543. LocalVariableAttribute va = (LocalVariableAttribute)ca.getAttribute(
  544. LocalVariableAttribute.tag);
  545. if (va == null) {
  546. va = new LocalVariableAttribute(cp);
  547. ca.getAttributes().add(va);
  548. }
  549. int maxLocals = ca.getMaxLocals();
  550. String desc = Descriptor.of(type);
  551. va.addEntry(0, ca.getCodeLength(),
  552. cp.addUtf8Info(name), cp.addUtf8Info(desc), maxLocals);
  553. ca.setMaxLocals(maxLocals + Descriptor.dataSize(desc));
  554. }
  555. /**
  556. * Inserts a new parameter, which becomes the first parameter.
  557. */
  558. public void insertParameter(CtClass type)
  559. throws CannotCompileException
  560. {
  561. declaringClass.checkModify();
  562. String desc = methodInfo.getDescriptor();
  563. String desc2 = Descriptor.insertParameter(type, desc);
  564. try {
  565. addParameter2(Modifier.isStatic(getModifiers()) ? 0 : 1, type, desc);
  566. }
  567. catch (BadBytecode e) {
  568. throw new CannotCompileException(e);
  569. }
  570. methodInfo.setDescriptor(desc2);
  571. }
  572. /**
  573. * Appends a new parameter, which becomes the last parameter.
  574. */
  575. public void addParameter(CtClass type)
  576. throws CannotCompileException
  577. {
  578. declaringClass.checkModify();
  579. String desc = methodInfo.getDescriptor();
  580. String desc2 = Descriptor.appendParameter(type, desc);
  581. int offset = Modifier.isStatic(getModifiers()) ? 0 : 1;
  582. try {
  583. addParameter2(offset + Descriptor.paramSize(desc), type, desc);
  584. }
  585. catch (BadBytecode e) {
  586. throw new CannotCompileException(e);
  587. }
  588. methodInfo.setDescriptor(desc2);
  589. }
  590. private void addParameter2(int where, CtClass type, String desc)
  591. throws BadBytecode
  592. {
  593. CodeAttribute ca = methodInfo.getCodeAttribute();
  594. if (ca != null) {
  595. int size = 1;
  596. char typeDesc = 'L';
  597. int classInfo = 0;
  598. if (type.isPrimitive()) {
  599. CtPrimitiveType cpt = (CtPrimitiveType)type;
  600. size = cpt.getDataSize();
  601. typeDesc = cpt.getDescriptor();
  602. }
  603. else
  604. classInfo = methodInfo.getConstPool().addClassInfo(type);
  605. ca.insertLocalVar(where, size);
  606. LocalVariableAttribute va
  607. = (LocalVariableAttribute)ca.getAttribute(LocalVariableAttribute.tag);
  608. if (va != null)
  609. va.shiftIndex(where, size);
  610. LocalVariableTypeAttribute lvta
  611. = (LocalVariableTypeAttribute)ca.getAttribute(LocalVariableTypeAttribute.tag);
  612. if (lvta != null)
  613. lvta.shiftIndex(where, size);
  614. StackMapTable smt = (StackMapTable)ca.getAttribute(StackMapTable.tag);
  615. if (smt != null)
  616. smt.insertLocal(where, StackMapTable.typeTagOf(typeDesc), classInfo);
  617. StackMap sm = (StackMap)ca.getAttribute(StackMap.tag);
  618. if (sm != null)
  619. sm.insertLocal(where, StackMapTable.typeTagOf(typeDesc), classInfo);
  620. }
  621. }
  622. /**
  623. * Modifies the method/constructor body.
  624. *
  625. * @param converter specifies how to modify.
  626. */
  627. public void instrument(CodeConverter converter)
  628. throws CannotCompileException
  629. {
  630. declaringClass.checkModify();
  631. ConstPool cp = methodInfo.getConstPool();
  632. converter.doit(getDeclaringClass(), methodInfo, cp);
  633. }
  634. /**
  635. * Modifies the method/constructor body.
  636. *
  637. * <p>While executing this method, only <code>replace()</code>
  638. * in <code>Expr</code> is available for bytecode modification.
  639. * Other methods such as <code>insertBefore()</code> may collapse
  640. * the bytecode because the <code>ExprEditor</code> loses
  641. * its current position.
  642. *
  643. * @param editor specifies how to modify.
  644. * @see javassist.expr.Expr#replace(String)
  645. * @see #insertBefore(String)
  646. */
  647. public void instrument(ExprEditor editor)
  648. throws CannotCompileException
  649. {
  650. // if the class is not frozen,
  651. // does not turn the modified flag on.
  652. if (declaringClass.isFrozen())
  653. declaringClass.checkModify();
  654. if (editor.doit(declaringClass, methodInfo))
  655. declaringClass.checkModify();
  656. }
  657. /**
  658. * Inserts bytecode at the beginning of the body.
  659. *
  660. * <p>If this object represents a constructor,
  661. * the bytecode is inserted before
  662. * a constructor in the super class or this class is called.
  663. * Therefore, the inserted bytecode is subject to constraints described
  664. * in Section 4.8.2 of The Java Virtual Machine Specification (2nd ed).
  665. * For example, it cannot access instance fields or methods although
  666. * it may assign a value to an instance field directly declared in this
  667. * class. Accessing static fields and methods is allowed.
  668. * Use <code>insertBeforeBody()</code> in <code>CtConstructor</code>.
  669. *
  670. * @param src the source code representing the inserted bytecode.
  671. * It must be a single statement or block.
  672. * @see CtConstructor#insertBeforeBody(String)
  673. */
  674. public void insertBefore(String src) throws CannotCompileException {
  675. insertBefore(src, true);
  676. }
  677. private void insertBefore(String src, boolean rebuild)
  678. throws CannotCompileException
  679. {
  680. CtClass cc = declaringClass;
  681. cc.checkModify();
  682. CodeAttribute ca = methodInfo.getCodeAttribute();
  683. if (ca == null)
  684. throw new CannotCompileException("no method body");
  685. CodeIterator iterator = ca.iterator();
  686. Javac jv = new Javac(cc);
  687. try {
  688. int nvars = jv.recordParams(getParameterTypes(),
  689. Modifier.isStatic(getModifiers()));
  690. jv.recordParamNames(ca, nvars);
  691. jv.recordLocalVariables(ca, 0);
  692. jv.recordType(getReturnType0());
  693. jv.compileStmnt(src);
  694. Bytecode b = jv.getBytecode();
  695. int stack = b.getMaxStack();
  696. int locals = b.getMaxLocals();
  697. if (stack > ca.getMaxStack())
  698. ca.setMaxStack(stack);
  699. if (locals > ca.getMaxLocals())
  700. ca.setMaxLocals(locals);
  701. int pos = iterator.insertEx(b.get());
  702. iterator.insert(b.getExceptionTable(), pos);
  703. if (rebuild)
  704. methodInfo.rebuildStackMapIf6(cc.getClassPool(), cc.getClassFile2());
  705. }
  706. catch (NotFoundException e) {
  707. throw new CannotCompileException(e);
  708. }
  709. catch (CompileError e) {
  710. throw new CannotCompileException(e);
  711. }
  712. catch (BadBytecode e) {
  713. throw new CannotCompileException(e);
  714. }
  715. }
  716. /**
  717. * Inserts bytecode at the end of the body.
  718. * The bytecode is inserted just before every return insturction.
  719. * It is not executed when an exception is thrown.
  720. *
  721. * @param src the source code representing the inserted bytecode.
  722. * It must be a single statement or block.
  723. */
  724. public void insertAfter(String src)
  725. throws CannotCompileException
  726. {
  727. insertAfter(src, false);
  728. }
  729. /**
  730. * Inserts bytecode at the end of the body.
  731. * The bytecode is inserted just before every return insturction.
  732. *
  733. * @param src the source code representing the inserted bytecode.
  734. * It must be a single statement or block.
  735. * @param asFinally true if the inserted bytecode is executed
  736. * not only when the control normally returns
  737. * but also when an exception is thrown.
  738. * If this parameter is true, the inserted code cannot
  739. * access local variables.
  740. */
  741. public void insertAfter(String src, boolean asFinally)
  742. throws CannotCompileException
  743. {
  744. CtClass cc = declaringClass;
  745. cc.checkModify();
  746. ConstPool pool = methodInfo.getConstPool();
  747. CodeAttribute ca = methodInfo.getCodeAttribute();
  748. if (ca == null)
  749. throw new CannotCompileException("no method body");
  750. CodeIterator iterator = ca.iterator();
  751. int retAddr = ca.getMaxLocals();
  752. Bytecode b = new Bytecode(pool, 0, retAddr + 1);
  753. b.setStackDepth(ca.getMaxStack() + 1);
  754. Javac jv = new Javac(b, cc);
  755. try {
  756. int nvars = jv.recordParams(getParameterTypes(),
  757. Modifier.isStatic(getModifiers()));
  758. jv.recordParamNames(ca, nvars);
  759. CtClass rtype = getReturnType0();
  760. int varNo = jv.recordReturnType(rtype, true);
  761. jv.recordLocalVariables(ca, 0);
  762. // finally clause for exceptions
  763. int handlerLen = insertAfterHandler(asFinally, b, rtype, varNo,
  764. jv, src);
  765. int handlerPos = iterator.getCodeLength();
  766. if (asFinally)
  767. ca.getExceptionTable().add(getStartPosOfBody(ca), handlerPos, handlerPos, 0);
  768. int adviceLen = 0;
  769. int advicePos = 0;
  770. boolean noReturn = true;
  771. while (iterator.hasNext()) {
  772. int pos = iterator.next();
  773. if (pos >= handlerPos)
  774. break;
  775. int c = iterator.byteAt(pos);
  776. if (c == Opcode.ARETURN || c == Opcode.IRETURN
  777. || c == Opcode.FRETURN || c == Opcode.LRETURN
  778. || c == Opcode.DRETURN || c == Opcode.RETURN) {
  779. if (noReturn) {
  780. // finally clause for normal termination
  781. adviceLen = insertAfterAdvice(b, jv, src, pool, rtype, varNo);
  782. handlerPos = iterator.append(b.get());
  783. iterator.append(b.getExceptionTable(), handlerPos);
  784. advicePos = iterator.getCodeLength() - adviceLen;
  785. handlerLen = advicePos - handlerPos;
  786. noReturn = false;
  787. }
  788. insertGoto(iterator, advicePos, pos);
  789. advicePos = iterator.getCodeLength() - adviceLen;
  790. handlerPos = advicePos - handlerLen;
  791. }
  792. }
  793. if (noReturn) {
  794. handlerPos = iterator.append(b.get());
  795. iterator.append(b.getExceptionTable(), handlerPos);
  796. }
  797. ca.setMaxStack(b.getMaxStack());
  798. ca.setMaxLocals(b.getMaxLocals());
  799. methodInfo.rebuildStackMapIf6(cc.getClassPool(), cc.getClassFile2());
  800. }
  801. catch (NotFoundException e) {
  802. throw new CannotCompileException(e);
  803. }
  804. catch (CompileError e) {
  805. throw new CannotCompileException(e);
  806. }
  807. catch (BadBytecode e) {
  808. throw new CannotCompileException(e);
  809. }
  810. }
  811. private int insertAfterAdvice(Bytecode code, Javac jv, String src,
  812. ConstPool cp, CtClass rtype, int varNo)
  813. throws CompileError
  814. {
  815. int pc = code.currentPc();
  816. if (rtype == CtClass.voidType) {
  817. code.addOpcode(Opcode.ACONST_NULL);
  818. code.addAstore(varNo);
  819. jv.compileStmnt(src);
  820. code.addOpcode(Opcode.RETURN);
  821. if (code.getMaxLocals() < 1)
  822. code.setMaxLocals(1);
  823. }
  824. else {
  825. code.addStore(varNo, rtype);
  826. jv.compileStmnt(src);
  827. code.addLoad(varNo, rtype);
  828. if (rtype.isPrimitive())
  829. code.addOpcode(((CtPrimitiveType)rtype).getReturnOp());
  830. else
  831. code.addOpcode(Opcode.ARETURN);
  832. }
  833. return code.currentPc() - pc;
  834. }
  835. /*
  836. * assert subr > pos
  837. */
  838. private void insertGoto(CodeIterator iterator, int subr, int pos)
  839. throws BadBytecode
  840. {
  841. iterator.setMark(subr);
  842. // the gap length might be a multiple of 4.
  843. iterator.writeByte(Opcode.NOP, pos);
  844. boolean wide = subr + 2 - pos > Short.MAX_VALUE;
  845. pos = iterator.insertGapAt(pos, wide ? 4 : 2, false).position;
  846. int offset = iterator.getMark() - pos;
  847. if (wide) {
  848. iterator.writeByte(Opcode.GOTO_W, pos);
  849. iterator.write32bit(offset, pos + 1);
  850. }
  851. else if (offset <= Short.MAX_VALUE) {
  852. iterator.writeByte(Opcode.GOTO, pos);
  853. iterator.write16bit(offset, pos + 1);
  854. }
  855. else {
  856. pos = iterator.insertGapAt(pos, 2, false).position;
  857. iterator.writeByte(Opcode.GOTO_W, pos);
  858. iterator.write32bit(iterator.getMark() - pos, pos + 1);
  859. }
  860. }
  861. /* insert a finally clause
  862. */
  863. private int insertAfterHandler(boolean asFinally, Bytecode b,
  864. CtClass rtype, int returnVarNo,
  865. Javac javac, String src)
  866. throws CompileError
  867. {
  868. if (!asFinally)
  869. return 0;
  870. int var = b.getMaxLocals();
  871. b.incMaxLocals(1);
  872. int pc = b.currentPc();
  873. b.addAstore(var); // store an exception
  874. if (rtype.isPrimitive()) {
  875. char c = ((CtPrimitiveType)rtype).getDescriptor();
  876. if (c == 'D') {
  877. b.addDconst(0.0);
  878. b.addDstore(returnVarNo);
  879. }
  880. else if (c == 'F') {
  881. b.addFconst(0);
  882. b.addFstore(returnVarNo);
  883. }
  884. else if (c == 'J') {
  885. b.addLconst(0);
  886. b.addLstore(returnVarNo);
  887. }
  888. else if (c == 'V') {
  889. b.addOpcode(Opcode.ACONST_NULL);
  890. b.addAstore(returnVarNo);
  891. }
  892. else { // int, boolean, char, short, ...
  893. b.addIconst(0);
  894. b.addIstore(returnVarNo);
  895. }
  896. }
  897. else {
  898. b.addOpcode(Opcode.ACONST_NULL);
  899. b.addAstore(returnVarNo);
  900. }
  901. javac.compileStmnt(src);
  902. b.addAload(var);
  903. b.addOpcode(Opcode.ATHROW);
  904. return b.currentPc() - pc;
  905. }
  906. /* -- OLD version --
  907. public void insertAfter(String src) throws CannotCompileException {
  908. declaringClass.checkModify();
  909. CodeAttribute ca = methodInfo.getCodeAttribute();
  910. CodeIterator iterator = ca.iterator();
  911. Bytecode b = new Bytecode(methodInfo.getConstPool(),
  912. ca.getMaxStack(), ca.getMaxLocals());
  913. b.setStackDepth(ca.getMaxStack());
  914. Javac jv = new Javac(b, declaringClass);
  915. try {
  916. jv.recordParams(getParameterTypes(),
  917. Modifier.isStatic(getModifiers()));
  918. CtClass rtype = getReturnType0();
  919. int varNo = jv.recordReturnType(rtype, true);
  920. boolean isVoid = rtype == CtClass.voidType;
  921. if (isVoid) {
  922. b.addOpcode(Opcode.ACONST_NULL);
  923. b.addAstore(varNo);
  924. jv.compileStmnt(src);
  925. }
  926. else {
  927. b.addStore(varNo, rtype);
  928. jv.compileStmnt(src);
  929. b.addLoad(varNo, rtype);
  930. }
  931. byte[] code = b.get();
  932. ca.setMaxStack(b.getMaxStack());
  933. ca.setMaxLocals(b.getMaxLocals());
  934. while (iterator.hasNext()) {
  935. int pos = iterator.next();
  936. int c = iterator.byteAt(pos);
  937. if (c == Opcode.ARETURN || c == Opcode.IRETURN
  938. || c == Opcode.FRETURN || c == Opcode.LRETURN
  939. || c == Opcode.DRETURN || c == Opcode.RETURN)
  940. iterator.insert(pos, code);
  941. }
  942. }
  943. catch (NotFoundException e) {
  944. throw new CannotCompileException(e);
  945. }
  946. catch (CompileError e) {
  947. throw new CannotCompileException(e);
  948. }
  949. catch (BadBytecode e) {
  950. throw new CannotCompileException(e);
  951. }
  952. }
  953. */
  954. /**
  955. * Adds a catch clause that handles an exception thrown in the
  956. * body. The catch clause must end with a return or throw statement.
  957. *
  958. * @param src the source code representing the catch clause.
  959. * It must be a single statement or block.
  960. * @param exceptionType the type of the exception handled by the
  961. * catch clause.
  962. */
  963. public void addCatch(String src, CtClass exceptionType)
  964. throws CannotCompileException
  965. {
  966. addCatch(src, exceptionType, "$e");
  967. }
  968. /**
  969. * Adds a catch clause that handles an exception thrown in the
  970. * body. The catch clause must end with a return or throw statement.
  971. *
  972. * @param src the source code representing the catch clause.
  973. * It must be a single statement or block.
  974. * @param exceptionType the type of the exception handled by the
  975. * catch clause.
  976. * @param exceptionName the name of the variable containing the
  977. * caught exception, for example,
  978. * <code>$e</code>.
  979. */
  980. public void addCatch(String src, CtClass exceptionType,
  981. String exceptionName)
  982. throws CannotCompileException
  983. {
  984. CtClass cc = declaringClass;
  985. cc.checkModify();
  986. ConstPool cp = methodInfo.getConstPool();
  987. CodeAttribute ca = methodInfo.getCodeAttribute();
  988. CodeIterator iterator = ca.iterator();
  989. Bytecode b = new Bytecode(cp, ca.getMaxStack(), ca.getMaxLocals());
  990. b.setStackDepth(1);
  991. Javac jv = new Javac(b, cc);
  992. try {
  993. jv.recordParams(getParameterTypes(),
  994. Modifier.isStatic(getModifiers()));
  995. int var = jv.recordVariable(exceptionType, exceptionName);
  996. b.addAstore(var);
  997. jv.compileStmnt(src);
  998. int stack = b.getMaxStack();
  999. int locals = b.getMaxLocals();
  1000. if (stack > ca.getMaxStack())
  1001. ca.setMaxStack(stack);
  1002. if (locals > ca.getMaxLocals())
  1003. ca.setMaxLocals(locals);
  1004. int len = iterator.getCodeLength();
  1005. int pos = iterator.append(b.get());
  1006. ca.getExceptionTable().add(getStartPosOfBody(ca), len, len,
  1007. cp.addClassInfo(exceptionType));
  1008. iterator.append(b.getExceptionTable(), pos);
  1009. methodInfo.rebuildStackMapIf6(cc.getClassPool(), cc.getClassFile2());
  1010. }
  1011. catch (NotFoundException e) {
  1012. throw new CannotCompileException(e);
  1013. }
  1014. catch (CompileError e) {
  1015. throw new CannotCompileException(e);
  1016. } catch (BadBytecode e) {
  1017. throw new CannotCompileException(e);
  1018. }
  1019. }
  1020. /* CtConstructor overrides this method.
  1021. */
  1022. int getStartPosOfBody(CodeAttribute ca) throws CannotCompileException {
  1023. return 0;
  1024. }
  1025. /**
  1026. * Inserts bytecode at the specified line in the body.
  1027. * It is equivalent to:
  1028. *
  1029. * <br><code>insertAt(lineNum, true, src)</code>
  1030. *
  1031. * <br>See this method as well.
  1032. *
  1033. * @param lineNum the line number. The bytecode is inserted at the
  1034. * beginning of the code at the line specified by this
  1035. * line number.
  1036. * @param src the source code representing the inserted bytecode.
  1037. * It must be a single statement or block.
  1038. * @return the line number at which the bytecode has been inserted.
  1039. *
  1040. * @see CtBehavior#insertAt(int,boolean,String)
  1041. */
  1042. public int insertAt(int lineNum, String src)
  1043. throws CannotCompileException
  1044. {
  1045. return insertAt(lineNum, true, src);
  1046. }
  1047. /**
  1048. * Inserts bytecode at the specified line in the body.
  1049. *
  1050. * <p>If there is not
  1051. * a statement at the specified line, the bytecode might be inserted
  1052. * at the line including the first statement after that line specified.
  1053. * For example, if there is only a closing brace at that line, the
  1054. * bytecode would be inserted at another line below.
  1055. * To know exactly where the bytecode will be inserted, call with
  1056. * <code>modify</code> set to <code>false</code>.
  1057. *
  1058. * @param lineNum the line number. The bytecode is inserted at the
  1059. * beginning of the code at the line specified by this
  1060. * line number.
  1061. * @param modify if false, this method does not insert the bytecode.
  1062. * It instead only returns the line number at which
  1063. * the bytecode would be inserted.
  1064. * @param src the source code representing the inserted bytecode.
  1065. * It must be a single statement or block.
  1066. * If modify is false, the value of src can be null.
  1067. * @return the line number at which the bytecode has been inserted.
  1068. */
  1069. public int insertAt(int lineNum, boolean modify, String src)
  1070. throws CannotCompileException
  1071. {
  1072. CodeAttribute ca = methodInfo.getCodeAttribute();
  1073. if (ca == null)
  1074. throw new CannotCompileException("no method body");
  1075. LineNumberAttribute ainfo
  1076. = (LineNumberAttribute)ca.getAttribute(LineNumberAttribute.tag);
  1077. if (ainfo == null)
  1078. throw new CannotCompileException("no line number info");
  1079. LineNumberAttribute.Pc pc = ainfo.toNearPc(lineNum);
  1080. lineNum = pc.line;
  1081. int index = pc.index;
  1082. if (!modify)
  1083. return lineNum;
  1084. CtClass cc = declaringClass;
  1085. cc.checkModify();
  1086. CodeIterator iterator = ca.iterator();
  1087. Javac jv = new Javac(cc);
  1088. try {
  1089. jv.recordLocalVariables(ca, index);
  1090. jv.recordParams(getParameterTypes(),
  1091. Modifier.isStatic(getModifiers()));
  1092. jv.setMaxLocals(ca.getMaxLocals());
  1093. jv.compileStmnt(src);
  1094. Bytecode b = jv.getBytecode();
  1095. int locals = b.getMaxLocals();
  1096. int stack = b.getMaxStack();
  1097. ca.setMaxLocals(locals);
  1098. /* We assume that there is no values in the operand stack
  1099. * at the position where the bytecode is inserted.
  1100. */
  1101. if (stack > ca.getMaxStack())
  1102. ca.setMaxStack(stack);
  1103. index = iterator.insertAt(index, b.get());
  1104. iterator.insert(b.getExceptionTable(), index);
  1105. methodInfo.rebuildStackMapIf6(cc.getClassPool(), cc.getClassFile2());
  1106. return lineNum;
  1107. }
  1108. catch (NotFoundException e) {
  1109. throw new CannotCompileException(e);
  1110. }
  1111. catch (CompileError e) {
  1112. throw new CannotCompileException(e);
  1113. }
  1114. catch (BadBytecode e) {
  1115. throw new CannotCompileException(e);
  1116. }
  1117. }
  1118. }