View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   *  Unless required by applicable law or agreed to in writing, software
12   *  distributed under the License is distributed on an "AS IS" BASIS,
13   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   *  See the License for the specific language governing permissions and
15   *  limitations under the License.
16   *
17   */
18  package org.apache.bcel.classfile;
19  
20  import java.io.DataInputStream;
21  import java.io.DataOutputStream;
22  import java.io.IOException;
23  import org.apache.bcel.Constants;
24  
25  /** 
26   * This class represents a chunk of Java byte code contained in a
27   * method. It is instantiated by the
28   * <em>Attribute.readAttribute()</em> method. A <em>Code</em>
29   * attribute contains informations about operand stack, local
30   * variables, byte code and the exceptions handled within this
31   * method.
32   *
33   * This attribute has attributes itself, namely <em>LineNumberTable</em> which
34   * is used for debugging purposes and <em>LocalVariableTable</em> which 
35   * contains information about the local variables.
36   *
37   * @version $Id: Code.java 1152077 2011-07-29 02:29:42Z dbrosius $
38   * @author  <A HREF="mailto:m.dahm@gmx.de">M. Dahm</A>
39   * @see     Attribute
40   * @see     CodeException
41   * @see     LineNumberTable
42   * @see LocalVariableTable
43   */
44  public final class Code extends Attribute {
45  
46      private static final long serialVersionUID = -432884354459701506L;
47      private int max_stack; // Maximum size of stack used by this method
48      private int max_locals; // Number of local variables
49      private int code_length; // Length of code in bytes
50      private byte[] code; // Actual byte code
51      private int exception_table_length;
52      private CodeException[] exception_table; // Table of handled exceptions
53      private int attributes_count; // Attributes of code: LineNumber
54      private Attribute[] attributes; // or LocalVariable
55  
56  
57      /**
58       * Initialize from another object. Note that both objects use the same
59       * references (shallow copy). Use copy() for a physical copy.
60       */
61      public Code(Code c) {
62          this(c.getNameIndex(), c.getLength(), c.getMaxStack(), c.getMaxLocals(), c.getCode(), c
63                  .getExceptionTable(), c.getAttributes(), c.getConstantPool());
64      }
65  
66  
67      /**
68       * @param name_index Index pointing to the name <em>Code</em>
69       * @param length Content length in bytes
70       * @param file Input stream
71       * @param constant_pool Array of constants
72       */
73      Code(int name_index, int length, DataInputStream file, ConstantPool constant_pool)
74              throws IOException {
75          // Initialize with some default values which will be overwritten later
76          this(name_index, length, file.readUnsignedShort(), file.readUnsignedShort(), (byte[]) null,
77                  (CodeException[]) null, (Attribute[]) null, constant_pool);
78          code_length = file.readInt();
79          code = new byte[code_length]; // Read byte code
80          file.readFully(code);
81          /* Read exception table that contains all regions where an exception
82           * handler is active, i.e., a try { ... } catch() block.
83           */
84          exception_table_length = file.readUnsignedShort();
85          exception_table = new CodeException[exception_table_length];
86          for (int i = 0; i < exception_table_length; i++) {
87              exception_table[i] = new CodeException(file);
88          }
89          /* Read all attributes, currently `LineNumberTable' and
90           * `LocalVariableTable'
91           */
92          attributes_count = file.readUnsignedShort();
93          attributes = new Attribute[attributes_count];
94          for (int i = 0; i < attributes_count; i++) {
95              attributes[i] = Attribute.readAttribute(file, constant_pool);
96          }
97          /* Adjust length, because of setAttributes in this(), s.b.  length
98           * is incorrect, because it didn't take the internal attributes
99           * into account yet! Very subtle bug, fixed in 3.1.1.
100          */
101         this.length = length;
102     }
103 
104 
105     /**
106      * @param name_index Index pointing to the name <em>Code</em>
107      * @param length Content length in bytes
108      * @param max_stack Maximum size of stack
109      * @param max_locals Number of local variables
110      * @param code Actual byte code
111      * @param exception_table Table of handled exceptions
112      * @param attributes Attributes of code: LineNumber or LocalVariable
113      * @param constant_pool Array of constants
114      */
115     public Code(int name_index, int length, int max_stack, int max_locals, byte[] code,
116             CodeException[] exception_table, Attribute[] attributes, ConstantPool constant_pool) {
117         super(Constants.ATTR_CODE, name_index, length, constant_pool);
118         this.max_stack = max_stack;
119         this.max_locals = max_locals;
120         setCode(code);
121         setExceptionTable(exception_table);
122         setAttributes(attributes); // Overwrites length!
123     }
124 
125 
126     /**
127      * Called by objects that are traversing the nodes of the tree implicitely
128      * defined by the contents of a Java class. I.e., the hierarchy of methods,
129      * fields, attributes, etc. spawns a tree of objects.
130      *
131      * @param v Visitor object
132      */
133     @Override
134     public void accept( Visitor v ) {
135         v.visitCode(this);
136     }
137 
138 
139     /**
140      * Dump code attribute to file stream in binary format.
141      *
142      * @param file Output file stream
143      * @throws IOException
144      */
145     @Override
146     public final void dump( DataOutputStream file ) throws IOException {
147         super.dump(file);
148         file.writeShort(max_stack);
149         file.writeShort(max_locals);
150         file.writeInt(code_length);
151         file.write(code, 0, code_length);
152         file.writeShort(exception_table_length);
153         for (int i = 0; i < exception_table_length; i++) {
154             exception_table[i].dump(file);
155         }
156         file.writeShort(attributes_count);
157         for (int i = 0; i < attributes_count; i++) {
158             attributes[i].dump(file);
159         }
160     }
161 
162 
163     /**
164      * @return Collection of code attributes.
165      * @see Attribute
166      */
167     public final Attribute[] getAttributes() {
168         return attributes;
169     }
170 
171 
172     /**
173      * @return LineNumberTable of Code, if it has one
174      */
175     public LineNumberTable getLineNumberTable() {
176         for (int i = 0; i < attributes_count; i++) {
177             if (attributes[i] instanceof LineNumberTable) {
178                 return (LineNumberTable) attributes[i];
179             }
180         }
181         return null;
182     }
183 
184 
185     /**
186      * @return LocalVariableTable of Code, if it has one
187      */
188     public LocalVariableTable getLocalVariableTable() {
189         for (int i = 0; i < attributes_count; i++) {
190             if (attributes[i] instanceof LocalVariableTable) {
191                 return (LocalVariableTable) attributes[i];
192             }
193         }
194         return null;
195     }
196 
197 
198     /**
199      * @return Actual byte code of the method.
200      */
201     public final byte[] getCode() {
202         return code;
203     }
204 
205 
206     /**
207      * @return Table of handled exceptions.
208      * @see CodeException
209      */
210     public final CodeException[] getExceptionTable() {
211         return exception_table;
212     }
213 
214 
215     /**
216      * @return Number of local variables.
217      */
218     public final int getMaxLocals() {
219         return max_locals;
220     }
221 
222 
223     /**
224      * @return Maximum size of stack used by this method.
225      */
226     public final int getMaxStack() {
227         return max_stack;
228     }
229 
230 
231     /**
232      * @return the internal length of this code attribute (minus the first 6 bytes) 
233      * and excluding all its attributes
234      */
235     private final int getInternalLength() {
236         return 2 /*max_stack*/+ 2 /*max_locals*/+ 4 /*code length*/
237                 + code_length /*byte-code*/
238                 + 2 /*exception-table length*/
239                 + 8 * exception_table_length /* exception table */
240                 + 2 /* attributes count */;
241     }
242 
243 
244     /**
245      * @return the full size of this code attribute, minus its first 6 bytes,
246      * including the size of all its contained attributes
247      */
248     private final int calculateLength() {
249         int len = 0;
250         for (int i = 0; i < attributes_count; i++) {
251             len += attributes[i].length + 6 /*attribute header size*/;
252         }
253         return len + getInternalLength();
254     }
255 
256 
257     /**
258      * @param attributes the attributes to set for this Code
259      */
260     public final void setAttributes( Attribute[] attributes ) {
261         this.attributes = attributes;
262         attributes_count = (attributes == null) ? 0 : attributes.length;
263         length = calculateLength(); // Adjust length
264     }
265 
266 
267     /**
268      * @param code byte code
269      */
270     public final void setCode( byte[] code ) {
271         this.code = code;
272         code_length = (code == null) ? 0 : code.length;
273         length = calculateLength(); // Adjust length
274     }
275 
276 
277     /**
278      * @param exception_table exception table
279      */
280     public final void setExceptionTable( CodeException[] exception_table ) {
281         this.exception_table = exception_table;
282         exception_table_length = (exception_table == null) ? 0 : exception_table.length;
283         length = calculateLength(); // Adjust length
284     }
285 
286 
287     /**
288      * @param max_locals maximum number of local variables
289      */
290     public final void setMaxLocals( int max_locals ) {
291         this.max_locals = max_locals;
292     }
293 
294 
295     /**
296      * @param max_stack maximum stack size
297      */
298     public final void setMaxStack( int max_stack ) {
299         this.max_stack = max_stack;
300     }
301 
302 
303     /**
304      * @return String representation of code chunk.
305      */
306     public final String toString( boolean verbose ) {
307         StringBuilder buf = new StringBuilder(100);
308         buf.append("Code(max_stack = ").append(max_stack).append(", max_locals = ").append(
309                 max_locals).append(", code_length = ").append(code_length).append(")\n").append(
310                 Utility.codeToString(code, constant_pool, 0, -1, verbose));
311         if (exception_table_length > 0) {
312             buf.append("\nException handler(s) = \n").append("From\tTo\tHandler\tType\n");
313             for (int i = 0; i < exception_table_length; i++) {
314                 buf.append(exception_table[i].toString(constant_pool, verbose)).append("\n");
315             }
316         }
317         if (attributes_count > 0) {
318             buf.append("\nAttribute(s) = \n");
319             for (int i = 0; i < attributes_count; i++) {
320                 buf.append(attributes[i].toString()).append("\n");
321             }
322         }
323         return buf.toString();
324     }
325 
326 
327     /**
328      * @return String representation of code chunk.
329      */
330     @Override
331     public final String toString() {
332         return toString(true);
333     }
334 
335 
336     /**
337      * @return deep copy of this attribute
338      * 
339      * @param _constant_pool the constant pool to duplicate
340      */
341     @Override
342     public Attribute copy( ConstantPool _constant_pool ) {
343         Code c = (Code) clone();
344         if (code != null) {
345             c.code = new byte[code.length];
346             System.arraycopy(code, 0, c.code, 0, code.length);
347         }
348         c.constant_pool = _constant_pool;
349         c.exception_table = new CodeException[exception_table_length];
350         for (int i = 0; i < exception_table_length; i++) {
351             c.exception_table[i] = exception_table[i].copy();
352         }
353         c.attributes = new Attribute[attributes_count];
354         for (int i = 0; i < attributes_count; i++) {
355             c.attributes[i] = attributes[i].copy(_constant_pool);
356         }
357         return c;
358     }
359 }