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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  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 access and property flags of this nested class.
  210. * This method returns -1 if the class is not a nested class.
  211. *
  212. * <p>The returned value is obtained from <code>inner_class_access_flags</code>
  213. * of the entry representing this nested class itself
  214. * in <code>InnerClasses_attribute</code>>.
  215. */
  216. public int getInnerAccessFlags() {
  217. InnerClassesAttribute ica
  218. = (InnerClassesAttribute)getAttribute(InnerClassesAttribute.tag);
  219. if (ica == null)
  220. return -1;
  221. String name = getName();
  222. int n = ica.tableLength();
  223. for (int i = 0; i < n; ++i)
  224. if (name.equals(ica.innerClass(i)))
  225. return ica.accessFlags(i);
  226. return -1;
  227. }
  228. /**
  229. * Returns the class name.
  230. */
  231. public String getName() {
  232. return thisclassname;
  233. }
  234. /**
  235. * Sets the class name. This method substitutes the new name for all
  236. * occurrences of the old class name in the class file.
  237. */
  238. public void setName(String name) {
  239. renameClass(thisclassname, name);
  240. }
  241. /**
  242. * Returns the super class name.
  243. */
  244. public String getSuperclass() {
  245. if (cachedSuperclass == null)
  246. cachedSuperclass = constPool.getClassInfo(superClass);
  247. return cachedSuperclass;
  248. }
  249. /**
  250. * Returns the index of the constant pool entry representing the super
  251. * class.
  252. */
  253. public int getSuperclassId() {
  254. return superClass;
  255. }
  256. /**
  257. * Sets the super class.
  258. *
  259. * <p>
  260. * This method modifies constructors so that they call constructors declared
  261. * in the new super class.
  262. */
  263. public void setSuperclass(String superclass) throws CannotCompileException {
  264. if (superclass == null)
  265. superclass = "java.lang.Object";
  266. try {
  267. this.superClass = constPool.addClassInfo(superclass);
  268. ArrayList list = methods;
  269. int n = list.size();
  270. for (int i = 0; i < n; ++i) {
  271. MethodInfo minfo = (MethodInfo)list.get(i);
  272. minfo.setSuperclass(superclass);
  273. }
  274. }
  275. catch (BadBytecode e) {
  276. throw new CannotCompileException(e);
  277. }
  278. cachedSuperclass = superclass;
  279. }
  280. /**
  281. * Replaces all occurrences of a class name in the class file.
  282. *
  283. * <p>
  284. * If class X is substituted for class Y in the class file, X and Y must
  285. * have the same signature. If Y provides a method m(), X must provide it
  286. * even if X inherits m() from the super class. If this fact is not
  287. * guaranteed, the bytecode verifier may cause an error.
  288. *
  289. * @param oldname
  290. * the replaced class name
  291. * @param newname
  292. * the substituted class name
  293. */
  294. public final void renameClass(String oldname, String newname) {
  295. ArrayList list;
  296. int n;
  297. if (oldname.equals(newname))
  298. return;
  299. if (oldname.equals(thisclassname))
  300. thisclassname = newname;
  301. oldname = Descriptor.toJvmName(oldname);
  302. newname = Descriptor.toJvmName(newname);
  303. constPool.renameClass(oldname, newname);
  304. list = methods;
  305. n = list.size();
  306. for (int i = 0; i < n; ++i) {
  307. MethodInfo minfo = (MethodInfo)list.get(i);
  308. String desc = minfo.getDescriptor();
  309. minfo.setDescriptor(Descriptor.rename(desc, oldname, newname));
  310. }
  311. list = fields;
  312. n = list.size();
  313. for (int i = 0; i < n; ++i) {
  314. FieldInfo finfo = (FieldInfo)list.get(i);
  315. String desc = finfo.getDescriptor();
  316. finfo.setDescriptor(Descriptor.rename(desc, oldname, newname));
  317. }
  318. }
  319. /**
  320. * Replaces all occurrences of several class names in the class file.
  321. *
  322. * @param classnames
  323. * specifies which class name is replaced with which new name.
  324. * Class names must be described with the JVM-internal
  325. * representation like <code>java/lang/Object</code>.
  326. * @see #renameClass(String,String)
  327. */
  328. public final void renameClass(Map classnames) {
  329. String jvmNewThisName = (String)classnames.get(Descriptor
  330. .toJvmName(thisclassname));
  331. if (jvmNewThisName != null)
  332. thisclassname = Descriptor.toJavaName(jvmNewThisName);
  333. constPool.renameClass(classnames);
  334. ArrayList list = methods;
  335. int n = list.size();
  336. for (int i = 0; i < n; ++i) {
  337. MethodInfo minfo = (MethodInfo)list.get(i);
  338. String desc = minfo.getDescriptor();
  339. minfo.setDescriptor(Descriptor.rename(desc, classnames));
  340. }
  341. list = fields;
  342. n = list.size();
  343. for (int i = 0; i < n; ++i) {
  344. FieldInfo finfo = (FieldInfo)list.get(i);
  345. String desc = finfo.getDescriptor();
  346. finfo.setDescriptor(Descriptor.rename(desc, classnames));
  347. }
  348. }
  349. /**
  350. * Returns the names of the interfaces implemented by the class.
  351. * The returned array is read only.
  352. */
  353. public String[] getInterfaces() {
  354. if (cachedInterfaces != null)
  355. return cachedInterfaces;
  356. String[] rtn = null;
  357. if (interfaces == null)
  358. rtn = new String[0];
  359. else {
  360. int n = interfaces.length;
  361. String[] list = new String[n];
  362. for (int i = 0; i < n; ++i)
  363. list[i] = constPool.getClassInfo(interfaces[i]);
  364. rtn = list;
  365. }
  366. cachedInterfaces = rtn;
  367. return rtn;
  368. }
  369. /**
  370. * Sets the interfaces.
  371. *
  372. * @param nameList
  373. * the names of the interfaces.
  374. */
  375. public void setInterfaces(String[] nameList) {
  376. cachedInterfaces = null;
  377. if (nameList != null) {
  378. int n = nameList.length;
  379. interfaces = new int[n];
  380. for (int i = 0; i < n; ++i)
  381. interfaces[i] = constPool.addClassInfo(nameList[i]);
  382. }
  383. }
  384. /**
  385. * Appends an interface to the interfaces implemented by the class.
  386. */
  387. public void addInterface(String name) {
  388. cachedInterfaces = null;
  389. int info = constPool.addClassInfo(name);
  390. if (interfaces == null) {
  391. interfaces = new int[1];
  392. interfaces[0] = info;
  393. }
  394. else {
  395. int n = interfaces.length;
  396. int[] newarray = new int[n + 1];
  397. System.arraycopy(interfaces, 0, newarray, 0, n);
  398. newarray[n] = info;
  399. interfaces = newarray;
  400. }
  401. }
  402. /**
  403. * Returns all the fields declared in the class.
  404. *
  405. * @return a list of <code>FieldInfo</code>.
  406. * @see FieldInfo
  407. */
  408. public List getFields() {
  409. return fields;
  410. }
  411. /**
  412. * Appends a field to the class.
  413. */
  414. public void addField(FieldInfo finfo) throws CannotCompileException {
  415. testExistingField(finfo.getName(), finfo.getDescriptor());
  416. fields.add(finfo);
  417. }
  418. private void addField0(FieldInfo finfo) {
  419. fields.add(finfo);
  420. }
  421. private void testExistingField(String name, String descriptor)
  422. throws CannotCompileException {
  423. ListIterator it = fields.listIterator(0);
  424. while (it.hasNext()) {
  425. FieldInfo minfo = (FieldInfo)it.next();
  426. if (minfo.getName().equals(name))
  427. throw new CannotCompileException("duplicate field: " + name);
  428. }
  429. }
  430. /**
  431. * Returns all the methods declared in the class.
  432. *
  433. * @return a list of <code>MethodInfo</code>.
  434. * @see MethodInfo
  435. */
  436. public List getMethods() {
  437. return methods;
  438. }
  439. /**
  440. * Returns the method with the specified name. If there are multiple methods
  441. * with that name, this method returns one of them.
  442. *
  443. * @return null if no such a method is found.
  444. */
  445. public MethodInfo getMethod(String name) {
  446. ArrayList list = methods;
  447. int n = list.size();
  448. for (int i = 0; i < n; ++i) {
  449. MethodInfo minfo = (MethodInfo)list.get(i);
  450. if (minfo.getName().equals(name))
  451. return minfo;
  452. }
  453. return null;
  454. }
  455. /**
  456. * Returns a static initializer (class initializer), or null if it does not
  457. * exist.
  458. */
  459. public MethodInfo getStaticInitializer() {
  460. return getMethod(MethodInfo.nameClinit);
  461. }
  462. /**
  463. * Appends a method to the class.
  464. */
  465. public void addMethod(MethodInfo minfo) throws CannotCompileException {
  466. testExistingMethod(minfo.getName(), minfo.getDescriptor());
  467. methods.add(minfo);
  468. }
  469. private void addMethod0(MethodInfo minfo) {
  470. methods.add(minfo);
  471. }
  472. private void testExistingMethod(String name, String descriptor)
  473. throws CannotCompileException {
  474. ListIterator it = methods.listIterator(0);
  475. while (it.hasNext()) {
  476. MethodInfo minfo = (MethodInfo)it.next();
  477. if (minfo.getName().equals(name)
  478. && Descriptor.eqParamTypes(minfo.getDescriptor(),
  479. descriptor))
  480. throw new CannotCompileException("duplicate method: " + name);
  481. }
  482. }
  483. /**
  484. * Returns all the attributes. The returned <code>List</code> object
  485. * is shared with this object. If you add a new attribute to the list,
  486. * the attribute is also added to the classs file represented by this
  487. * object. If you remove an attribute from the list, it is also removed
  488. * from the class file.
  489. *
  490. * @return a list of <code>AttributeInfo</code> objects.
  491. * @see AttributeInfo
  492. */
  493. public List getAttributes() {
  494. return attributes;
  495. }
  496. /**
  497. * Returns the attribute with the specified name. If there are multiple
  498. * attributes with that name, this method returns either of them. It
  499. * returns null if the specified attributed is not found.
  500. *
  501. * @param name attribute name
  502. * @see #getAttributes()
  503. */
  504. public AttributeInfo getAttribute(String name) {
  505. LinkedList list = attributes;
  506. int n = list.size();
  507. for (int i = 0; i < n; ++i) {
  508. AttributeInfo ai = (AttributeInfo)list.get(i);
  509. if (ai.getName().equals(name))
  510. return ai;
  511. }
  512. return null;
  513. }
  514. /**
  515. * Appends an attribute. If there is already an attribute with the same
  516. * name, the new one substitutes for it.
  517. *
  518. * @see #getAttributes()
  519. */
  520. public void addAttribute(AttributeInfo info) {
  521. AttributeInfo.remove(attributes, info.getName());
  522. attributes.add(info);
  523. }
  524. /**
  525. * Returns the source file containing this class.
  526. *
  527. * @return null if this information is not available.
  528. */
  529. public String getSourceFile() {
  530. SourceFileAttribute sf
  531. = (SourceFileAttribute)getAttribute(SourceFileAttribute.tag);
  532. if (sf == null)
  533. return null;
  534. else
  535. return sf.getFileName();
  536. }
  537. private void read(DataInputStream in) throws IOException {
  538. int i, n;
  539. int magic = in.readInt();
  540. if (magic != 0xCAFEBABE)
  541. throw new IOException("non class file");
  542. minor = in.readUnsignedShort();
  543. major = in.readUnsignedShort();
  544. constPool = new ConstPool(in);
  545. accessFlags = in.readUnsignedShort();
  546. thisClass = in.readUnsignedShort();
  547. constPool.setThisClassInfo(thisClass);
  548. superClass = in.readUnsignedShort();
  549. n = in.readUnsignedShort();
  550. if (n == 0)
  551. interfaces = null;
  552. else {
  553. interfaces = new int[n];
  554. for (i = 0; i < n; ++i)
  555. interfaces[i] = in.readUnsignedShort();
  556. }
  557. ConstPool cp = constPool;
  558. n = in.readUnsignedShort();
  559. fields = new ArrayList();
  560. for (i = 0; i < n; ++i)
  561. addField0(new FieldInfo(cp, in));
  562. n = in.readUnsignedShort();
  563. methods = new ArrayList();
  564. for (i = 0; i < n; ++i)
  565. addMethod0(new MethodInfo(cp, in));
  566. attributes = new LinkedList();
  567. n = in.readUnsignedShort();
  568. for (i = 0; i < n; ++i)
  569. addAttribute(AttributeInfo.read(cp, in));
  570. thisclassname = constPool.getClassInfo(thisClass);
  571. }
  572. /**
  573. * Writes a class file represened by this object into an output stream.
  574. */
  575. public void write(DataOutputStream out) throws IOException {
  576. int i, n;
  577. out.writeInt(0xCAFEBABE); // magic
  578. out.writeShort(minor); // minor version
  579. out.writeShort(major); // major version
  580. constPool.write(out); // constant pool
  581. out.writeShort(accessFlags);
  582. out.writeShort(thisClass);
  583. out.writeShort(superClass);
  584. if (interfaces == null)
  585. n = 0;
  586. else
  587. n = interfaces.length;
  588. out.writeShort(n);
  589. for (i = 0; i < n; ++i)
  590. out.writeShort(interfaces[i]);
  591. ArrayList list = fields;
  592. n = list.size();
  593. out.writeShort(n);
  594. for (i = 0; i < n; ++i) {
  595. FieldInfo finfo = (FieldInfo)list.get(i);
  596. finfo.write(out);
  597. }
  598. list = methods;
  599. n = list.size();
  600. out.writeShort(n);
  601. for (i = 0; i < n; ++i) {
  602. MethodInfo minfo = (MethodInfo)list.get(i);
  603. minfo.write(out);
  604. }
  605. out.writeShort(attributes.size());
  606. AttributeInfo.writeAll(attributes, out);
  607. }
  608. /**
  609. * Get the Major version.
  610. *
  611. * @return the major version
  612. */
  613. public int getMajorVersion() {
  614. return major;
  615. }
  616. /**
  617. * Set the major version.
  618. *
  619. * @param major
  620. * the major version
  621. */
  622. public void setMajorVersion(int major) {
  623. this.major = major;
  624. }
  625. /**
  626. * Get the minor version.
  627. *
  628. * @return the minor version
  629. */
  630. public int getMinorVersion() {
  631. return minor;
  632. }
  633. /**
  634. * Set the minor version.
  635. *
  636. * @param minor
  637. * the minor version
  638. */
  639. public void setMinorVersion(int minor) {
  640. this.minor = minor;
  641. }
  642. /**
  643. * Sets the major and minor version to Java 5.
  644. *
  645. * If the major version is older than 49, Java 5
  646. * extensions such as annotations are ignored
  647. * by the JVM.
  648. */
  649. public void setVersionToJava5() {
  650. this.major = 49;
  651. this.minor = 0;
  652. }
  653. }