0001: /***
0002: * ASM: a very small and fast Java bytecode manipulation framework
0003: * Copyright (c) 2000-2005 INRIA, France Telecom
0004: * All rights reserved.
0005: *
0006: * Redistribution and use in source and binary forms, with or without
0007: * modification, are permitted provided that the following conditions
0008: * are met:
0009: * 1. Redistributions of source code must retain the above copyright
0010: * notice, this list of conditions and the following disclaimer.
0011: * 2. Redistributions in binary form must reproduce the above copyright
0012: * notice, this list of conditions and the following disclaimer in the
0013: * documentation and/or other materials provided with the distribution.
0014: * 3. Neither the name of the copyright holders nor the names of its
0015: * contributors may be used to endorse or promote products derived from
0016: * this software without specific prior written permission.
0017: *
0018: * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
0019: * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
0020: * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
0021: * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
0022: * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
0023: * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
0024: * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
0025: * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
0026: * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
0027: * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
0028: * THE POSSIBILITY OF SUCH DAMAGE.
0029: */package org.ejb3unit.asm;
0030:
0031: /**
0032: * A {@link ClassVisitor} that generates classes in bytecode form. More
0033: * precisely this visitor generates a byte array conforming to the Java class
0034: * file format. It can be used alone, to generate a Java class "from scratch",
0035: * or with one or more {@link ClassReader ClassReader} and adapter class visitor
0036: * to generate a modified class from one or more existing Java classes.
0037: *
0038: * @author Eric Bruneton
0039: */
0040: public class ClassWriter implements ClassVisitor {
0041:
0042: /**
0043: * Flag to automatically compute the maximum stack size and the maximum
0044: * number of local variables of methods. If this flag is set, then the
0045: * arguments of the {@link MethodVisitor#visitMaxs visitMaxs} method of the
0046: * {@link MethodVisitor} returned by the {@link #visitMethod visitMethod}
0047: * method will be ignored, and computed automatically from the signature and
0048: * the bytecode of each method.
0049: *
0050: * @see #ClassWriter(int)
0051: */
0052: public final static int COMPUTE_MAXS = 1;
0053:
0054: /**
0055: * Flag to automatically compute the stack map frames of methods from
0056: * scratch. If this flag is set, then the calls to the
0057: * {@link MethodVisitor#visitFrame} method are ignored, and the stack map
0058: * frames are recomputed from the methods bytecode. The arguments of the
0059: * {@link MethodVisitor#visitMaxs visitMaxs} method are also ignored and
0060: * recomputed from the bytecode. In other words, computeFrames implies
0061: * computeMaxs.
0062: *
0063: * @see #ClassWriter(int)
0064: */
0065: public final static int COMPUTE_FRAMES = 2;
0066:
0067: /**
0068: * The type of instructions without any argument.
0069: */
0070: final static int NOARG_INSN = 0;
0071:
0072: /**
0073: * The type of instructions with an signed byte argument.
0074: */
0075: final static int SBYTE_INSN = 1;
0076:
0077: /**
0078: * The type of instructions with an signed short argument.
0079: */
0080: final static int SHORT_INSN = 2;
0081:
0082: /**
0083: * The type of instructions with a local variable index argument.
0084: */
0085: final static int VAR_INSN = 3;
0086:
0087: /**
0088: * The type of instructions with an implicit local variable index argument.
0089: */
0090: final static int IMPLVAR_INSN = 4;
0091:
0092: /**
0093: * The type of instructions with a type descriptor argument.
0094: */
0095: final static int TYPE_INSN = 5;
0096:
0097: /**
0098: * The type of field and method invocations instructions.
0099: */
0100: final static int FIELDORMETH_INSN = 6;
0101:
0102: /**
0103: * The type of the INVOKEINTERFACE instruction.
0104: */
0105: final static int ITFMETH_INSN = 7;
0106:
0107: /**
0108: * The type of instructions with a 2 bytes bytecode offset label.
0109: */
0110: final static int LABEL_INSN = 8;
0111:
0112: /**
0113: * The type of instructions with a 4 bytes bytecode offset label.
0114: */
0115: final static int LABELW_INSN = 9;
0116:
0117: /**
0118: * The type of the LDC instruction.
0119: */
0120: final static int LDC_INSN = 10;
0121:
0122: /**
0123: * The type of the LDC_W and LDC2_W instructions.
0124: */
0125: final static int LDCW_INSN = 11;
0126:
0127: /**
0128: * The type of the IINC instruction.
0129: */
0130: final static int IINC_INSN = 12;
0131:
0132: /**
0133: * The type of the TABLESWITCH instruction.
0134: */
0135: final static int TABL_INSN = 13;
0136:
0137: /**
0138: * The type of the LOOKUPSWITCH instruction.
0139: */
0140: final static int LOOK_INSN = 14;
0141:
0142: /**
0143: * The type of the MULTIANEWARRAY instruction.
0144: */
0145: final static int MANA_INSN = 15;
0146:
0147: /**
0148: * The type of the WIDE instruction.
0149: */
0150: final static int WIDE_INSN = 16;
0151:
0152: /**
0153: * The instruction types of all JVM opcodes.
0154: */
0155: static byte[] TYPE;
0156:
0157: /**
0158: * The type of CONSTANT_Class constant pool items.
0159: */
0160: final static int CLASS = 7;
0161:
0162: /**
0163: * The type of CONSTANT_Fieldref constant pool items.
0164: */
0165: final static int FIELD = 9;
0166:
0167: /**
0168: * The type of CONSTANT_Methodref constant pool items.
0169: */
0170: final static int METH = 10;
0171:
0172: /**
0173: * The type of CONSTANT_InterfaceMethodref constant pool items.
0174: */
0175: final static int IMETH = 11;
0176:
0177: /**
0178: * The type of CONSTANT_String constant pool items.
0179: */
0180: final static int STR = 8;
0181:
0182: /**
0183: * The type of CONSTANT_Integer constant pool items.
0184: */
0185: final static int INT = 3;
0186:
0187: /**
0188: * The type of CONSTANT_Float constant pool items.
0189: */
0190: final static int FLOAT = 4;
0191:
0192: /**
0193: * The type of CONSTANT_Long constant pool items.
0194: */
0195: final static int LONG = 5;
0196:
0197: /**
0198: * The type of CONSTANT_Double constant pool items.
0199: */
0200: final static int DOUBLE = 6;
0201:
0202: /**
0203: * The type of CONSTANT_NameAndType constant pool items.
0204: */
0205: final static int NAME_TYPE = 12;
0206:
0207: /**
0208: * The type of CONSTANT_Utf8 constant pool items.
0209: */
0210: final static int UTF8 = 1;
0211:
0212: /**
0213: * Normal type Item stored in the ClassWriter {@link ClassWriter#typeTable},
0214: * instead of the constant pool, in order to avoid clashes with normal
0215: * constant pool items in the ClassWriter constant pool's hash table.
0216: */
0217: final static int TYPE_NORMAL = 13;
0218:
0219: /**
0220: * Uninitialized type Item stored in the ClassWriter
0221: * {@link ClassWriter#typeTable}, instead of the constant pool, in order to
0222: * avoid clashes with normal constant pool items in the ClassWriter constant
0223: * pool's hash table.
0224: */
0225: final static int TYPE_UNINIT = 14;
0226:
0227: /**
0228: * Merged type Item stored in the ClassWriter {@link ClassWriter#typeTable},
0229: * instead of the constant pool, in order to avoid clashes with normal
0230: * constant pool items in the ClassWriter constant pool's hash table.
0231: */
0232: final static int TYPE_MERGED = 15;
0233:
0234: /**
0235: * The class reader from which this class writer was constructed, if any.
0236: */
0237: ClassReader cr;
0238:
0239: /**
0240: * Minor and major version numbers of the class to be generated.
0241: */
0242: int version;
0243:
0244: /**
0245: * Index of the next item to be added in the constant pool.
0246: */
0247: int index;
0248:
0249: /**
0250: * The constant pool of this class.
0251: */
0252: ByteVector pool;
0253:
0254: /**
0255: * The constant pool's hash table data.
0256: */
0257: Item[] items;
0258:
0259: /**
0260: * The threshold of the constant pool's hash table.
0261: */
0262: int threshold;
0263:
0264: /**
0265: * A reusable key used to look for items in the {@link #items} hash table.
0266: */
0267: Item key;
0268:
0269: /**
0270: * A reusable key used to look for items in the {@link #items} hash table.
0271: */
0272: Item key2;
0273:
0274: /**
0275: * A reusable key used to look for items in the {@link #items} hash table.
0276: */
0277: Item key3;
0278:
0279: /**
0280: * A type table used to temporarily store internal names that will not
0281: * necessarily be stored in the constant pool. This type table is used by
0282: * the control flow and data flow analysis algorithm used to compute stack
0283: * map frames from scratch. This array associates to each index <tt>i</tt>
0284: * the Item whose index is <tt>i</tt>. All Item objects stored in this
0285: * array are also stored in the {@link #items} hash table. These two arrays
0286: * allow to retrieve an Item from its index or, conversly, to get the index
0287: * of an Item from its value. Each Item stores an internal name in its
0288: * {@link Item#strVal1} field.
0289: */
0290: Item[] typeTable;
0291:
0292: /**
0293: * Number of elements in the {@link #typeTable} array.
0294: */
0295: private short typeCount; // TODO int?
0296:
0297: /**
0298: * The access flags of this class.
0299: */
0300: private int access;
0301:
0302: /**
0303: * The constant pool item that contains the internal name of this class.
0304: */
0305: private int name;
0306:
0307: /**
0308: * The internal name of this class.
0309: */
0310: String this Name;
0311:
0312: /**
0313: * The constant pool item that contains the signature of this class.
0314: */
0315: private int signature;
0316:
0317: /**
0318: * The constant pool item that contains the internal name of the super class
0319: * of this class.
0320: */
0321: private int super Name;
0322:
0323: /**
0324: * Number of interfaces implemented or extended by this class or interface.
0325: */
0326: private int interfaceCount;
0327:
0328: /**
0329: * The interfaces implemented or extended by this class or interface. More
0330: * precisely, this array contains the indexes of the constant pool items
0331: * that contain the internal names of these interfaces.
0332: */
0333: private int[] interfaces;
0334:
0335: /**
0336: * The index of the constant pool item that contains the name of the source
0337: * file from which this class was compiled.
0338: */
0339: private int sourceFile;
0340:
0341: /**
0342: * The SourceDebug attribute of this class.
0343: */
0344: private ByteVector sourceDebug;
0345:
0346: /**
0347: * The constant pool item that contains the name of the enclosing class of
0348: * this class.
0349: */
0350: private int enclosingMethodOwner;
0351:
0352: /**
0353: * The constant pool item that contains the name and descriptor of the
0354: * enclosing method of this class.
0355: */
0356: private int enclosingMethod;
0357:
0358: /**
0359: * The runtime visible annotations of this class.
0360: */
0361: private AnnotationWriter anns;
0362:
0363: /**
0364: * The runtime invisible annotations of this class.
0365: */
0366: private AnnotationWriter ianns;
0367:
0368: /**
0369: * The non standard attributes of this class.
0370: */
0371: private Attribute attrs;
0372:
0373: /**
0374: * The number of entries in the InnerClasses attribute.
0375: */
0376: private int innerClassesCount;
0377:
0378: /**
0379: * The InnerClasses attribute.
0380: */
0381: private ByteVector innerClasses;
0382:
0383: /**
0384: * The fields of this class. These fields are stored in a linked list of
0385: * {@link FieldWriter} objects, linked to each other by their
0386: * {@link FieldWriter#next} field. This field stores the first element of
0387: * this list.
0388: */
0389: FieldWriter firstField;
0390:
0391: /**
0392: * The fields of this class. These fields are stored in a linked list of
0393: * {@link FieldWriter} objects, linked to each other by their
0394: * {@link FieldWriter#next} field. This field stores the last element of
0395: * this list.
0396: */
0397: FieldWriter lastField;
0398:
0399: /**
0400: * The methods of this class. These methods are stored in a linked list of
0401: * {@link MethodWriter} objects, linked to each other by their
0402: * {@link MethodWriter#next} field. This field stores the first element of
0403: * this list.
0404: */
0405: MethodWriter firstMethod;
0406:
0407: /**
0408: * The methods of this class. These methods are stored in a linked list of
0409: * {@link MethodWriter} objects, linked to each other by their
0410: * {@link MethodWriter#next} field. This field stores the last element of
0411: * this list.
0412: */
0413: MethodWriter lastMethod;
0414:
0415: /**
0416: * <tt>true</tt> if the maximum stack size and number of local variables
0417: * must be automatically computed.
0418: */
0419: private boolean computeMaxs;
0420:
0421: /**
0422: * <tt>true</tt> if the stack map frames must be recomputed from scratch.
0423: */
0424: private boolean computeFrames;
0425:
0426: /**
0427: * <tt>true</tt> if the stack map tables of this class are invalid. The
0428: * {@link MethodWriter#resizeInstructions} method cannot transform existing
0429: * stack map tables, and so produces potentially invalid classes when it is
0430: * executed. In this case the class is reread and rewritten with the
0431: * {@link #COMPUTE_FRAMES} option (the resizeInstructions method can resize
0432: * stack map tables when this option is used).
0433: */
0434: boolean invalidFrames;
0435:
0436: // ------------------------------------------------------------------------
0437: // Static initializer
0438: // ------------------------------------------------------------------------
0439:
0440: /**
0441: * Computes the instruction types of JVM opcodes.
0442: */
0443: static {
0444: int i;
0445: byte[] b = new byte[220];
0446: String s = "AAAAAAAAAAAAAAAABCKLLDDDDDEEEEEEEEEEEEEEEEEEEEAAAAAAAADD"
0447: + "DDDEEEEEEEEEEEEEEEEEEEEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
0448: + "AAAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAAAAAAIIIIIIIIIIIIIIIIDNOAA"
0449: + "AAAAGGGGGGGHAFBFAAFFAAQPIIJJIIIIIIIIIIIIIIIIII";
0450: for (i = 0; i < b.length; ++i) {
0451: b[i] = (byte) (s.charAt(i) - 'A');
0452: }
0453: TYPE = b;
0454:
0455: // code to generate the above string
0456: //
0457: // // SBYTE_INSN instructions
0458: // b[Constants.NEWARRAY] = SBYTE_INSN;
0459: // b[Constants.BIPUSH] = SBYTE_INSN;
0460: //
0461: // // SHORT_INSN instructions
0462: // b[Constants.SIPUSH] = SHORT_INSN;
0463: //
0464: // // (IMPL)VAR_INSN instructions
0465: // b[Constants.RET] = VAR_INSN;
0466: // for (i = Constants.ILOAD; i <= Constants.ALOAD; ++i) {
0467: // b[i] = VAR_INSN;
0468: // }
0469: // for (i = Constants.ISTORE; i <= Constants.ASTORE; ++i) {
0470: // b[i] = VAR_INSN;
0471: // }
0472: // for (i = 26; i <= 45; ++i) { // ILOAD_0 to ALOAD_3
0473: // b[i] = IMPLVAR_INSN;
0474: // }
0475: // for (i = 59; i <= 78; ++i) { // ISTORE_0 to ASTORE_3
0476: // b[i] = IMPLVAR_INSN;
0477: // }
0478: //
0479: // // TYPE_INSN instructions
0480: // b[Constants.NEW] = TYPE_INSN;
0481: // b[Constants.ANEWARRAY] = TYPE_INSN;
0482: // b[Constants.CHECKCAST] = TYPE_INSN;
0483: // b[Constants.INSTANCEOF] = TYPE_INSN;
0484: //
0485: // // (Set)FIELDORMETH_INSN instructions
0486: // for (i = Constants.GETSTATIC; i <= Constants.INVOKESTATIC; ++i) {
0487: // b[i] = FIELDORMETH_INSN;
0488: // }
0489: // b[Constants.INVOKEINTERFACE] = ITFMETH_INSN;
0490: //
0491: // // LABEL(W)_INSN instructions
0492: // for (i = Constants.IFEQ; i <= Constants.JSR; ++i) {
0493: // b[i] = LABEL_INSN;
0494: // }
0495: // b[Constants.IFNULL] = LABEL_INSN;
0496: // b[Constants.IFNONNULL] = LABEL_INSN;
0497: // b[200] = LABELW_INSN; // GOTO_W
0498: // b[201] = LABELW_INSN; // JSR_W
0499: // // temporary opcodes used internally by ASM - see Label and
0500: // MethodWriter
0501: // for (i = 202; i < 220; ++i) {
0502: // b[i] = LABEL_INSN;
0503: // }
0504: //
0505: // // LDC(_W) instructions
0506: // b[Constants.LDC] = LDC_INSN;
0507: // b[19] = LDCW_INSN; // LDC_W
0508: // b[20] = LDCW_INSN; // LDC2_W
0509: //
0510: // // special instructions
0511: // b[Constants.IINC] = IINC_INSN;
0512: // b[Constants.TABLESWITCH] = TABL_INSN;
0513: // b[Constants.LOOKUPSWITCH] = LOOK_INSN;
0514: // b[Constants.MULTIANEWARRAY] = MANA_INSN;
0515: // b[196] = WIDE_INSN; // WIDE
0516: //
0517: // for (i = 0; i < b.length; ++i) {
0518: // System.err.print((char)('A' + b[i]));
0519: // }
0520: // System.err.println();
0521: }
0522:
0523: // ------------------------------------------------------------------------
0524: // Constructor
0525: // ------------------------------------------------------------------------
0526:
0527: /**
0528: * Constructs a new {@link ClassWriter} object.
0529: *
0530: * @param flags option flags that can be used to modify the default behavior
0531: * of this class. See {@link #COMPUTE_MAXS}, {@link #COMPUTE_FRAMES}.
0532: */
0533: public ClassWriter(final int flags) {
0534: index = 1;
0535: pool = new ByteVector();
0536: items = new Item[256];
0537: threshold = (int) (0.75d * items.length);
0538: key = new Item();
0539: key2 = new Item();
0540: key3 = new Item();
0541: this .computeMaxs = (flags & COMPUTE_MAXS) != 0;
0542: this .computeFrames = (flags & COMPUTE_FRAMES) != 0;
0543: }
0544:
0545: /**
0546: * Constructs a new {@link ClassWriter} object and enables optimizations for
0547: * "mostly add" bytecode transformations. These optimizations are the
0548: * following:
0549: *
0550: * <ul> <li>The constant pool from the original class is copied as is in
0551: * the new class, which saves time. New constant pool entries will be added
0552: * at the end if necessary, but unused constant pool entries <i>won't be
0553: * removed</i>.</li> <li>Methods that are not transformed are copied as
0554: * is in the new class, directly from the original class bytecode (i.e.
0555: * without emitting visit events for all the method instructions), which
0556: * saves a <i>lot</i> of time. Untransformed methods are detected by the
0557: * fact that the {@link ClassReader} receives {@link MethodVisitor} objects
0558: * that come from a {@link ClassWriter} (and not from a custom
0559: * {@link ClassAdapter} or any other {@link ClassVisitor} instance).</li>
0560: * </ul>
0561: *
0562: * @param classReader the {@link ClassReader} used to read the original
0563: * class. It will be used to copy the entire constant pool from the
0564: * original class and also to copy other fragments of original
0565: * bytecode where applicable.
0566: * @param flags option flags that can be used to modify the default behavior
0567: * of this class. See {@link #COMPUTE_MAXS}, {@link #COMPUTE_FRAMES}.
0568: */
0569: public ClassWriter(final ClassReader classReader, final int flags) {
0570: this (flags);
0571: classReader.copyPool(this );
0572: this .cr = classReader;
0573: }
0574:
0575: // ------------------------------------------------------------------------
0576: // Implementation of the ClassVisitor interface
0577: // ------------------------------------------------------------------------
0578:
0579: public void visit(final int version, final int access,
0580: final String name, final String signature,
0581: final String super Name, final String[] interfaces) {
0582: this .version = version;
0583: this .access = access;
0584: this .name = newClass(name);
0585: this Name = name;
0586: if (signature != null) {
0587: this .signature = newUTF8(signature);
0588: }
0589: this .super Name = super Name == null ? 0 : newClass(super Name);
0590: if (interfaces != null && interfaces.length > 0) {
0591: interfaceCount = interfaces.length;
0592: this .interfaces = new int[interfaceCount];
0593: for (int i = 0; i < interfaceCount; ++i) {
0594: this .interfaces[i] = newClass(interfaces[i]);
0595: }
0596: }
0597: }
0598:
0599: public void visitSource(final String file, final String debug) {
0600: if (file != null) {
0601: sourceFile = newUTF8(file);
0602: }
0603: if (debug != null) {
0604: sourceDebug = new ByteVector().putUTF8(debug);
0605: }
0606: }
0607:
0608: public void visitOuterClass(final String owner, final String name,
0609: final String desc) {
0610: enclosingMethodOwner = newClass(owner);
0611: if (name != null && desc != null) {
0612: enclosingMethod = newNameType(name, desc);
0613: }
0614: }
0615:
0616: public AnnotationVisitor visitAnnotation(final String desc,
0617: final boolean visible) {
0618: ByteVector bv = new ByteVector();
0619: // write type, and reserve space for values count
0620: bv.putShort(newUTF8(desc)).putShort(0);
0621: AnnotationWriter aw = new AnnotationWriter(this , true, bv, bv,
0622: 2);
0623: if (visible) {
0624: aw.next = anns;
0625: anns = aw;
0626: } else {
0627: aw.next = ianns;
0628: ianns = aw;
0629: }
0630: return aw;
0631: }
0632:
0633: public void visitAttribute(final Attribute attr) {
0634: attr.next = attrs;
0635: attrs = attr;
0636: }
0637:
0638: public void visitInnerClass(final String name,
0639: final String outerName, final String innerName,
0640: final int access) {
0641: if (innerClasses == null) {
0642: innerClasses = new ByteVector();
0643: }
0644: ++innerClassesCount;
0645: innerClasses.putShort(name == null ? 0 : newClass(name));
0646: innerClasses.putShort(outerName == null ? 0
0647: : newClass(outerName));
0648: innerClasses.putShort(innerName == null ? 0
0649: : newUTF8(innerName));
0650: innerClasses.putShort(access);
0651: }
0652:
0653: public FieldVisitor visitField(final int access, final String name,
0654: final String desc, final String signature,
0655: final Object value) {
0656: return new FieldWriter(this , access, name, desc, signature,
0657: value);
0658: }
0659:
0660: public MethodVisitor visitMethod(final int access,
0661: final String name, final String desc,
0662: final String signature, final String[] exceptions) {
0663: return new MethodWriter(this , access, name, desc, signature,
0664: exceptions, computeMaxs, computeFrames);
0665: }
0666:
0667: public void visitEnd() {
0668: }
0669:
0670: // ------------------------------------------------------------------------
0671: // Other public methods
0672: // ------------------------------------------------------------------------
0673:
0674: /**
0675: * Returns the bytecode of the class that was build with this class writer.
0676: *
0677: * @return the bytecode of the class that was build with this class writer.
0678: */
0679: public byte[] toByteArray() {
0680: // computes the real size of the bytecode of this class
0681: int size = 24 + 2 * interfaceCount;
0682: int nbFields = 0;
0683: FieldWriter fb = firstField;
0684: while (fb != null) {
0685: ++nbFields;
0686: size += fb.getSize();
0687: fb = fb.next;
0688: }
0689: int nbMethods = 0;
0690: MethodWriter mb = firstMethod;
0691: while (mb != null) {
0692: ++nbMethods;
0693: size += mb.getSize();
0694: mb = mb.next;
0695: }
0696: int attributeCount = 0;
0697: if (signature != 0) {
0698: ++attributeCount;
0699: size += 8;
0700: newUTF8("Signature");
0701: }
0702: if (sourceFile != 0) {
0703: ++attributeCount;
0704: size += 8;
0705: newUTF8("SourceFile");
0706: }
0707: if (sourceDebug != null) {
0708: ++attributeCount;
0709: size += sourceDebug.length + 4;
0710: newUTF8("SourceDebugExtension");
0711: }
0712: if (enclosingMethodOwner != 0) {
0713: ++attributeCount;
0714: size += 10;
0715: newUTF8("EnclosingMethod");
0716: }
0717: if ((access & Opcodes.ACC_DEPRECATED) != 0) {
0718: ++attributeCount;
0719: size += 6;
0720: newUTF8("Deprecated");
0721: }
0722: if ((access & Opcodes.ACC_SYNTHETIC) != 0
0723: && (version & 0xffff) < Opcodes.V1_5) {
0724: ++attributeCount;
0725: size += 6;
0726: newUTF8("Synthetic");
0727: }
0728: if (innerClasses != null) {
0729: ++attributeCount;
0730: size += 8 + innerClasses.length;
0731: newUTF8("InnerClasses");
0732: }
0733: if (anns != null) {
0734: ++attributeCount;
0735: size += 8 + anns.getSize();
0736: newUTF8("RuntimeVisibleAnnotations");
0737: }
0738: if (ianns != null) {
0739: ++attributeCount;
0740: size += 8 + ianns.getSize();
0741: newUTF8("RuntimeInvisibleAnnotations");
0742: }
0743: if (attrs != null) {
0744: attributeCount += attrs.getCount();
0745: size += attrs.getSize(this , null, 0, -1, -1);
0746: }
0747: size += pool.length;
0748: // allocates a byte vector of this size, in order to avoid unnecessary
0749: // arraycopy operations in the ByteVector.enlarge() method
0750: ByteVector out = new ByteVector(size);
0751: out.putInt(0xCAFEBABE).putInt(version);
0752: out.putShort(index).putByteArray(pool.data, 0, pool.length);
0753: out.putShort(access).putShort(name).putShort(super Name);
0754: out.putShort(interfaceCount);
0755: for (int i = 0; i < interfaceCount; ++i) {
0756: out.putShort(interfaces[i]);
0757: }
0758: out.putShort(nbFields);
0759: fb = firstField;
0760: while (fb != null) {
0761: fb.put(out);
0762: fb = fb.next;
0763: }
0764: out.putShort(nbMethods);
0765: mb = firstMethod;
0766: while (mb != null) {
0767: mb.put(out);
0768: mb = mb.next;
0769: }
0770: out.putShort(attributeCount);
0771: if (signature != 0) {
0772: out.putShort(newUTF8("Signature")).putInt(2).putShort(
0773: signature);
0774: }
0775: if (sourceFile != 0) {
0776: out.putShort(newUTF8("SourceFile")).putInt(2).putShort(
0777: sourceFile);
0778: }
0779: if (sourceDebug != null) {
0780: int len = sourceDebug.length - 2;
0781: out.putShort(newUTF8("SourceDebugExtension")).putInt(len);
0782: out.putByteArray(sourceDebug.data, 2, len);
0783: }
0784: if (enclosingMethodOwner != 0) {
0785: out.putShort(newUTF8("EnclosingMethod")).putInt(4);
0786: out.putShort(enclosingMethodOwner)
0787: .putShort(enclosingMethod);
0788: }
0789: if ((access & Opcodes.ACC_DEPRECATED) != 0) {
0790: out.putShort(newUTF8("Deprecated")).putInt(0);
0791: }
0792: if ((access & Opcodes.ACC_SYNTHETIC) != 0
0793: && (version & 0xffff) < Opcodes.V1_5) {
0794: out.putShort(newUTF8("Synthetic")).putInt(0);
0795: }
0796: if (innerClasses != null) {
0797: out.putShort(newUTF8("InnerClasses"));
0798: out.putInt(innerClasses.length + 2).putShort(
0799: innerClassesCount);
0800: out.putByteArray(innerClasses.data, 0, innerClasses.length);
0801: }
0802: if (anns != null) {
0803: out.putShort(newUTF8("RuntimeVisibleAnnotations"));
0804: anns.put(out);
0805: }
0806: if (ianns != null) {
0807: out.putShort(newUTF8("RuntimeInvisibleAnnotations"));
0808: ianns.put(out);
0809: }
0810: if (attrs != null) {
0811: attrs.put(this , null, 0, -1, -1, out);
0812: }
0813: if (invalidFrames) {
0814: ClassWriter cw = new ClassWriter(COMPUTE_FRAMES);
0815: new ClassReader(out.data).accept(cw,
0816: ClassReader.SKIP_FRAMES);
0817: return cw.toByteArray();
0818: }
0819: return out.data;
0820: }
0821:
0822: // ------------------------------------------------------------------------
0823: // Utility methods: constant pool management
0824: // ------------------------------------------------------------------------
0825:
0826: /**
0827: * Adds a number or string constant to the constant pool of the class being
0828: * build. Does nothing if the constant pool already contains a similar item.
0829: *
0830: * @param cst the value of the constant to be added to the constant pool.
0831: * This parameter must be an {@link Integer}, a {@link Float}, a
0832: * {@link Long}, a {@link Double}, a {@link String} or a
0833: * {@link Type}.
0834: * @return a new or already existing constant item with the given value.
0835: */
0836: Item newConstItem(final Object cst) {
0837: if (cst instanceof Integer) {
0838: int val = ((Integer) cst).intValue();
0839: return newInteger(val);
0840: } else if (cst instanceof Byte) {
0841: int val = ((Byte) cst).intValue();
0842: return newInteger(val);
0843: } else if (cst instanceof Character) {
0844: int val = ((Character) cst).charValue();
0845: return newInteger(val);
0846: } else if (cst instanceof Short) {
0847: int val = ((Short) cst).intValue();
0848: return newInteger(val);
0849: } else if (cst instanceof Boolean) {
0850: int val = ((Boolean) cst).booleanValue() ? 1 : 0;
0851: return newInteger(val);
0852: } else if (cst instanceof Float) {
0853: float val = ((Float) cst).floatValue();
0854: return newFloat(val);
0855: } else if (cst instanceof Long) {
0856: long val = ((Long) cst).longValue();
0857: return newLong(val);
0858: } else if (cst instanceof Double) {
0859: double val = ((Double) cst).doubleValue();
0860: return newDouble(val);
0861: } else if (cst instanceof String) {
0862: return newString((String) cst);
0863: } else if (cst instanceof Type) {
0864: Type t = (Type) cst;
0865: return newClassItem(t.getSort() == Type.OBJECT ? t
0866: .getInternalName() : t.getDescriptor());
0867: } else {
0868: throw new IllegalArgumentException("value " + cst);
0869: }
0870: }
0871:
0872: /**
0873: * Adds a number or string constant to the constant pool of the class being
0874: * build. Does nothing if the constant pool already contains a similar item.
0875: * <i>This method is intended for {@link Attribute} sub classes, and is
0876: * normally not needed by class generators or adapters.</i>
0877: *
0878: * @param cst the value of the constant to be added to the constant pool.
0879: * This parameter must be an {@link Integer}, a {@link Float}, a
0880: * {@link Long}, a {@link Double} or a {@link String}.
0881: * @return the index of a new or already existing constant item with the
0882: * given value.
0883: */
0884: public int newConst(final Object cst) {
0885: return newConstItem(cst).index;
0886: }
0887:
0888: /**
0889: * Adds an UTF8 string to the constant pool of the class being build. Does
0890: * nothing if the constant pool already contains a similar item. <i>This
0891: * method is intended for {@link Attribute} sub classes, and is normally not
0892: * needed by class generators or adapters.</i>
0893: *
0894: * @param value the String value.
0895: * @return the index of a new or already existing UTF8 item.
0896: */
0897: public int newUTF8(final String value) {
0898: key.set(UTF8, value, null, null);
0899: Item result = get(key);
0900: if (result == null) {
0901: pool.putByte(UTF8).putUTF8(value);
0902: result = new Item(index++, key);
0903: put(result);
0904: }
0905: return result.index;
0906: }
0907:
0908: /**
0909: * Adds a class reference to the constant pool of the class being build.
0910: * Does nothing if the constant pool already contains a similar item.
0911: * <i>This method is intended for {@link Attribute} sub classes, and is
0912: * normally not needed by class generators or adapters.</i>
0913: *
0914: * @param value the internal name of the class.
0915: * @return a new or already existing class reference item.
0916: */
0917: Item newClassItem(final String value) {
0918: key2.set(CLASS, value, null, null);
0919: Item result = get(key2);
0920: if (result == null) {
0921: pool.put12(CLASS, newUTF8(value));
0922: result = new Item(index++, key2);
0923: put(result);
0924: }
0925: return result;
0926: }
0927:
0928: /**
0929: * Adds a class reference to the constant pool of the class being build.
0930: * Does nothing if the constant pool already contains a similar item.
0931: * <i>This method is intended for {@link Attribute} sub classes, and is
0932: * normally not needed by class generators or adapters.</i>
0933: *
0934: * @param value the internal name of the class.
0935: * @return the index of a new or already existing class reference item.
0936: */
0937: public int newClass(final String value) {
0938: return newClassItem(value).index;
0939: }
0940:
0941: /**
0942: * Adds a field reference to the constant pool of the class being build.
0943: * Does nothing if the constant pool already contains a similar item.
0944: *
0945: * @param owner the internal name of the field's owner class.
0946: * @param name the field's name.
0947: * @param desc the field's descriptor.
0948: * @return a new or already existing field reference item.
0949: */
0950: Item newFieldItem(final String owner, final String name,
0951: final String desc) {
0952: key3.set(FIELD, owner, name, desc);
0953: Item result = get(key3);
0954: if (result == null) {
0955: put122(FIELD, newClass(owner), newNameType(name, desc));
0956: result = new Item(index++, key3);
0957: put(result);
0958: }
0959: return result;
0960: }
0961:
0962: /**
0963: * Adds a field reference to the constant pool of the class being build.
0964: * Does nothing if the constant pool already contains a similar item.
0965: * <i>This method is intended for {@link Attribute} sub classes, and is
0966: * normally not needed by class generators or adapters.</i>
0967: *
0968: * @param owner the internal name of the field's owner class.
0969: * @param name the field's name.
0970: * @param desc the field's descriptor.
0971: * @return the index of a new or already existing field reference item.
0972: */
0973: public int newField(final String owner, final String name,
0974: final String desc) {
0975: return newFieldItem(owner, name, desc).index;
0976: }
0977:
0978: /**
0979: * Adds a method reference to the constant pool of the class being build.
0980: * Does nothing if the constant pool already contains a similar item.
0981: *
0982: * @param owner the internal name of the method's owner class.
0983: * @param name the method's name.
0984: * @param desc the method's descriptor.
0985: * @param itf <tt>true</tt> if <tt>owner</tt> is an interface.
0986: * @return a new or already existing method reference item.
0987: */
0988: Item newMethodItem(final String owner, final String name,
0989: final String desc, final boolean itf) {
0990: int type = itf ? IMETH : METH;
0991: key3.set(type, owner, name, desc);
0992: Item result = get(key3);
0993: if (result == null) {
0994: put122(type, newClass(owner), newNameType(name, desc));
0995: result = new Item(index++, key3);
0996: put(result);
0997: }
0998: return result;
0999: }
1000:
1001: /**
1002: * Adds a method reference to the constant pool of the class being build.
1003: * Does nothing if the constant pool already contains a similar item.
1004: * <i>This method is intended for {@link Attribute} sub classes, and is
1005: * normally not needed by class generators or adapters.</i>
1006: *
1007: * @param owner the internal name of the method's owner class.
1008: * @param name the method's name.
1009: * @param desc the method's descriptor.
1010: * @param itf <tt>true</tt> if <tt>owner</tt> is an interface.
1011: * @return the index of a new or already existing method reference item.
1012: */
1013: public int newMethod(final String owner, final String name,
1014: final String desc, final boolean itf) {
1015: return newMethodItem(owner, name, desc, itf).index;
1016: }
1017:
1018: /**
1019: * Adds an integer to the constant pool of the class being build. Does
1020: * nothing if the constant pool already contains a similar item.
1021: *
1022: * @param value the int value.
1023: * @return a new or already existing int item.
1024: */
1025: Item newInteger(final int value) {
1026: key.set(value);
1027: Item result = get(key);
1028: if (result == null) {
1029: pool.putByte(INT).putInt(value);
1030: result = new Item(index++, key);
1031: put(result);
1032: }
1033: return result;
1034: }
1035:
1036: /**
1037: * Adds a float to the constant pool of the class being build. Does nothing
1038: * if the constant pool already contains a similar item.
1039: *
1040: * @param value the float value.
1041: * @return a new or already existing float item.
1042: */
1043: Item newFloat(final float value) {
1044: key.set(value);
1045: Item result = get(key);
1046: if (result == null) {
1047: pool.putByte(FLOAT).putInt(key.intVal);
1048: result = new Item(index++, key);
1049: put(result);
1050: }
1051: return result;
1052: }
1053:
1054: /**
1055: * Adds a long to the constant pool of the class being build. Does nothing
1056: * if the constant pool already contains a similar item.
1057: *
1058: * @param value the long value.
1059: * @return a new or already existing long item.
1060: */
1061: Item newLong(final long value) {
1062: key.set(value);
1063: Item result = get(key);
1064: if (result == null) {
1065: pool.putByte(LONG).putLong(value);
1066: result = new Item(index, key);
1067: put(result);
1068: index += 2;
1069: }
1070: return result;
1071: }
1072:
1073: /**
1074: * Adds a double to the constant pool of the class being build. Does nothing
1075: * if the constant pool already contains a similar item.
1076: *
1077: * @param value the double value.
1078: * @return a new or already existing double item.
1079: */
1080: Item newDouble(final double value) {
1081: key.set(value);
1082: Item result = get(key);
1083: if (result == null) {
1084: pool.putByte(DOUBLE).putLong(key.longVal);
1085: result = new Item(index, key);
1086: put(result);
1087: index += 2;
1088: }
1089: return result;
1090: }
1091:
1092: /**
1093: * Adds a string to the constant pool of the class being build. Does nothing
1094: * if the constant pool already contains a similar item.
1095: *
1096: * @param value the String value.
1097: * @return a new or already existing string item.
1098: */
1099: private Item newString(final String value) {
1100: key2.set(STR, value, null, null);
1101: Item result = get(key2);
1102: if (result == null) {
1103: pool.put12(STR, newUTF8(value));
1104: result = new Item(index++, key2);
1105: put(result);
1106: }
1107: return result;
1108: }
1109:
1110: /**
1111: * Adds a name and type to the constant pool of the class being build. Does
1112: * nothing if the constant pool already contains a similar item. <i>This
1113: * method is intended for {@link Attribute} sub classes, and is normally not
1114: * needed by class generators or adapters.</i>
1115: *
1116: * @param name a name.
1117: * @param desc a type descriptor.
1118: * @return the index of a new or already existing name and type item.
1119: */
1120: public int newNameType(final String name, final String desc) {
1121: key2.set(NAME_TYPE, name, desc, null);
1122: Item result = get(key2);
1123: if (result == null) {
1124: put122(NAME_TYPE, newUTF8(name), newUTF8(desc));
1125: result = new Item(index++, key2);
1126: put(result);
1127: }
1128: return result.index;
1129: }
1130:
1131: /**
1132: * Adds the given internal name to {@link #typeTable} and returns its index.
1133: * Does nothing if the type table already contains this internal name.
1134: *
1135: * @param type the internal name to be added to the type table.
1136: * @return the index of this internal name in the type table.
1137: */
1138: int addType(final String type) {
1139: key.set(TYPE_NORMAL, type, null, null);
1140: Item result = get(key);
1141: if (result == null) {
1142: result = addType(key);
1143: }
1144: return result.index;
1145: }
1146:
1147: /**
1148: * Adds the given "uninitialized" type to {@link #typeTable} and returns its
1149: * index. This method is used for UNINITIALIZED types, made of an internal
1150: * name and a bytecode offset.
1151: *
1152: * @param type the internal name to be added to the type table.
1153: * @param offset the bytecode offset of the NEW instruction that created
1154: * this UNINITIALIZED type value.
1155: * @return the index of this internal name in the type table.
1156: */
1157: int addUninitializedType(final String type, final int offset) {
1158: key.type = TYPE_UNINIT;
1159: key.intVal = offset;
1160: key.strVal1 = type;
1161: key.hashCode = 0x7FFFFFFF & (TYPE_UNINIT + type.hashCode() + offset);
1162: Item result = get(key);
1163: if (result == null) {
1164: result = addType(key);
1165: }
1166: return result.index;
1167: }
1168:
1169: /**
1170: * Adds the given Item to {@link #typeTable}.
1171: *
1172: * @param item the value to be added to the type table.
1173: * @return the added Item, which a new Item instance with the same value as
1174: * the given Item.
1175: */
1176: private Item addType(final Item item) {
1177: ++typeCount;
1178: Item result = new Item(typeCount, key);
1179: put(result);
1180: if (typeTable == null) {
1181: typeTable = new Item[16];
1182: }
1183: if (typeCount == typeTable.length) {
1184: Item[] newTable = new Item[2 * typeTable.length];
1185: System.arraycopy(typeTable, 0, newTable, 0,
1186: typeTable.length);
1187: typeTable = newTable;
1188: }
1189: typeTable[typeCount] = result;
1190: return result;
1191: }
1192:
1193: /**
1194: * Returns the index of the common super type of the two given types. This
1195: * method calls {@link #getCommonSuperClass} and caches the result in the
1196: * {@link #items} hash table to speedup future calls with the same
1197: * parameters.
1198: *
1199: * @param type1 index of an internal name in {@link #typeTable}.
1200: * @param type2 index of an internal name in {@link #typeTable}.
1201: * @return the index of the common super type of the two given types.
1202: */
1203: int getMergedType(final int type1, final int type2) {
1204: key2.type = TYPE_MERGED;
1205: key2.longVal = type1 | (((long) type2) << 32);
1206: key2.hashCode = 0x7FFFFFFF & (TYPE_MERGED + type1 + type2);
1207: Item result = get(key2);
1208: if (result == null) {
1209: String t = typeTable[type1].strVal1;
1210: String u = typeTable[type2].strVal1;
1211: key2.intVal = addType(getCommonSuperClass(t, u));
1212: result = new Item((short) 0, key2);
1213: put(result);
1214: }
1215: return result.intVal;
1216: }
1217:
1218: /**
1219: * Returns the common super type of the two given types. The default
1220: * implementation of this method <i>loads<i> the two given classes and uses
1221: * the java.lang.Class methods to find the common super class. It can be
1222: * overriden to compute this common super type in other ways, in particular
1223: * without actually loading any class, or to take into account the class
1224: * that is currently being generated by this ClassWriter, which can of
1225: * course not be loaded since it is under construction.
1226: *
1227: * @param type1 the internal name of a class.
1228: * @param type2 the internal name of another class.
1229: * @return the internal name of the common super class of the two given
1230: * classes.
1231: */
1232: protected String getCommonSuperClass(final String type1,
1233: final String type2) {
1234: Class c, d;
1235: try {
1236: c = Class.forName(type1.replace('/', '.'));
1237: d = Class.forName(type2.replace('/', '.'));
1238: } catch (ClassNotFoundException e) {
1239: throw new RuntimeException(e);
1240: }
1241: if (c.isAssignableFrom(d)) {
1242: return type1;
1243: }
1244: if (d.isAssignableFrom(c)) {
1245: return type2;
1246: }
1247: if (c.isInterface() || d.isInterface()) {
1248: return "java/lang/Object";
1249: } else {
1250: do {
1251: c = c.getSuperclass();
1252: } while (!c.isAssignableFrom(d));
1253: return c.getName().replace('.', '/');
1254: }
1255: }
1256:
1257: /**
1258: * Returns the constant pool's hash table item which is equal to the given
1259: * item.
1260: *
1261: * @param key a constant pool item.
1262: * @return the constant pool's hash table item which is equal to the given
1263: * item, or <tt>null</tt> if there is no such item.
1264: */
1265: private Item get(final Item key) {
1266: Item i = items[key.hashCode % items.length];
1267: while (i != null && !key.isEqualTo(i)) {
1268: i = i.next;
1269: }
1270: return i;
1271: }
1272:
1273: /**
1274: * Puts the given item in the constant pool's hash table. The hash table
1275: * <i>must</i> not already contains this item.
1276: *
1277: * @param i the item to be added to the constant pool's hash table.
1278: */
1279: private void put(final Item i) {
1280: if (index > threshold) {
1281: int ll = items.length;
1282: int nl = ll * 2 + 1;
1283: Item[] newItems = new Item[nl];
1284: for (int l = ll - 1; l >= 0; --l) {
1285: Item j = items[l];
1286: while (j != null) {
1287: int index = j.hashCode % newItems.length;
1288: Item k = j.next;
1289: j.next = newItems[index];
1290: newItems[index] = j;
1291: j = k;
1292: }
1293: }
1294: items = newItems;
1295: threshold = (int) (nl * 0.75);
1296: }
1297: int index = i.hashCode % items.length;
1298: i.next = items[index];
1299: items[index] = i;
1300: }
1301:
1302: /**
1303: * Puts one byte and two shorts into the constant pool.
1304: *
1305: * @param b a byte.
1306: * @param s1 a short.
1307: * @param s2 another short.
1308: */
1309: private void put122(final int b, final int s1, final int s2) {
1310: pool.put12(b, s1).putShort(s2);
1311: }
1312: }
|