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 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  1. /*
  2. * Javassist, a Java-bytecode translator toolkit.
  3. * Copyright (C) 1999-2003 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. *
  10. * Software distributed under the License is distributed on an "AS IS" basis,
  11. * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  12. * for the specific language governing rights and limitations under the
  13. * License.
  14. */
  15. package javassist;
  16. import javassist.bytecode.*;
  17. import javassist.compiler.Javac;
  18. import javassist.compiler.CompileError;
  19. import javassist.expr.ExprEditor;
  20. /**
  21. * <code>CtBehavior</code> is the abstract super class of
  22. * <code>CtMethod</code> and <code>CtConstructor</code>.
  23. */
  24. public abstract class CtBehavior extends CtMember {
  25. protected MethodInfo methodInfo;
  26. protected CtBehavior(CtClass clazz, MethodInfo minfo) {
  27. super(clazz);
  28. methodInfo = minfo;
  29. }
  30. /**
  31. * Returns the MethodInfo representing this member in the
  32. * class file.
  33. */
  34. public MethodInfo getMethodInfo() {
  35. declaringClass.checkModify();
  36. return methodInfo;
  37. }
  38. /**
  39. * Undocumented method. Do not use; internal-use only.
  40. */
  41. public MethodInfo getMethodInfo2() { return methodInfo; }
  42. /**
  43. * Obtains the modifiers of the member.
  44. *
  45. * @return modifiers encoded with
  46. * <code>javassist.Modifier</code>.
  47. * @see Modifier
  48. */
  49. public int getModifiers() {
  50. return AccessFlag.toModifier(methodInfo.getAccessFlags());
  51. }
  52. /**
  53. * Sets the encoded modifiers of the member.
  54. *
  55. * @see Modifier
  56. */
  57. public void setModifiers(int mod) {
  58. declaringClass.checkModify();
  59. methodInfo.setAccessFlags(AccessFlag.of(mod));
  60. }
  61. /**
  62. * Obtains the name of this member.
  63. *
  64. * @see CtConstructor#getName()
  65. */
  66. public abstract String getName();
  67. /**
  68. * Obtains parameter types of this member.
  69. */
  70. public CtClass[] getParameterTypes() throws NotFoundException {
  71. return Descriptor.getParameterTypes(methodInfo.getDescriptor(),
  72. declaringClass.getClassPool());
  73. }
  74. /**
  75. * Obtains the type of the returned value.
  76. */
  77. CtClass getReturnType0() throws NotFoundException {
  78. return Descriptor.getReturnType(methodInfo.getDescriptor(),
  79. declaringClass.getClassPool());
  80. }
  81. /**
  82. * Returns the character string representing the parameter types
  83. * and the return type. If two members have the same parameter types
  84. * and the return type, <code>getSignature()</code> returns the
  85. * same string.
  86. */
  87. public String getSignature() {
  88. return methodInfo.getDescriptor();
  89. }
  90. /**
  91. * Obtains exceptions that this member may throw.
  92. */
  93. public CtClass[] getExceptionTypes() throws NotFoundException {
  94. String[] exceptions;
  95. ExceptionsAttribute ea = methodInfo.getExceptionsAttribute();
  96. if (ea == null)
  97. exceptions = null;
  98. else
  99. exceptions = ea.getExceptions();
  100. return declaringClass.getClassPool().get(exceptions);
  101. }
  102. /**
  103. * Sets exceptions that this member may throw.
  104. */
  105. public void setExceptionTypes(CtClass[] types) throws NotFoundException {
  106. declaringClass.checkModify();
  107. if (types == null) {
  108. methodInfo.removeExceptionsAttribute();
  109. return;
  110. }
  111. String[] names = new String[types.length];
  112. for (int i = 0; i < types.length; ++i)
  113. names[i] = types[i].getName();
  114. ExceptionsAttribute ea = methodInfo.getExceptionsAttribute();
  115. if (ea == null) {
  116. ea = new ExceptionsAttribute(methodInfo.getConstPool());
  117. methodInfo.setExceptionsAttribute(ea);
  118. }
  119. ea.setExceptions(names);
  120. }
  121. /**
  122. * Returns true if the body is empty.
  123. */
  124. public abstract boolean isEmpty();
  125. /**
  126. * Sets a member body.
  127. *
  128. * @param src the source code representing the member body.
  129. * It must be a single statement or block.
  130. */
  131. public void setBody(String src) throws CannotCompileException {
  132. declaringClass.checkModify();
  133. try {
  134. Javac jv = new Javac(declaringClass);
  135. Bytecode b = jv.compileBody(this, src);
  136. methodInfo.setCodeAttribute(b.toCodeAttribute());
  137. methodInfo.setAccessFlags(methodInfo.getAccessFlags()
  138. & ~AccessFlag.ABSTRACT);
  139. }
  140. catch (CompileError e) {
  141. throw new CannotCompileException(e);
  142. }
  143. }
  144. static void setBody0(CtClass srcClass, MethodInfo srcInfo,
  145. CtClass destClass, MethodInfo destInfo,
  146. ClassMap map)
  147. throws CannotCompileException
  148. {
  149. destClass.checkModify();
  150. if (map == null)
  151. map = new ClassMap();
  152. map.put(srcClass.getName(), destClass.getName());
  153. try {
  154. CodeAttribute cattr = srcInfo.getCodeAttribute();
  155. if (cattr != null) {
  156. ConstPool cp = destInfo.getConstPool();
  157. CodeAttribute ca = (CodeAttribute)cattr.copy(cp, map);
  158. destInfo.setCodeAttribute(ca);
  159. }
  160. }
  161. catch (CodeAttribute.RuntimeCopyException e) {
  162. /* the exception may be thrown by copy() in CodeAttribute.
  163. */
  164. throw new CannotCompileException(e);
  165. }
  166. destInfo.setAccessFlags(destInfo.getAccessFlags()
  167. & ~AccessFlag.ABSTRACT);
  168. }
  169. /**
  170. * Obtains an attribute with the given name.
  171. * If that attribute is not found in the class file, this
  172. * method returns null.
  173. *
  174. * @param name attribute name
  175. */
  176. public byte[] getAttribute(String name) {
  177. AttributeInfo ai = methodInfo.getAttribute(name);
  178. if (ai == null)
  179. return null;
  180. else
  181. return ai.get();
  182. }
  183. /**
  184. * Adds an attribute. The attribute is saved in the class file.
  185. *
  186. * @param name attribute name
  187. * @param data attribute value
  188. */
  189. public void setAttribute(String name, byte[] data) {
  190. declaringClass.checkModify();
  191. methodInfo.addAttribute(new AttributeInfo(methodInfo.getConstPool(),
  192. name, data));
  193. }
  194. /**
  195. * Declares to use <code>$cflow</code> for this member;
  196. * If <code>$cflow</code> is used, the class files modified
  197. * with Javassist requires a support class
  198. * <code>javassist.runtime.Cflow</code> at runtime
  199. * (other Javassist classes are not required at runtime).
  200. *
  201. * <p>Every <code>$cflow</code> variable is given a unique name.
  202. * For example, if the given name is <code>"Point.paint"</code>,
  203. * then the variable is indicated by <code>$cflow(Point.paint)</code>.
  204. *
  205. * @param name <code>$cflow</code> name. It can include
  206. * alphabets, numbers, <code>_</code>,
  207. * <code>$</code>, and <code>.</code> (dot).
  208. *
  209. * @see javassist.runtime.Cflow
  210. */
  211. public void useCflow(String name) throws CannotCompileException {
  212. CtClass cc = declaringClass;
  213. cc.checkModify();
  214. ClassPool pool = cc.getClassPool();
  215. String fname;
  216. int i = 0;
  217. while (true) {
  218. fname = "_cflow$" + i++;
  219. try {
  220. cc.getDeclaredField(fname);
  221. }
  222. catch(NotFoundException e) {
  223. break;
  224. }
  225. }
  226. pool.recordCflow(name, declaringClass.getName(), fname);
  227. try {
  228. CtClass type = pool.get("javassist.runtime.Cflow");
  229. CtField field = new CtField(type, fname, cc);
  230. field.setModifiers(Modifier.PUBLIC | Modifier.STATIC);
  231. cc.addField(field, CtField.Initializer.byNew(type));
  232. insertBefore(fname + ".enter();");
  233. String src = fname + ".exit();";
  234. insertAfter(src, true);
  235. }
  236. catch (NotFoundException e) {
  237. throw new CannotCompileException(e);
  238. }
  239. }
  240. /**
  241. * Modifies the member body.
  242. *
  243. * @param converter specifies how to modify.
  244. */
  245. public void instrument(CodeConverter converter)
  246. throws CannotCompileException
  247. {
  248. declaringClass.checkModify();
  249. ConstPool cp = methodInfo.getConstPool();
  250. converter.doit(getDeclaringClass(), methodInfo, cp);
  251. }
  252. /**
  253. * Modifies the member body.
  254. *
  255. * @param editor specifies how to modify.
  256. */
  257. public void instrument(ExprEditor editor)
  258. throws CannotCompileException
  259. {
  260. // if the class is not frozen,
  261. // does not trun the modified flag on.
  262. if (declaringClass.isFrozen())
  263. declaringClass.checkModify();
  264. if (editor.doit(declaringClass, methodInfo))
  265. declaringClass.checkModify();
  266. }
  267. /**
  268. * Inserts bytecode at the beginning of the body.
  269. *
  270. * @param src the source code representing the inserted bytecode.
  271. * It must be a single statement or block.
  272. */
  273. public void insertBefore(String src) throws CannotCompileException {
  274. declaringClass.checkModify();
  275. CodeAttribute ca = methodInfo.getCodeAttribute();
  276. if (ca == null)
  277. throw new CannotCompileException("no method body");
  278. CodeIterator iterator = ca.iterator();
  279. Javac jv = new Javac(declaringClass);
  280. try {
  281. jv.recordParams(getParameterTypes(),
  282. Modifier.isStatic(getModifiers()));
  283. jv.compileStmnt(src);
  284. Bytecode b = jv.getBytecode();
  285. int stack = b.getMaxStack();
  286. int locals = b.getMaxLocals();
  287. if (stack > ca.getMaxStack())
  288. ca.setMaxStack(stack);
  289. if (locals > ca.getMaxLocals())
  290. ca.setMaxLocals(locals);
  291. int pos = iterator.insertEx(b.get());
  292. iterator.insert(b.getExceptionTable(), pos);
  293. }
  294. catch (NotFoundException e) {
  295. throw new CannotCompileException(e);
  296. }
  297. catch (CompileError e) {
  298. throw new CannotCompileException(e);
  299. }
  300. catch (BadBytecode e) {
  301. throw new CannotCompileException(e);
  302. }
  303. }
  304. /**
  305. * Inserts bytecode at the end of the body.
  306. * The bytecode is inserted just before every return insturction.
  307. * It is not executed when an exception is thrown.
  308. *
  309. * @param src the source code representing the inserted bytecode.
  310. * It must be a single statement or block.
  311. */
  312. public void insertAfter(String src)
  313. throws CannotCompileException
  314. {
  315. insertAfter(src, false);
  316. }
  317. /**
  318. * Inserts bytecode at the end of the body.
  319. * The bytecode is inserted just before every return insturction.
  320. *
  321. * @param src the source code representing the inserted bytecode.
  322. * It must be a single statement or block.
  323. * @param asFinally true if the inserted bytecode is executed
  324. * not only when the control normally returns
  325. * but also when an exception is thrown.
  326. */
  327. public void insertAfter(String src, boolean asFinally)
  328. throws CannotCompileException
  329. {
  330. declaringClass.checkModify();
  331. CodeAttribute ca = methodInfo.getCodeAttribute();
  332. if (ca == null)
  333. throw new CannotCompileException("no method body");
  334. CodeIterator iterator = ca.iterator();
  335. int retAddr = ca.getMaxLocals();
  336. Bytecode b = new Bytecode(methodInfo.getConstPool(), 0, retAddr + 1);
  337. b.setStackDepth(ca.getMaxStack() + 1);
  338. Javac jv = new Javac(b, declaringClass);
  339. try {
  340. jv.recordParams(getParameterTypes(),
  341. Modifier.isStatic(getModifiers()));
  342. CtClass rtype = getReturnType0();
  343. int varNo = jv.recordReturnType(rtype, true);
  344. boolean isVoid = rtype == CtClass.voidType;
  345. int handlerLen = insertAfterHandler(asFinally, b, rtype);
  346. b.addAstore(retAddr);
  347. if (isVoid) {
  348. b.addOpcode(Opcode.ACONST_NULL);
  349. b.addAstore(varNo);
  350. jv.compileStmnt(src);
  351. }
  352. else {
  353. b.addStore(varNo, rtype);
  354. jv.compileStmnt(src);
  355. b.addLoad(varNo, rtype);
  356. }
  357. b.addRet(retAddr);
  358. ca.setMaxStack(b.getMaxStack());
  359. ca.setMaxLocals(b.getMaxLocals());
  360. int gapPos = iterator.append(b.get());
  361. iterator.append(b.getExceptionTable(), gapPos);
  362. if (asFinally)
  363. ca.getExceptionTable().add(0, gapPos, gapPos, 0);
  364. int gapLen = iterator.getCodeLength() - gapPos - handlerLen;
  365. int subr = iterator.getCodeLength() - gapLen;
  366. while (iterator.hasNext()) {
  367. int pos = iterator.next();
  368. if (pos >= subr)
  369. break;
  370. int c = iterator.byteAt(pos);
  371. if (c == Opcode.ARETURN || c == Opcode.IRETURN
  372. || c == Opcode.FRETURN || c == Opcode.LRETURN
  373. || c == Opcode.DRETURN || c == Opcode.RETURN) {
  374. if (subr - pos > Short.MAX_VALUE - 5) {
  375. int s = iterator.insertGap(pos, 5);
  376. iterator.writeByte(Opcode.JSR_W, pos);
  377. iterator.write32bit(subr - pos + s, pos + 1);
  378. }
  379. else {
  380. int s = iterator.insertGap(pos, 3);
  381. iterator.writeByte(Opcode.JSR, pos);
  382. iterator.write16bit(subr - pos + s, pos + 1);
  383. }
  384. subr = iterator.getCodeLength() - gapLen;
  385. }
  386. }
  387. }
  388. catch (NotFoundException e) {
  389. throw new CannotCompileException(e);
  390. }
  391. catch (CompileError e) {
  392. throw new CannotCompileException(e);
  393. }
  394. catch (BadBytecode e) {
  395. throw new CannotCompileException(e);
  396. }
  397. }
  398. private int insertAfterHandler(boolean asFinally, Bytecode b,
  399. CtClass rtype)
  400. {
  401. if (!asFinally)
  402. return 0;
  403. int var = b.getMaxLocals();
  404. b.incMaxLocals(1);
  405. int pc = b.currentPc();
  406. b.addAstore(var);
  407. if (rtype.isPrimitive()) {
  408. char c = ((CtPrimitiveType)rtype).getDescriptor();
  409. if (c == 'D')
  410. b.addDconst(0.0);
  411. else if (c == 'F')
  412. b.addFconst(0);
  413. else if (c == 'J')
  414. b.addLconst(0);
  415. else if (c != 'V') // int, boolean, char, short, ...
  416. b.addIconst(0);
  417. }
  418. else
  419. b.addOpcode(Opcode.ACONST_NULL);
  420. b.addOpcode(Opcode.JSR);
  421. int pc2 = b.currentPc();
  422. b.addIndex(0); // correct later
  423. b.addAload(var);
  424. b.addOpcode(Opcode.ATHROW);
  425. int pc3 = b.currentPc();
  426. b.write16bit(pc2, pc3 - pc2 + 1);
  427. return pc3 - pc;
  428. }
  429. /* -- OLD version --
  430. public void insertAfter(String src) throws CannotCompileException {
  431. declaringClass.checkModify();
  432. CodeAttribute ca = methodInfo.getCodeAttribute();
  433. CodeIterator iterator = ca.iterator();
  434. Bytecode b = new Bytecode(methodInfo.getConstPool(),
  435. ca.getMaxStack(), ca.getMaxLocals());
  436. b.setStackDepth(ca.getMaxStack());
  437. Javac jv = new Javac(b, declaringClass);
  438. try {
  439. jv.recordParams(getParameterTypes(),
  440. Modifier.isStatic(getModifiers()));
  441. CtClass rtype = getReturnType0();
  442. int varNo = jv.recordReturnType(rtype, true);
  443. boolean isVoid = rtype == CtClass.voidType;
  444. if (isVoid) {
  445. b.addOpcode(Opcode.ACONST_NULL);
  446. b.addAstore(varNo);
  447. jv.compileStmnt(src);
  448. }
  449. else {
  450. b.addStore(varNo, rtype);
  451. jv.compileStmnt(src);
  452. b.addLoad(varNo, rtype);
  453. }
  454. byte[] code = b.get();
  455. ca.setMaxStack(b.getMaxStack());
  456. ca.setMaxLocals(b.getMaxLocals());
  457. while (iterator.hasNext()) {
  458. int pos = iterator.next();
  459. int c = iterator.byteAt(pos);
  460. if (c == Opcode.ARETURN || c == Opcode.IRETURN
  461. || c == Opcode.FRETURN || c == Opcode.LRETURN
  462. || c == Opcode.DRETURN || c == Opcode.RETURN)
  463. iterator.insert(pos, code);
  464. }
  465. }
  466. catch (NotFoundException e) {
  467. throw new CannotCompileException(e);
  468. }
  469. catch (CompileError e) {
  470. throw new CannotCompileException(e);
  471. }
  472. catch (BadBytecode e) {
  473. throw new CannotCompileException(e);
  474. }
  475. }
  476. */
  477. /**
  478. * Adds a catch clause that handles an exception thrown in the
  479. * body. The catch clause must end with a return or throw statement.
  480. *
  481. * @param src the source code representing the catch clause.
  482. * It must be a single statement or block.
  483. * @param exceptionType the type of the exception handled by the
  484. * catch clause.
  485. */
  486. public void addCatch(String src, CtClass exceptionType)
  487. throws CannotCompileException
  488. {
  489. addCatch(src, exceptionType, "$e");
  490. }
  491. /**
  492. * Adds a catch clause that handles an exception thrown in the
  493. * body. The catch clause must end with a return or throw statement.
  494. *
  495. * @param src the source code representing the catch clause.
  496. * It must be a single statement or block.
  497. * @param exceptionType the type of the exception handled by the
  498. * catch clause.
  499. * @param exceptionName the name of the variable containing the
  500. * caught exception, for example,
  501. * <code>$e</code>.
  502. */
  503. public void addCatch(String src, CtClass exceptionType,
  504. String exceptionName)
  505. throws CannotCompileException
  506. {
  507. declaringClass.checkModify();
  508. ConstPool cp = methodInfo.getConstPool();
  509. CodeAttribute ca = methodInfo.getCodeAttribute();
  510. CodeIterator iterator = ca.iterator();
  511. Bytecode b = new Bytecode(cp, ca.getMaxStack(), ca.getMaxLocals());
  512. b.setStackDepth(1);
  513. Javac jv = new Javac(b, declaringClass);
  514. try {
  515. jv.recordParams(getParameterTypes(),
  516. Modifier.isStatic(getModifiers()));
  517. int var = jv.recordVariable(exceptionType, exceptionName);
  518. b.addAstore(var);
  519. jv.compileStmnt(src);
  520. int stack = b.getMaxStack();
  521. int locals = b.getMaxLocals();
  522. if (stack > ca.getMaxStack())
  523. ca.setMaxStack(stack);
  524. if (locals > ca.getMaxLocals())
  525. ca.setMaxLocals(locals);
  526. int len = iterator.getCodeLength();
  527. int pos = iterator.append(b.get());
  528. ca.getExceptionTable().add(0, len, len,
  529. cp.addClassInfo(exceptionType));
  530. iterator.append(b.getExceptionTable(), pos);
  531. }
  532. catch (NotFoundException e) {
  533. throw new CannotCompileException(e);
  534. }
  535. catch (CompileError e) {
  536. throw new CannotCompileException(e);
  537. }
  538. }
  539. }