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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209
  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)
  608. ca.getAttribute(LocalVariableAttribute.tag);
  609. if (va != null)
  610. va.shiftIndex(where, size);
  611. StackMapTable smt = (StackMapTable)ca.getAttribute(StackMapTable.tag);
  612. if (smt != null)
  613. smt.insertLocal(where, StackMapTable.typeTagOf(typeDesc), classInfo);
  614. StackMap sm = (StackMap)ca.getAttribute(StackMap.tag);
  615. if (sm != null)
  616. sm.insertLocal(where, StackMapTable.typeTagOf(typeDesc), classInfo);
  617. }
  618. }
  619. /**
  620. * Modifies the method/constructor body.
  621. *
  622. * @param converter specifies how to modify.
  623. */
  624. public void instrument(CodeConverter converter)
  625. throws CannotCompileException
  626. {
  627. declaringClass.checkModify();
  628. ConstPool cp = methodInfo.getConstPool();
  629. converter.doit(getDeclaringClass(), methodInfo, cp);
  630. }
  631. /**
  632. * Modifies the method/constructor body.
  633. *
  634. * <p>While executing this method, only <code>replace()</code>
  635. * in <code>Expr</code> is available for bytecode modification.
  636. * Other methods such as <code>insertBefore()</code> may collapse
  637. * the bytecode because the <code>ExprEditor</code> loses
  638. * its current position.
  639. *
  640. * @param editor specifies how to modify.
  641. * @see javassist.expr.Expr#replace(String)
  642. * @see #insertBefore(String)
  643. */
  644. public void instrument(ExprEditor editor)
  645. throws CannotCompileException
  646. {
  647. // if the class is not frozen,
  648. // does not turn the modified flag on.
  649. if (declaringClass.isFrozen())
  650. declaringClass.checkModify();
  651. if (editor.doit(declaringClass, methodInfo))
  652. declaringClass.checkModify();
  653. }
  654. /**
  655. * Inserts bytecode at the beginning of the body.
  656. *
  657. * <p>If this object represents a constructor,
  658. * the bytecode is inserted before
  659. * a constructor in the super class or this class is called.
  660. * Therefore, the inserted bytecode is subject to constraints described
  661. * in Section 4.8.2 of The Java Virtual Machine Specification (2nd ed).
  662. * For example, it cannot access instance fields or methods although
  663. * it may assign a value to an instance field directly declared in this
  664. * class. Accessing static fields and methods is allowed.
  665. * Use <code>insertBeforeBody()</code> in <code>CtConstructor</code>.
  666. *
  667. * @param src the source code representing the inserted bytecode.
  668. * It must be a single statement or block.
  669. * @see CtConstructor#insertBeforeBody(String)
  670. */
  671. public void insertBefore(String src) throws CannotCompileException {
  672. insertBefore(src, true);
  673. }
  674. private void insertBefore(String src, boolean rebuild)
  675. throws CannotCompileException
  676. {
  677. CtClass cc = declaringClass;
  678. cc.checkModify();
  679. CodeAttribute ca = methodInfo.getCodeAttribute();
  680. if (ca == null)
  681. throw new CannotCompileException("no method body");
  682. CodeIterator iterator = ca.iterator();
  683. Javac jv = new Javac(cc);
  684. try {
  685. int nvars = jv.recordParams(getParameterTypes(),
  686. Modifier.isStatic(getModifiers()));
  687. jv.recordParamNames(ca, nvars);
  688. jv.recordLocalVariables(ca, 0);
  689. jv.recordType(getReturnType0());
  690. jv.compileStmnt(src);
  691. Bytecode b = jv.getBytecode();
  692. int stack = b.getMaxStack();
  693. int locals = b.getMaxLocals();
  694. if (stack > ca.getMaxStack())
  695. ca.setMaxStack(stack);
  696. if (locals > ca.getMaxLocals())
  697. ca.setMaxLocals(locals);
  698. int pos = iterator.insertEx(b.get());
  699. iterator.insert(b.getExceptionTable(), pos);
  700. if (rebuild)
  701. methodInfo.rebuildStackMapIf6(cc.getClassPool(), cc.getClassFile2());
  702. }
  703. catch (NotFoundException e) {
  704. throw new CannotCompileException(e);
  705. }
  706. catch (CompileError e) {
  707. throw new CannotCompileException(e);
  708. }
  709. catch (BadBytecode e) {
  710. throw new CannotCompileException(e);
  711. }
  712. }
  713. /**
  714. * Inserts bytecode at the end of the body.
  715. * The bytecode is inserted just before every return insturction.
  716. * It is not executed when an exception is thrown.
  717. *
  718. * @param src the source code representing the inserted bytecode.
  719. * It must be a single statement or block.
  720. */
  721. public void insertAfter(String src)
  722. throws CannotCompileException
  723. {
  724. insertAfter(src, false);
  725. }
  726. /**
  727. * Inserts bytecode at the end of the body.
  728. * The bytecode is inserted just before every return insturction.
  729. *
  730. * @param src the source code representing the inserted bytecode.
  731. * It must be a single statement or block.
  732. * @param asFinally true if the inserted bytecode is executed
  733. * not only when the control normally returns
  734. * but also when an exception is thrown.
  735. * If this parameter is true, the inserted code cannot
  736. * access local variables.
  737. */
  738. public void insertAfter(String src, boolean asFinally)
  739. throws CannotCompileException
  740. {
  741. CtClass cc = declaringClass;
  742. cc.checkModify();
  743. ConstPool pool = methodInfo.getConstPool();
  744. CodeAttribute ca = methodInfo.getCodeAttribute();
  745. if (ca == null)
  746. throw new CannotCompileException("no method body");
  747. CodeIterator iterator = ca.iterator();
  748. int retAddr = ca.getMaxLocals();
  749. Bytecode b = new Bytecode(pool, 0, retAddr + 1);
  750. b.setStackDepth(ca.getMaxStack() + 1);
  751. Javac jv = new Javac(b, cc);
  752. try {
  753. int nvars = jv.recordParams(getParameterTypes(),
  754. Modifier.isStatic(getModifiers()));
  755. jv.recordParamNames(ca, nvars);
  756. CtClass rtype = getReturnType0();
  757. int varNo = jv.recordReturnType(rtype, true);
  758. jv.recordLocalVariables(ca, 0);
  759. // finally clause for exceptions
  760. int handlerLen = insertAfterHandler(asFinally, b, rtype, varNo,
  761. jv, src);
  762. int handlerPos = iterator.getCodeLength();
  763. if (asFinally)
  764. ca.getExceptionTable().add(getStartPosOfBody(ca), handlerPos, handlerPos, 0);
  765. int adviceLen = 0;
  766. int advicePos = 0;
  767. boolean noReturn = true;
  768. while (iterator.hasNext()) {
  769. int pos = iterator.next();
  770. if (pos >= handlerPos)
  771. break;
  772. int c = iterator.byteAt(pos);
  773. if (c == Opcode.ARETURN || c == Opcode.IRETURN
  774. || c == Opcode.FRETURN || c == Opcode.LRETURN
  775. || c == Opcode.DRETURN || c == Opcode.RETURN) {
  776. if (noReturn) {
  777. // finally clause for normal termination
  778. adviceLen = insertAfterAdvice(b, jv, src, pool, rtype, varNo);
  779. handlerPos = iterator.append(b.get());
  780. iterator.append(b.getExceptionTable(), handlerPos);
  781. advicePos = iterator.getCodeLength() - adviceLen;
  782. handlerLen = advicePos - handlerPos;
  783. noReturn = false;
  784. }
  785. insertGoto(iterator, advicePos, pos);
  786. advicePos = iterator.getCodeLength() - adviceLen;
  787. handlerPos = advicePos - handlerLen;
  788. }
  789. }
  790. if (noReturn) {
  791. handlerPos = iterator.append(b.get());
  792. iterator.append(b.getExceptionTable(), handlerPos);
  793. }
  794. ca.setMaxStack(b.getMaxStack());
  795. ca.setMaxLocals(b.getMaxLocals());
  796. methodInfo.rebuildStackMapIf6(cc.getClassPool(), cc.getClassFile2());
  797. }
  798. catch (NotFoundException e) {
  799. throw new CannotCompileException(e);
  800. }
  801. catch (CompileError e) {
  802. throw new CannotCompileException(e);
  803. }
  804. catch (BadBytecode e) {
  805. throw new CannotCompileException(e);
  806. }
  807. }
  808. private int insertAfterAdvice(Bytecode code, Javac jv, String src,
  809. ConstPool cp, CtClass rtype, int varNo)
  810. throws CompileError
  811. {
  812. int pc = code.currentPc();
  813. if (rtype == CtClass.voidType) {
  814. code.addOpcode(Opcode.ACONST_NULL);
  815. code.addAstore(varNo);
  816. jv.compileStmnt(src);
  817. code.addOpcode(Opcode.RETURN);
  818. if (code.getMaxLocals() < 1)
  819. code.setMaxLocals(1);
  820. }
  821. else {
  822. code.addStore(varNo, rtype);
  823. jv.compileStmnt(src);
  824. code.addLoad(varNo, rtype);
  825. if (rtype.isPrimitive())
  826. code.addOpcode(((CtPrimitiveType)rtype).getReturnOp());
  827. else
  828. code.addOpcode(Opcode.ARETURN);
  829. }
  830. return code.currentPc() - pc;
  831. }
  832. /*
  833. * assert subr > pos
  834. */
  835. private void insertGoto(CodeIterator iterator, int subr, int pos)
  836. throws BadBytecode
  837. {
  838. iterator.setMark(subr);
  839. // the gap length might be a multiple of 4.
  840. iterator.writeByte(Opcode.NOP, pos);
  841. boolean wide = subr + 2 - pos > Short.MAX_VALUE;
  842. pos = iterator.insertGapAt(pos, wide ? 4 : 2, false).position;
  843. int offset = iterator.getMark() - pos;
  844. if (wide) {
  845. iterator.writeByte(Opcode.GOTO_W, pos);
  846. iterator.write32bit(offset, pos + 1);
  847. }
  848. else if (offset <= Short.MAX_VALUE) {
  849. iterator.writeByte(Opcode.GOTO, pos);
  850. iterator.write16bit(offset, pos + 1);
  851. }
  852. else {
  853. pos = iterator.insertGapAt(pos, 2, false).position;
  854. iterator.writeByte(Opcode.GOTO_W, pos);
  855. iterator.write32bit(iterator.getMark() - pos, pos + 1);
  856. }
  857. }
  858. /* insert a finally clause
  859. */
  860. private int insertAfterHandler(boolean asFinally, Bytecode b,
  861. CtClass rtype, int returnVarNo,
  862. Javac javac, String src)
  863. throws CompileError
  864. {
  865. if (!asFinally)
  866. return 0;
  867. int var = b.getMaxLocals();
  868. b.incMaxLocals(1);
  869. int pc = b.currentPc();
  870. b.addAstore(var); // store an exception
  871. if (rtype.isPrimitive()) {
  872. char c = ((CtPrimitiveType)rtype).getDescriptor();
  873. if (c == 'D') {
  874. b.addDconst(0.0);
  875. b.addDstore(returnVarNo);
  876. }
  877. else if (c == 'F') {
  878. b.addFconst(0);
  879. b.addFstore(returnVarNo);
  880. }
  881. else if (c == 'J') {
  882. b.addLconst(0);
  883. b.addLstore(returnVarNo);
  884. }
  885. else if (c == 'V') {
  886. b.addOpcode(Opcode.ACONST_NULL);
  887. b.addAstore(returnVarNo);
  888. }
  889. else { // int, boolean, char, short, ...
  890. b.addIconst(0);
  891. b.addIstore(returnVarNo);
  892. }
  893. }
  894. else {
  895. b.addOpcode(Opcode.ACONST_NULL);
  896. b.addAstore(returnVarNo);
  897. }
  898. javac.compileStmnt(src);
  899. b.addAload(var);
  900. b.addOpcode(Opcode.ATHROW);
  901. return b.currentPc() - pc;
  902. }
  903. /* -- OLD version --
  904. public void insertAfter(String src) throws CannotCompileException {
  905. declaringClass.checkModify();
  906. CodeAttribute ca = methodInfo.getCodeAttribute();
  907. CodeIterator iterator = ca.iterator();
  908. Bytecode b = new Bytecode(methodInfo.getConstPool(),
  909. ca.getMaxStack(), ca.getMaxLocals());
  910. b.setStackDepth(ca.getMaxStack());
  911. Javac jv = new Javac(b, declaringClass);
  912. try {
  913. jv.recordParams(getParameterTypes(),
  914. Modifier.isStatic(getModifiers()));
  915. CtClass rtype = getReturnType0();
  916. int varNo = jv.recordReturnType(rtype, true);
  917. boolean isVoid = rtype == CtClass.voidType;
  918. if (isVoid) {
  919. b.addOpcode(Opcode.ACONST_NULL);
  920. b.addAstore(varNo);
  921. jv.compileStmnt(src);
  922. }
  923. else {
  924. b.addStore(varNo, rtype);
  925. jv.compileStmnt(src);
  926. b.addLoad(varNo, rtype);
  927. }
  928. byte[] code = b.get();
  929. ca.setMaxStack(b.getMaxStack());
  930. ca.setMaxLocals(b.getMaxLocals());
  931. while (iterator.hasNext()) {
  932. int pos = iterator.next();
  933. int c = iterator.byteAt(pos);
  934. if (c == Opcode.ARETURN || c == Opcode.IRETURN
  935. || c == Opcode.FRETURN || c == Opcode.LRETURN
  936. || c == Opcode.DRETURN || c == Opcode.RETURN)
  937. iterator.insert(pos, code);
  938. }
  939. }
  940. catch (NotFoundException e) {
  941. throw new CannotCompileException(e);
  942. }
  943. catch (CompileError e) {
  944. throw new CannotCompileException(e);
  945. }
  946. catch (BadBytecode e) {
  947. throw new CannotCompileException(e);
  948. }
  949. }
  950. */
  951. /**
  952. * Adds a catch clause that handles an exception thrown in the
  953. * body. The catch clause must end with a return or throw statement.
  954. *
  955. * @param src the source code representing the catch clause.
  956. * It must be a single statement or block.
  957. * @param exceptionType the type of the exception handled by the
  958. * catch clause.
  959. */
  960. public void addCatch(String src, CtClass exceptionType)
  961. throws CannotCompileException
  962. {
  963. addCatch(src, exceptionType, "$e");
  964. }
  965. /**
  966. * Adds a catch clause that handles an exception thrown in the
  967. * body. The catch clause must end with a return or throw statement.
  968. *
  969. * @param src the source code representing the catch clause.
  970. * It must be a single statement or block.
  971. * @param exceptionType the type of the exception handled by the
  972. * catch clause.
  973. * @param exceptionName the name of the variable containing the
  974. * caught exception, for example,
  975. * <code>$e</code>.
  976. */
  977. public void addCatch(String src, CtClass exceptionType,
  978. String exceptionName)
  979. throws CannotCompileException
  980. {
  981. CtClass cc = declaringClass;
  982. cc.checkModify();
  983. ConstPool cp = methodInfo.getConstPool();
  984. CodeAttribute ca = methodInfo.getCodeAttribute();
  985. CodeIterator iterator = ca.iterator();
  986. Bytecode b = new Bytecode(cp, ca.getMaxStack(), ca.getMaxLocals());
  987. b.setStackDepth(1);
  988. Javac jv = new Javac(b, cc);
  989. try {
  990. jv.recordParams(getParameterTypes(),
  991. Modifier.isStatic(getModifiers()));
  992. int var = jv.recordVariable(exceptionType, exceptionName);
  993. b.addAstore(var);
  994. jv.compileStmnt(src);
  995. int stack = b.getMaxStack();
  996. int locals = b.getMaxLocals();
  997. if (stack > ca.getMaxStack())
  998. ca.setMaxStack(stack);
  999. if (locals > ca.getMaxLocals())
  1000. ca.setMaxLocals(locals);
  1001. int len = iterator.getCodeLength();
  1002. int pos = iterator.append(b.get());
  1003. ca.getExceptionTable().add(getStartPosOfBody(ca), len, len,
  1004. cp.addClassInfo(exceptionType));
  1005. iterator.append(b.getExceptionTable(), pos);
  1006. methodInfo.rebuildStackMapIf6(cc.getClassPool(), cc.getClassFile2());
  1007. }
  1008. catch (NotFoundException e) {
  1009. throw new CannotCompileException(e);
  1010. }
  1011. catch (CompileError e) {
  1012. throw new CannotCompileException(e);
  1013. } catch (BadBytecode e) {
  1014. throw new CannotCompileException(e);
  1015. }
  1016. }
  1017. /* CtConstructor overrides this method.
  1018. */
  1019. int getStartPosOfBody(CodeAttribute ca) throws CannotCompileException {
  1020. return 0;
  1021. }
  1022. /**
  1023. * Inserts bytecode at the specified line in the body.
  1024. * It is equivalent to:
  1025. *
  1026. * <br><code>insertAt(lineNum, true, src)</code>
  1027. *
  1028. * <br>See this method as well.
  1029. *
  1030. * @param lineNum the line number. The bytecode is inserted at the
  1031. * beginning of the code at the line specified by this
  1032. * line number.
  1033. * @param src the source code representing the inserted bytecode.
  1034. * It must be a single statement or block.
  1035. * @return the line number at which the bytecode has been inserted.
  1036. *
  1037. * @see CtBehavior#insertAt(int,boolean,String)
  1038. */
  1039. public int insertAt(int lineNum, String src)
  1040. throws CannotCompileException
  1041. {
  1042. return insertAt(lineNum, true, src);
  1043. }
  1044. /**
  1045. * Inserts bytecode at the specified line in the body.
  1046. *
  1047. * <p>If there is not
  1048. * a statement at the specified line, the bytecode might be inserted
  1049. * at the line including the first statement after that line specified.
  1050. * For example, if there is only a closing brace at that line, the
  1051. * bytecode would be inserted at another line below.
  1052. * To know exactly where the bytecode will be inserted, call with
  1053. * <code>modify</code> set to <code>false</code>.
  1054. *
  1055. * @param lineNum the line number. The bytecode is inserted at the
  1056. * beginning of the code at the line specified by this
  1057. * line number.
  1058. * @param modify if false, this method does not insert the bytecode.
  1059. * It instead only returns the line number at which
  1060. * the bytecode would be inserted.
  1061. * @param src the source code representing the inserted bytecode.
  1062. * It must be a single statement or block.
  1063. * If modify is false, the value of src can be null.
  1064. * @return the line number at which the bytecode has been inserted.
  1065. */
  1066. public int insertAt(int lineNum, boolean modify, String src)
  1067. throws CannotCompileException
  1068. {
  1069. CodeAttribute ca = methodInfo.getCodeAttribute();
  1070. if (ca == null)
  1071. throw new CannotCompileException("no method body");
  1072. LineNumberAttribute ainfo
  1073. = (LineNumberAttribute)ca.getAttribute(LineNumberAttribute.tag);
  1074. if (ainfo == null)
  1075. throw new CannotCompileException("no line number info");
  1076. LineNumberAttribute.Pc pc = ainfo.toNearPc(lineNum);
  1077. lineNum = pc.line;
  1078. int index = pc.index;
  1079. if (!modify)
  1080. return lineNum;
  1081. CtClass cc = declaringClass;
  1082. cc.checkModify();
  1083. CodeIterator iterator = ca.iterator();
  1084. Javac jv = new Javac(cc);
  1085. try {
  1086. jv.recordLocalVariables(ca, index);
  1087. jv.recordParams(getParameterTypes(),
  1088. Modifier.isStatic(getModifiers()));
  1089. jv.setMaxLocals(ca.getMaxLocals());
  1090. jv.compileStmnt(src);
  1091. Bytecode b = jv.getBytecode();
  1092. int locals = b.getMaxLocals();
  1093. int stack = b.getMaxStack();
  1094. ca.setMaxLocals(locals);
  1095. /* We assume that there is no values in the operand stack
  1096. * at the position where the bytecode is inserted.
  1097. */
  1098. if (stack > ca.getMaxStack())
  1099. ca.setMaxStack(stack);
  1100. index = iterator.insertAt(index, b.get());
  1101. iterator.insert(b.getExceptionTable(), index);
  1102. methodInfo.rebuildStackMapIf6(cc.getClassPool(), cc.getClassFile2());
  1103. return lineNum;
  1104. }
  1105. catch (NotFoundException e) {
  1106. throw new CannotCompileException(e);
  1107. }
  1108. catch (CompileError e) {
  1109. throw new CannotCompileException(e);
  1110. }
  1111. catch (BadBytecode e) {
  1112. throw new CannotCompileException(e);
  1113. }
  1114. }
  1115. }