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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  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. * If it is <code>null</code>, the substituted member
  131. * body does nothing except returning zero or null.
  132. */
  133. public void setBody(String src) throws CannotCompileException {
  134. declaringClass.checkModify();
  135. try {
  136. Javac jv = new Javac(declaringClass);
  137. Bytecode b = jv.compileBody(this, src);
  138. methodInfo.setCodeAttribute(b.toCodeAttribute());
  139. methodInfo.setAccessFlags(methodInfo.getAccessFlags()
  140. & ~AccessFlag.ABSTRACT);
  141. }
  142. catch (CompileError e) {
  143. throw new CannotCompileException(e);
  144. }
  145. }
  146. static void setBody0(CtClass srcClass, MethodInfo srcInfo,
  147. CtClass destClass, MethodInfo destInfo,
  148. ClassMap map)
  149. throws CannotCompileException
  150. {
  151. destClass.checkModify();
  152. if (map == null)
  153. map = new ClassMap();
  154. map.put(srcClass.getName(), destClass.getName());
  155. try {
  156. CodeAttribute cattr = srcInfo.getCodeAttribute();
  157. if (cattr != null) {
  158. ConstPool cp = destInfo.getConstPool();
  159. CodeAttribute ca = (CodeAttribute)cattr.copy(cp, map);
  160. destInfo.setCodeAttribute(ca);
  161. }
  162. }
  163. catch (CodeAttribute.RuntimeCopyException e) {
  164. /* the exception may be thrown by copy() in CodeAttribute.
  165. */
  166. throw new CannotCompileException(e);
  167. }
  168. destInfo.setAccessFlags(destInfo.getAccessFlags()
  169. & ~AccessFlag.ABSTRACT);
  170. }
  171. /**
  172. * Obtains an attribute with the given name.
  173. * If that attribute is not found in the class file, this
  174. * method returns null.
  175. *
  176. * @param name attribute name
  177. */
  178. public byte[] getAttribute(String name) {
  179. AttributeInfo ai = methodInfo.getAttribute(name);
  180. if (ai == null)
  181. return null;
  182. else
  183. return ai.get();
  184. }
  185. /**
  186. * Adds an attribute. The attribute is saved in the class file.
  187. *
  188. * @param name attribute name
  189. * @param data attribute value
  190. */
  191. public void setAttribute(String name, byte[] data) {
  192. declaringClass.checkModify();
  193. methodInfo.addAttribute(new AttributeInfo(methodInfo.getConstPool(),
  194. name, data));
  195. }
  196. /**
  197. * Declares to use <code>$cflow</code> for this member;
  198. * If <code>$cflow</code> is used, the class files modified
  199. * with Javassist requires a support class
  200. * <code>javassist.runtime.Cflow</code> at runtime
  201. * (other Javassist classes are not required at runtime).
  202. *
  203. * <p>Every <code>$cflow</code> variable is given a unique name.
  204. * For example, if the given name is <code>"Point.paint"</code>,
  205. * then the variable is indicated by <code>$cflow(Point.paint)</code>.
  206. *
  207. * @param name <code>$cflow</code> name. It can include
  208. * alphabets, numbers, <code>_</code>,
  209. * <code>$</code>, and <code>.</code> (dot).
  210. *
  211. * @see javassist.runtime.Cflow
  212. */
  213. public void useCflow(String name) throws CannotCompileException {
  214. CtClass cc = declaringClass;
  215. cc.checkModify();
  216. ClassPool pool = cc.getClassPool();
  217. String fname;
  218. int i = 0;
  219. while (true) {
  220. fname = "_cflow$" + i++;
  221. try {
  222. cc.getDeclaredField(fname);
  223. }
  224. catch(NotFoundException e) {
  225. break;
  226. }
  227. }
  228. pool.recordCflow(name, declaringClass.getName(), fname);
  229. try {
  230. CtClass type = pool.get("javassist.runtime.Cflow");
  231. CtField field = new CtField(type, fname, cc);
  232. field.setModifiers(Modifier.PUBLIC | Modifier.STATIC);
  233. cc.addField(field, CtField.Initializer.byNew(type));
  234. insertBefore(fname + ".enter();");
  235. String src = fname + ".exit();";
  236. insertAfter(src, true);
  237. }
  238. catch (NotFoundException e) {
  239. throw new CannotCompileException(e);
  240. }
  241. }
  242. /**
  243. * Modifies the member body.
  244. *
  245. * @param converter specifies how to modify.
  246. */
  247. public void instrument(CodeConverter converter)
  248. throws CannotCompileException
  249. {
  250. declaringClass.checkModify();
  251. ConstPool cp = methodInfo.getConstPool();
  252. converter.doit(getDeclaringClass(), methodInfo, cp);
  253. }
  254. /**
  255. * Modifies the member body.
  256. *
  257. * @param editor specifies how to modify.
  258. */
  259. public void instrument(ExprEditor editor)
  260. throws CannotCompileException
  261. {
  262. // if the class is not frozen,
  263. // does not trun the modified flag on.
  264. if (declaringClass.isFrozen())
  265. declaringClass.checkModify();
  266. if (editor.doit(declaringClass, methodInfo))
  267. declaringClass.checkModify();
  268. }
  269. /**
  270. * Inserts bytecode at the beginning of the body.
  271. *
  272. * @param src the source code representing the inserted bytecode.
  273. * It must be a single statement or block.
  274. */
  275. public void insertBefore(String src) throws CannotCompileException {
  276. declaringClass.checkModify();
  277. CodeAttribute ca = methodInfo.getCodeAttribute();
  278. if (ca == null)
  279. throw new CannotCompileException("no method body");
  280. CodeIterator iterator = ca.iterator();
  281. Javac jv = new Javac(declaringClass);
  282. try {
  283. jv.recordParams(getParameterTypes(),
  284. Modifier.isStatic(getModifiers()));
  285. jv.compileStmnt(src);
  286. Bytecode b = jv.getBytecode();
  287. int stack = b.getMaxStack();
  288. int locals = b.getMaxLocals();
  289. if (stack > ca.getMaxStack())
  290. ca.setMaxStack(stack);
  291. if (locals > ca.getMaxLocals())
  292. ca.setMaxLocals(locals);
  293. int pos = iterator.insertEx(b.get());
  294. iterator.insert(b.getExceptionTable(), pos);
  295. }
  296. catch (NotFoundException e) {
  297. throw new CannotCompileException(e);
  298. }
  299. catch (CompileError e) {
  300. throw new CannotCompileException(e);
  301. }
  302. catch (BadBytecode e) {
  303. throw new CannotCompileException(e);
  304. }
  305. }
  306. /**
  307. * Inserts bytecode at the end of the body.
  308. * The bytecode is inserted just before every return insturction.
  309. * It is not executed when an exception is thrown.
  310. *
  311. * @param src the source code representing the inserted bytecode.
  312. * It must be a single statement or block.
  313. */
  314. public void insertAfter(String src)
  315. throws CannotCompileException
  316. {
  317. insertAfter(src, false);
  318. }
  319. /**
  320. * Inserts bytecode at the end of the body.
  321. * The bytecode is inserted just before every return insturction.
  322. *
  323. * @param src the source code representing the inserted bytecode.
  324. * It must be a single statement or block.
  325. * @param asFinally true if the inserted bytecode is executed
  326. * not only when the control normally returns
  327. * but also when an exception is thrown.
  328. */
  329. public void insertAfter(String src, boolean asFinally)
  330. throws CannotCompileException
  331. {
  332. declaringClass.checkModify();
  333. CodeAttribute ca = methodInfo.getCodeAttribute();
  334. if (ca == null)
  335. throw new CannotCompileException("no method body");
  336. CodeIterator iterator = ca.iterator();
  337. int retAddr = ca.getMaxLocals();
  338. Bytecode b = new Bytecode(methodInfo.getConstPool(), 0, retAddr + 1);
  339. b.setStackDepth(ca.getMaxStack() + 1);
  340. Javac jv = new Javac(b, declaringClass);
  341. try {
  342. jv.recordParams(getParameterTypes(),
  343. Modifier.isStatic(getModifiers()));
  344. CtClass rtype = getReturnType0();
  345. int varNo = jv.recordReturnType(rtype, true);
  346. boolean isVoid = rtype == CtClass.voidType;
  347. int handlerLen = insertAfterHandler(asFinally, b, rtype);
  348. b.addAstore(retAddr);
  349. if (isVoid) {
  350. b.addOpcode(Opcode.ACONST_NULL);
  351. b.addAstore(varNo);
  352. jv.compileStmnt(src);
  353. }
  354. else {
  355. b.addStore(varNo, rtype);
  356. jv.compileStmnt(src);
  357. b.addLoad(varNo, rtype);
  358. }
  359. b.addRet(retAddr);
  360. ca.setMaxStack(b.getMaxStack());
  361. ca.setMaxLocals(b.getMaxLocals());
  362. int gapPos = iterator.append(b.get());
  363. iterator.append(b.getExceptionTable(), gapPos);
  364. if (asFinally)
  365. ca.getExceptionTable().add(0, gapPos, gapPos, 0);
  366. int gapLen = iterator.getCodeLength() - gapPos - handlerLen;
  367. int subr = iterator.getCodeLength() - gapLen;
  368. while (iterator.hasNext()) {
  369. int pos = iterator.next();
  370. if (pos >= subr)
  371. break;
  372. int c = iterator.byteAt(pos);
  373. if (c == Opcode.ARETURN || c == Opcode.IRETURN
  374. || c == Opcode.FRETURN || c == Opcode.LRETURN
  375. || c == Opcode.DRETURN || c == Opcode.RETURN) {
  376. if (subr - pos > Short.MAX_VALUE - 5) {
  377. int s = iterator.insertGap(pos, 5);
  378. iterator.writeByte(Opcode.JSR_W, pos);
  379. iterator.write32bit(subr - pos + s, pos + 1);
  380. }
  381. else {
  382. int s = iterator.insertGap(pos, 3);
  383. iterator.writeByte(Opcode.JSR, pos);
  384. iterator.write16bit(subr - pos + s, pos + 1);
  385. }
  386. subr = iterator.getCodeLength() - gapLen;
  387. }
  388. }
  389. }
  390. catch (NotFoundException e) {
  391. throw new CannotCompileException(e);
  392. }
  393. catch (CompileError e) {
  394. throw new CannotCompileException(e);
  395. }
  396. catch (BadBytecode e) {
  397. throw new CannotCompileException(e);
  398. }
  399. }
  400. private int insertAfterHandler(boolean asFinally, Bytecode b,
  401. CtClass rtype)
  402. {
  403. if (!asFinally)
  404. return 0;
  405. int var = b.getMaxLocals();
  406. b.incMaxLocals(1);
  407. int pc = b.currentPc();
  408. b.addAstore(var);
  409. if (rtype.isPrimitive()) {
  410. char c = ((CtPrimitiveType)rtype).getDescriptor();
  411. if (c == 'D')
  412. b.addDconst(0.0);
  413. else if (c == 'F')
  414. b.addFconst(0);
  415. else if (c == 'J')
  416. b.addLconst(0);
  417. else if (c != 'V') // int, boolean, char, short, ...
  418. b.addIconst(0);
  419. }
  420. else
  421. b.addOpcode(Opcode.ACONST_NULL);
  422. b.addOpcode(Opcode.JSR);
  423. int pc2 = b.currentPc();
  424. b.addIndex(0); // correct later
  425. b.addAload(var);
  426. b.addOpcode(Opcode.ATHROW);
  427. int pc3 = b.currentPc();
  428. b.write16bit(pc2, pc3 - pc2 + 1);
  429. return pc3 - pc;
  430. }
  431. /* -- OLD version --
  432. public void insertAfter(String src) throws CannotCompileException {
  433. declaringClass.checkModify();
  434. CodeAttribute ca = methodInfo.getCodeAttribute();
  435. CodeIterator iterator = ca.iterator();
  436. Bytecode b = new Bytecode(methodInfo.getConstPool(),
  437. ca.getMaxStack(), ca.getMaxLocals());
  438. b.setStackDepth(ca.getMaxStack());
  439. Javac jv = new Javac(b, declaringClass);
  440. try {
  441. jv.recordParams(getParameterTypes(),
  442. Modifier.isStatic(getModifiers()));
  443. CtClass rtype = getReturnType0();
  444. int varNo = jv.recordReturnType(rtype, true);
  445. boolean isVoid = rtype == CtClass.voidType;
  446. if (isVoid) {
  447. b.addOpcode(Opcode.ACONST_NULL);
  448. b.addAstore(varNo);
  449. jv.compileStmnt(src);
  450. }
  451. else {
  452. b.addStore(varNo, rtype);
  453. jv.compileStmnt(src);
  454. b.addLoad(varNo, rtype);
  455. }
  456. byte[] code = b.get();
  457. ca.setMaxStack(b.getMaxStack());
  458. ca.setMaxLocals(b.getMaxLocals());
  459. while (iterator.hasNext()) {
  460. int pos = iterator.next();
  461. int c = iterator.byteAt(pos);
  462. if (c == Opcode.ARETURN || c == Opcode.IRETURN
  463. || c == Opcode.FRETURN || c == Opcode.LRETURN
  464. || c == Opcode.DRETURN || c == Opcode.RETURN)
  465. iterator.insert(pos, code);
  466. }
  467. }
  468. catch (NotFoundException e) {
  469. throw new CannotCompileException(e);
  470. }
  471. catch (CompileError e) {
  472. throw new CannotCompileException(e);
  473. }
  474. catch (BadBytecode e) {
  475. throw new CannotCompileException(e);
  476. }
  477. }
  478. */
  479. /**
  480. * Adds a catch clause that handles an exception thrown in the
  481. * body. The catch clause must end with a return or throw statement.
  482. *
  483. * @param src the source code representing the catch clause.
  484. * It must be a single statement or block.
  485. * @param exceptionType the type of the exception handled by the
  486. * catch clause.
  487. */
  488. public void addCatch(String src, CtClass exceptionType)
  489. throws CannotCompileException
  490. {
  491. addCatch(src, exceptionType, "$e");
  492. }
  493. /**
  494. * Adds a catch clause that handles an exception thrown in the
  495. * body. The catch clause must end with a return or throw statement.
  496. *
  497. * @param src the source code representing the catch clause.
  498. * It must be a single statement or block.
  499. * @param exceptionType the type of the exception handled by the
  500. * catch clause.
  501. * @param exceptionName the name of the variable containing the
  502. * caught exception, for example,
  503. * <code>$e</code>.
  504. */
  505. public void addCatch(String src, CtClass exceptionType,
  506. String exceptionName)
  507. throws CannotCompileException
  508. {
  509. declaringClass.checkModify();
  510. ConstPool cp = methodInfo.getConstPool();
  511. CodeAttribute ca = methodInfo.getCodeAttribute();
  512. CodeIterator iterator = ca.iterator();
  513. Bytecode b = new Bytecode(cp, ca.getMaxStack(), ca.getMaxLocals());
  514. b.setStackDepth(1);
  515. Javac jv = new Javac(b, declaringClass);
  516. try {
  517. jv.recordParams(getParameterTypes(),
  518. Modifier.isStatic(getModifiers()));
  519. int var = jv.recordVariable(exceptionType, exceptionName);
  520. b.addAstore(var);
  521. jv.compileStmnt(src);
  522. int stack = b.getMaxStack();
  523. int locals = b.getMaxLocals();
  524. if (stack > ca.getMaxStack())
  525. ca.setMaxStack(stack);
  526. if (locals > ca.getMaxLocals())
  527. ca.setMaxLocals(locals);
  528. int len = iterator.getCodeLength();
  529. int pos = iterator.append(b.get());
  530. ca.getExceptionTable().add(0, len, len,
  531. cp.addClassInfo(exceptionType));
  532. iterator.append(b.getExceptionTable(), pos);
  533. }
  534. catch (NotFoundException e) {
  535. throw new CannotCompileException(e);
  536. }
  537. catch (CompileError e) {
  538. throw new CannotCompileException(e);
  539. }
  540. }
  541. }