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.

ClassFile.java 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  1. /*
  2. * Javassist, a Java-bytecode translator toolkit.
  3. * Copyright (C) 1999-2006 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.bytecode;
  16. import java.io.DataInputStream;
  17. import java.io.DataOutputStream;
  18. import java.io.IOException;
  19. import java.util.ArrayList;
  20. import java.util.LinkedList;
  21. import java.util.List;
  22. import java.util.ListIterator;
  23. import java.util.Map;
  24. import javassist.CannotCompileException;
  25. /**
  26. * <code>ClassFile</code> represents a Java <code>.class</code> file, which
  27. * consists of a constant pool, methods, fields, and attributes.
  28. *
  29. * @see javassist.CtClass#getClassFile()
  30. */
  31. public final class ClassFile {
  32. int major, minor; // version number
  33. ConstPool constPool;
  34. int thisClass;
  35. int accessFlags;
  36. int superClass;
  37. int[] interfaces;
  38. ArrayList fields;
  39. ArrayList methods;
  40. LinkedList attributes;
  41. String thisclassname; // not JVM-internal name
  42. String[] cachedInterfaces;
  43. String cachedSuperclass;
  44. /**
  45. * Constructs a class file from a byte stream.
  46. */
  47. public ClassFile(DataInputStream in) throws IOException {
  48. read(in);
  49. }
  50. /**
  51. * Constructs a class file including no members.
  52. *
  53. * @param isInterface
  54. * true if this is an interface. false if this is a class.
  55. * @param classname
  56. * a fully-qualified class name
  57. * @param superclass
  58. * a fully-qualified super class name
  59. */
  60. public ClassFile(boolean isInterface, String classname, String superclass) {
  61. major = 45;
  62. minor = 3; // JDK 1.1 or later
  63. constPool = new ConstPool(classname);
  64. thisClass = constPool.getThisClassInfo();
  65. if (isInterface)
  66. accessFlags = AccessFlag.SUPER | AccessFlag.INTERFACE
  67. | AccessFlag.ABSTRACT;
  68. else
  69. accessFlags = AccessFlag.SUPER;
  70. initSuperclass(superclass);
  71. interfaces = null;
  72. fields = new ArrayList();
  73. methods = new ArrayList();
  74. thisclassname = classname;
  75. attributes = new LinkedList();
  76. attributes.add(new SourceFileAttribute(constPool,
  77. getSourcefileName(thisclassname)));
  78. }
  79. private void initSuperclass(String superclass) {
  80. if (superclass != null) {
  81. this.superClass = constPool.addClassInfo(superclass);
  82. cachedSuperclass = superclass;
  83. }
  84. else {
  85. this.superClass = constPool.addClassInfo("java.lang.Object");
  86. cachedSuperclass = "java.lang.Object";
  87. }
  88. }
  89. private static String getSourcefileName(String qname) {
  90. int index = qname.lastIndexOf('.');
  91. if (index >= 0)
  92. qname = qname.substring(index + 1);
  93. return qname + ".java";
  94. }
  95. /**
  96. * Eliminates dead constant pool items. If a method or a field is removed,
  97. * the constant pool items used by that method/field become dead items. This
  98. * method recreates a constant pool.
  99. */
  100. public void compact() {
  101. ConstPool cp = compact0();
  102. ArrayList list = methods;
  103. int n = list.size();
  104. for (int i = 0; i < n; ++i) {
  105. MethodInfo minfo = (MethodInfo)list.get(i);
  106. minfo.compact(cp);
  107. }
  108. list = fields;
  109. n = list.size();
  110. for (int i = 0; i < n; ++i) {
  111. FieldInfo finfo = (FieldInfo)list.get(i);
  112. finfo.compact(cp);
  113. }
  114. attributes = AttributeInfo.copyAll(attributes, cp);
  115. constPool = cp;
  116. }
  117. private ConstPool compact0() {
  118. ConstPool cp = new ConstPool(thisclassname);
  119. thisClass = cp.getThisClassInfo();
  120. String sc = getSuperclass();
  121. if (sc != null)
  122. superClass = cp.addClassInfo(getSuperclass());
  123. if (interfaces != null) {
  124. int n = interfaces.length;
  125. for (int i = 0; i < n; ++i)
  126. interfaces[i]
  127. = cp.addClassInfo(constPool.getClassInfo(interfaces[i]));
  128. }
  129. return cp;
  130. }
  131. /**
  132. * Discards all attributes, associated with both the class file and the
  133. * members such as a code attribute and exceptions attribute. The unused
  134. * constant pool entries are also discarded (a new packed constant pool is
  135. * constructed).
  136. */
  137. public void prune() {
  138. ConstPool cp = compact0();
  139. LinkedList newAttributes = new LinkedList();
  140. AttributeInfo invisibleAnnotations
  141. = getAttribute(AnnotationsAttribute.invisibleTag);
  142. if (invisibleAnnotations != null) {
  143. invisibleAnnotations = invisibleAnnotations.copy(cp, null);
  144. newAttributes.add(invisibleAnnotations);
  145. }
  146. AttributeInfo visibleAnnotations
  147. = getAttribute(AnnotationsAttribute.visibleTag);
  148. if (visibleAnnotations != null) {
  149. visibleAnnotations = visibleAnnotations.copy(cp, null);
  150. newAttributes.add(visibleAnnotations);
  151. }
  152. ArrayList list = methods;
  153. int n = list.size();
  154. for (int i = 0; i < n; ++i) {
  155. MethodInfo minfo = (MethodInfo)list.get(i);
  156. minfo.prune(cp);
  157. }
  158. list = fields;
  159. n = list.size();
  160. for (int i = 0; i < n; ++i) {
  161. FieldInfo finfo = (FieldInfo)list.get(i);
  162. finfo.prune(cp);
  163. }
  164. attributes = newAttributes;
  165. cp.prune();
  166. constPool = cp;
  167. }
  168. /**
  169. * Returns a constant pool table.
  170. */
  171. public ConstPool getConstPool() {
  172. return constPool;
  173. }
  174. /**
  175. * Returns true if this is an interface.
  176. */
  177. public boolean isInterface() {
  178. return (accessFlags & AccessFlag.INTERFACE) != 0;
  179. }
  180. /**
  181. * Returns true if this is a final class or interface.
  182. */
  183. public boolean isFinal() {
  184. return (accessFlags & AccessFlag.FINAL) != 0;
  185. }
  186. /**
  187. * Returns true if this is an abstract class or an interface.
  188. */
  189. public boolean isAbstract() {
  190. return (accessFlags & AccessFlag.ABSTRACT) != 0;
  191. }
  192. /**
  193. * Returns access flags.
  194. *
  195. * @see javassist.bytecode.AccessFlag
  196. */
  197. public int getAccessFlags() {
  198. return accessFlags;
  199. }
  200. /**
  201. * Changes access flags.
  202. *
  203. * @see javassist.bytecode.AccessFlag
  204. */
  205. public void setAccessFlags(int acc) {
  206. accessFlags = acc | AccessFlag.SUPER;
  207. }
  208. /**
  209. * Returns the class name.
  210. */
  211. public String getName() {
  212. return thisclassname;
  213. }
  214. /**
  215. * Sets the class name. This method substitutes the new name for all
  216. * occurrences of the old class name in the class file.
  217. */
  218. public void setName(String name) {
  219. renameClass(thisclassname, name);
  220. }
  221. /**
  222. * Returns the super class name.
  223. */
  224. public String getSuperclass() {
  225. if (cachedSuperclass == null)
  226. cachedSuperclass = constPool.getClassInfo(superClass);
  227. return cachedSuperclass;
  228. }
  229. /**
  230. * Returns the index of the constant pool entry representing the super
  231. * class.
  232. */
  233. public int getSuperclassId() {
  234. return superClass;
  235. }
  236. /**
  237. * Sets the super class.
  238. *
  239. * <p>
  240. * This method modifies constructors so that they call constructors declared
  241. * in the new super class.
  242. */
  243. public void setSuperclass(String superclass) throws CannotCompileException {
  244. if (superclass == null)
  245. superclass = "java.lang.Object";
  246. try {
  247. this.superClass = constPool.addClassInfo(superclass);
  248. ArrayList list = methods;
  249. int n = list.size();
  250. for (int i = 0; i < n; ++i) {
  251. MethodInfo minfo = (MethodInfo)list.get(i);
  252. minfo.setSuperclass(superclass);
  253. }
  254. }
  255. catch (BadBytecode e) {
  256. throw new CannotCompileException(e);
  257. }
  258. cachedSuperclass = superclass;
  259. }
  260. /**
  261. * Replaces all occurrences of a class name in the class file.
  262. *
  263. * <p>
  264. * If class X is substituted for class Y in the class file, X and Y must
  265. * have the same signature. If Y provides a method m(), X must provide it
  266. * even if X inherits m() from the super class. If this fact is not
  267. * guaranteed, the bytecode verifier may cause an error.
  268. *
  269. * @param oldname
  270. * the replaced class name
  271. * @param newname
  272. * the substituted class name
  273. */
  274. public final void renameClass(String oldname, String newname) {
  275. ArrayList list;
  276. int n;
  277. if (oldname.equals(newname))
  278. return;
  279. if (oldname.equals(thisclassname))
  280. thisclassname = newname;
  281. oldname = Descriptor.toJvmName(oldname);
  282. newname = Descriptor.toJvmName(newname);
  283. constPool.renameClass(oldname, newname);
  284. list = methods;
  285. n = list.size();
  286. for (int i = 0; i < n; ++i) {
  287. MethodInfo minfo = (MethodInfo)list.get(i);
  288. String desc = minfo.getDescriptor();
  289. minfo.setDescriptor(Descriptor.rename(desc, oldname, newname));
  290. }
  291. list = fields;
  292. n = list.size();
  293. for (int i = 0; i < n; ++i) {
  294. FieldInfo finfo = (FieldInfo)list.get(i);
  295. String desc = finfo.getDescriptor();
  296. finfo.setDescriptor(Descriptor.rename(desc, oldname, newname));
  297. }
  298. }
  299. /**
  300. * Replaces all occurrences of several class names in the class file.
  301. *
  302. * @param classnames
  303. * specifies which class name is replaced with which new name.
  304. * Class names must be described with the JVM-internal
  305. * representation like <code>java/lang/Object</code>.
  306. * @see #renameClass(String,String)
  307. */
  308. public final void renameClass(Map classnames) {
  309. String jvmNewThisName = (String)classnames.get(Descriptor
  310. .toJvmName(thisclassname));
  311. if (jvmNewThisName != null)
  312. thisclassname = Descriptor.toJavaName(jvmNewThisName);
  313. constPool.renameClass(classnames);
  314. ArrayList list = methods;
  315. int n = list.size();
  316. for (int i = 0; i < n; ++i) {
  317. MethodInfo minfo = (MethodInfo)list.get(i);
  318. String desc = minfo.getDescriptor();
  319. minfo.setDescriptor(Descriptor.rename(desc, classnames));
  320. }
  321. list = fields;
  322. n = list.size();
  323. for (int i = 0; i < n; ++i) {
  324. FieldInfo finfo = (FieldInfo)list.get(i);
  325. String desc = finfo.getDescriptor();
  326. finfo.setDescriptor(Descriptor.rename(desc, classnames));
  327. }
  328. }
  329. /**
  330. * Returns the names of the interfaces implemented by the class.
  331. * The returned array is read only.
  332. */
  333. public String[] getInterfaces() {
  334. if (cachedInterfaces != null)
  335. return cachedInterfaces;
  336. String[] rtn = null;
  337. if (interfaces == null)
  338. rtn = new String[0];
  339. else {
  340. int n = interfaces.length;
  341. String[] list = new String[n];
  342. for (int i = 0; i < n; ++i)
  343. list[i] = constPool.getClassInfo(interfaces[i]);
  344. rtn = list;
  345. }
  346. cachedInterfaces = rtn;
  347. return rtn;
  348. }
  349. /**
  350. * Sets the interfaces.
  351. *
  352. * @param nameList
  353. * the names of the interfaces.
  354. */
  355. public void setInterfaces(String[] nameList) {
  356. cachedInterfaces = null;
  357. if (nameList != null) {
  358. int n = nameList.length;
  359. interfaces = new int[n];
  360. for (int i = 0; i < n; ++i)
  361. interfaces[i] = constPool.addClassInfo(nameList[i]);
  362. }
  363. }
  364. /**
  365. * Appends an interface to the interfaces implemented by the class.
  366. */
  367. public void addInterface(String name) {
  368. cachedInterfaces = null;
  369. int info = constPool.addClassInfo(name);
  370. if (interfaces == null) {
  371. interfaces = new int[1];
  372. interfaces[0] = info;
  373. }
  374. else {
  375. int n = interfaces.length;
  376. int[] newarray = new int[n + 1];
  377. System.arraycopy(interfaces, 0, newarray, 0, n);
  378. newarray[n] = info;
  379. interfaces = newarray;
  380. }
  381. }
  382. /**
  383. * Returns all the fields declared in the class.
  384. *
  385. * @return a list of <code>FieldInfo</code>.
  386. * @see FieldInfo
  387. */
  388. public List getFields() {
  389. return fields;
  390. }
  391. /**
  392. * Appends a field to the class.
  393. */
  394. public void addField(FieldInfo finfo) throws CannotCompileException {
  395. testExistingField(finfo.getName(), finfo.getDescriptor());
  396. fields.add(finfo);
  397. }
  398. private void addField0(FieldInfo finfo) {
  399. fields.add(finfo);
  400. }
  401. private void testExistingField(String name, String descriptor)
  402. throws CannotCompileException {
  403. ListIterator it = fields.listIterator(0);
  404. while (it.hasNext()) {
  405. FieldInfo minfo = (FieldInfo)it.next();
  406. if (minfo.getName().equals(name))
  407. throw new CannotCompileException("duplicate field: " + name);
  408. }
  409. }
  410. /**
  411. * Returns all the methods declared in the class.
  412. *
  413. * @return a list of <code>MethodInfo</code>.
  414. * @see MethodInfo
  415. */
  416. public List getMethods() {
  417. return methods;
  418. }
  419. /**
  420. * Returns the method with the specified name. If there are multiple methods
  421. * with that name, this method returns one of them.
  422. *
  423. * @return null if no such a method is found.
  424. */
  425. public MethodInfo getMethod(String name) {
  426. ArrayList list = methods;
  427. int n = list.size();
  428. for (int i = 0; i < n; ++i) {
  429. MethodInfo minfo = (MethodInfo)list.get(i);
  430. if (minfo.getName().equals(name))
  431. return minfo;
  432. }
  433. return null;
  434. }
  435. /**
  436. * Returns a static initializer (class initializer), or null if it does not
  437. * exist.
  438. */
  439. public MethodInfo getStaticInitializer() {
  440. return getMethod(MethodInfo.nameClinit);
  441. }
  442. /**
  443. * Appends a method to the class.
  444. */
  445. public void addMethod(MethodInfo minfo) throws CannotCompileException {
  446. testExistingMethod(minfo.getName(), minfo.getDescriptor());
  447. methods.add(minfo);
  448. }
  449. private void addMethod0(MethodInfo minfo) {
  450. methods.add(minfo);
  451. }
  452. private void testExistingMethod(String name, String descriptor)
  453. throws CannotCompileException {
  454. ListIterator it = methods.listIterator(0);
  455. while (it.hasNext()) {
  456. MethodInfo minfo = (MethodInfo)it.next();
  457. if (minfo.getName().equals(name)
  458. && Descriptor.eqParamTypes(minfo.getDescriptor(),
  459. descriptor))
  460. throw new CannotCompileException("duplicate method: " + name);
  461. }
  462. }
  463. /**
  464. * Returns all the attributes. The returned <code>List</code> object
  465. * is shared with this object. If you add a new attribute to the list,
  466. * the attribute is also added to the classs file represented by this
  467. * object. If you remove an attribute from the list, it is also removed
  468. * from the class file.
  469. *
  470. * @return a list of <code>AttributeInfo</code> objects.
  471. * @see AttributeInfo
  472. */
  473. public List getAttributes() {
  474. return attributes;
  475. }
  476. /**
  477. * Returns the attribute with the specified name. If there are multiple
  478. * attributes with that name, this method returns either of them. It
  479. * returns null if the specified attributed is not found.
  480. *
  481. * @param name attribute name
  482. * @see #getAttributes()
  483. */
  484. public AttributeInfo getAttribute(String name) {
  485. LinkedList list = attributes;
  486. int n = list.size();
  487. for (int i = 0; i < n; ++i) {
  488. AttributeInfo ai = (AttributeInfo)list.get(i);
  489. if (ai.getName().equals(name))
  490. return ai;
  491. }
  492. return null;
  493. }
  494. /**
  495. * Appends an attribute. If there is already an attribute with the same
  496. * name, the new one substitutes for it.
  497. *
  498. * @see #getAttributes()
  499. */
  500. public void addAttribute(AttributeInfo info) {
  501. AttributeInfo.remove(attributes, info.getName());
  502. attributes.add(info);
  503. }
  504. /**
  505. * Returns the source file containing this class.
  506. *
  507. * @return null if this information is not available.
  508. */
  509. public String getSourceFile() {
  510. SourceFileAttribute sf
  511. = (SourceFileAttribute)getAttribute(SourceFileAttribute.tag);
  512. if (sf == null)
  513. return null;
  514. else
  515. return sf.getFileName();
  516. }
  517. private void read(DataInputStream in) throws IOException {
  518. int i, n;
  519. int magic = in.readInt();
  520. if (magic != 0xCAFEBABE)
  521. throw new IOException("non class file");
  522. minor = in.readUnsignedShort();
  523. major = in.readUnsignedShort();
  524. constPool = new ConstPool(in);
  525. accessFlags = in.readUnsignedShort();
  526. thisClass = in.readUnsignedShort();
  527. constPool.setThisClassInfo(thisClass);
  528. superClass = in.readUnsignedShort();
  529. n = in.readUnsignedShort();
  530. if (n == 0)
  531. interfaces = null;
  532. else {
  533. interfaces = new int[n];
  534. for (i = 0; i < n; ++i)
  535. interfaces[i] = in.readUnsignedShort();
  536. }
  537. ConstPool cp = constPool;
  538. n = in.readUnsignedShort();
  539. fields = new ArrayList();
  540. for (i = 0; i < n; ++i)
  541. addField0(new FieldInfo(cp, in));
  542. n = in.readUnsignedShort();
  543. methods = new ArrayList();
  544. for (i = 0; i < n; ++i)
  545. addMethod0(new MethodInfo(cp, in));
  546. attributes = new LinkedList();
  547. n = in.readUnsignedShort();
  548. for (i = 0; i < n; ++i)
  549. addAttribute(AttributeInfo.read(cp, in));
  550. thisclassname = constPool.getClassInfo(thisClass);
  551. }
  552. /**
  553. * Writes a class file represened by this object into an output stream.
  554. */
  555. public void write(DataOutputStream out) throws IOException {
  556. int i, n;
  557. out.writeInt(0xCAFEBABE); // magic
  558. out.writeShort(minor); // minor version
  559. out.writeShort(major); // major version
  560. constPool.write(out); // constant pool
  561. out.writeShort(accessFlags);
  562. out.writeShort(thisClass);
  563. out.writeShort(superClass);
  564. if (interfaces == null)
  565. n = 0;
  566. else
  567. n = interfaces.length;
  568. out.writeShort(n);
  569. for (i = 0; i < n; ++i)
  570. out.writeShort(interfaces[i]);
  571. ArrayList list = fields;
  572. n = list.size();
  573. out.writeShort(n);
  574. for (i = 0; i < n; ++i) {
  575. FieldInfo finfo = (FieldInfo)list.get(i);
  576. finfo.write(out);
  577. }
  578. list = methods;
  579. n = list.size();
  580. out.writeShort(n);
  581. for (i = 0; i < n; ++i) {
  582. MethodInfo minfo = (MethodInfo)list.get(i);
  583. minfo.write(out);
  584. }
  585. out.writeShort(attributes.size());
  586. AttributeInfo.writeAll(attributes, out);
  587. }
  588. /**
  589. * Get the Major version.
  590. *
  591. * @return the major version
  592. */
  593. public int getMajorVersion() {
  594. return major;
  595. }
  596. /**
  597. * Set the major version.
  598. *
  599. * @param major
  600. * the major version
  601. */
  602. public void setMajorVersion(int major) {
  603. this.major = major;
  604. }
  605. /**
  606. * Get the minor version.
  607. *
  608. * @return the minor version
  609. */
  610. public int getMinorVersion() {
  611. return minor;
  612. }
  613. /**
  614. * Set the minor version.
  615. *
  616. * @param minor
  617. * the minor version
  618. */
  619. public void setMinorVersion(int minor) {
  620. this.minor = minor;
  621. }
  622. /**
  623. * Sets the major and minor version to Java 5.
  624. *
  625. * If the major version is older than 49, Java 5
  626. * extensions such as annotations are ignored
  627. * by the JVM.
  628. */
  629. public void setVersionToJava5() {
  630. this.major = 49;
  631. this.minor = 0;
  632. }
  633. }