KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > org > apache > bcel > internal > classfile > Utility


1 package com.sun.org.apache.bcel.internal.classfile;
2
3 /* ====================================================================
4  * The Apache Software License, Version 1.1
5  *
6  * Copyright (c) 2001 The Apache Software Foundation. All rights
7  * reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  * notice, this list of conditions and the following disclaimer.
15  *
16  * 2. Redistributions in binary form must reproduce the above copyright
17  * notice, this list of conditions and the following disclaimer in
18  * the documentation and/or other materials provided with the
19  * distribution.
20  *
21  * 3. The end-user documentation included with the redistribution,
22  * if any, must include the following acknowledgment:
23  * "This product includes software developed by the
24  * Apache Software Foundation (http://www.apache.org/)."
25  * Alternately, this acknowledgment may appear in the software itself,
26  * if and wherever such third-party acknowledgments normally appear.
27  *
28  * 4. The names "Apache" and "Apache Software Foundation" and
29  * "Apache BCEL" must not be used to endorse or promote products
30  * derived from this software without prior written permission. For
31  * written permission, please contact apache@apache.org.
32  *
33  * 5. Products derived from this software may not be called "Apache",
34  * "Apache BCEL", nor may "Apache" appear in their name, without
35  * prior written permission of the Apache Software Foundation.
36  *
37  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
38  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
39  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
40  * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
41  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
42  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
43  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
44  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
45  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
46  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
47  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
48  * SUCH DAMAGE.
49  * ====================================================================
50  *
51  * This software consists of voluntary contributions made by many
52  * individuals on behalf of the Apache Software Foundation. For more
53  * information on the Apache Software Foundation, please see
54  * <http://www.apache.org/>.
55  */

56
57 import com.sun.org.apache.bcel.internal.Constants;
58 import com.sun.org.apache.bcel.internal.util.ByteSequence;
59 import java.io.*;
60 import java.util.ArrayList JavaDoc;
61 import java.util.zip.*;
62
63 /**
64  * Utility functions that do not really belong to any class in particular.
65  *
66  * @version $Id: Utility.java,v 1.1.1.1 2001/10/29 20:00:05 jvanzyl Exp $
67  * @author <A HREF="mailto:markus.dahm@berlin.de">M. Dahm</A>
68  */

69 public abstract class Utility {
70   private static int consumed_chars; /* How many chars have been consumed
71                       * during parsing in signatureToString().
72                       * Read by methodSignatureToString().
73                       * Set by side effect,but only internally.
74                       */

75   private static boolean wide=false; /* The `WIDE' instruction is used in the
76                       * byte code to allow 16-bit wide indices
77                       * for local variables. This opcode
78                       * precedes an `ILOAD', e.g.. The opcode
79                       * immediately following takes an extra
80                       * byte which is combined with the
81                       * following byte to form a
82                       * 16-bit value.
83                       */

84   /**
85    * Convert bit field of flags into string such as `static final'.
86    *
87    * @param access_flags Access flags
88    * @return String representation of flags
89    */

90   public static final String JavaDoc accessToString(int access_flags) {
91     return accessToString(access_flags, false);
92   }
93
94   /**
95    * Convert bit field of flags into string such as `static final'.
96    *
97    * Special case: Classes compiled with new compilers and with the
98    * `ACC_SUPER' flag would be said to be "synchronized". This is
99    * because SUN used the same value for the flags `ACC_SUPER' and
100    * `ACC_SYNCHRONIZED'.
101    *
102    * @param access_flags Access flags
103    * @param for_class access flags are for class qualifiers ?
104    * @return String representation of flags
105    */

106   public static final String JavaDoc accessToString(int access_flags,
107                         boolean for_class)
108   {
109     StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
110
111     int p = 0;
112     for(int i=0; p < Constants.MAX_ACC_FLAG; i++) { // Loop through known flags
113
p = pow2(i);
114
115       if((access_flags & p) != 0) {
116     /* Special case: Classes compiled with new compilers and with the
117      * `ACC_SUPER' flag would be said to be "synchronized". This is
118      * because SUN used the same value for the flags `ACC_SUPER' and
119      * `ACC_SYNCHRONIZED'.
120      */

121     if(for_class && ((p == Constants.ACC_SUPER) || (p == Constants.ACC_INTERFACE)))
122       continue;
123
124     buf.append(Constants.ACCESS_NAMES[i] + " ");
125       }
126     }
127
128     return buf.toString().trim();
129   }
130
131   /**
132    * @return "class" or "interface", depending on the ACC_INTERFACE flag
133    */

134   public static final String JavaDoc classOrInterface(int access_flags) {
135     return ((access_flags & Constants.ACC_INTERFACE) != 0)? "interface" : "class";
136   }
137
138   /**
139    * Disassemble a byte array of JVM byte codes starting from code line
140    * `index' and return the disassembled string representation. Decode only
141    * `num' opcodes (including their operands), use -1 if you want to
142    * decompile everything.
143    *
144    * @param code byte code array
145    * @param constant_pool Array of constants
146    * @param index offset in `code' array
147    * <EM>(number of opcodes, not bytes!)</EM>
148    * @param length number of opcodes to decompile, -1 for all
149    * @param verbose be verbose, e.g. print constant pool index
150    * @return String representation of byte codes
151    */

152   public static final String JavaDoc codeToString(byte[] code,
153                       ConstantPool constant_pool,
154                       int index, int length, boolean verbose)
155   {
156     StringBuffer JavaDoc buf = new StringBuffer JavaDoc(code.length * 20); // Should be sufficient
157
ByteSequence stream = new ByteSequence(code);
158
159     try {
160       for(int i=0; i < index; i++) // Skip `index' lines of code
161
codeToString(stream, constant_pool, verbose);
162
163       for(int i=0; stream.available() > 0; i++) {
164     if((length < 0) || (i < length)) {
165       String JavaDoc indices = fillup(stream.getIndex() + ":", 6, true, ' ');
166       buf.append(indices + codeToString(stream, constant_pool, verbose) + '\n');
167     }
168       }
169     } catch(IOException e) {
170       System.out.println(buf.toString());
171       e.printStackTrace();
172       throw new ClassFormatError JavaDoc("Byte code error: " + e);
173     }
174
175     return buf.toString();
176   }
177
178   public static final String JavaDoc codeToString(byte[] code,
179                       ConstantPool constant_pool,
180                       int index, int length) {
181     return codeToString(code, constant_pool, index, length, true);
182   }
183
184   /**
185    * Disassemble a stream of byte codes and return the
186    * string representation.
187    *
188    * @param bytes stream of bytes
189    * @param constant_pool Array of constants
190    * @param verbose be verbose, e.g. print constant pool index
191    * @return String representation of byte code
192    */

193   public static final String JavaDoc codeToString(ByteSequence bytes,
194                       ConstantPool constant_pool, boolean verbose)
195        throws IOException
196   {
197     short opcode = (short)bytes.readUnsignedByte();
198     int default_offset=0, low, high, npairs;
199     int index, vindex, constant;
200     int[] match, jump_table;
201     int no_pad_bytes=0, offset;
202     StringBuffer JavaDoc buf = new StringBuffer JavaDoc(Constants.OPCODE_NAMES[opcode]);
203
204     /* Special case: Skip (0-3) padding bytes, i.e., the
205      * following bytes are 4-byte-aligned
206      */

207     if((opcode == Constants.TABLESWITCH) || (opcode == Constants.LOOKUPSWITCH)) {
208       int remainder = bytes.getIndex() % 4;
209       no_pad_bytes = (remainder == 0)? 0 : 4 - remainder;
210
211       for(int i=0; i < no_pad_bytes; i++) {
212     byte b;
213
214     if((b=bytes.readByte()) != 0)
215       System.err.println("Warning: Padding byte != 0 in " +
216                  Constants.OPCODE_NAMES[opcode] + ":" + b);
217       }
218
219       // Both cases have a field default_offset in common
220
default_offset = bytes.readInt();
221     }
222
223     switch(opcode) {
224       /* Table switch has variable length arguments.
225        */

226     case Constants.TABLESWITCH:
227       low = bytes.readInt();
228       high = bytes.readInt();
229
230       offset = bytes.getIndex() - 12 - no_pad_bytes - 1;
231       default_offset += offset;
232
233       buf.append("\tdefault = " + default_offset + ", low = " + low +
234          ", high = " + high + "(");
235
236       jump_table = new int[high - low + 1];
237       for(int i=0; i < jump_table.length; i++) {
238     jump_table[i] = offset + bytes.readInt();
239     buf.append(jump_table[i]);
240
241     if(i < jump_table.length - 1)
242       buf.append(", ");
243       }
244       buf.append(")");
245
246       break;
247
248       /* Lookup switch has variable length arguments.
249        */

250     case Constants.LOOKUPSWITCH: {
251
252       npairs = bytes.readInt();
253       offset = bytes.getIndex() - 8 - no_pad_bytes - 1;
254       
255       match = new int[npairs];
256       jump_table = new int[npairs];
257       default_offset += offset;
258
259       buf.append("\tdefault = " + default_offset + ", npairs = " + npairs +
260          " (");
261
262       for(int i=0; i < npairs; i++) {
263     match[i] = bytes.readInt();
264
265     jump_table[i] = offset + bytes.readInt();
266
267     buf.append("(" + match[i] + ", " + jump_table[i] + ")");
268
269     if(i < npairs - 1)
270       buf.append(", ");
271       }
272       buf.append(")");
273     }
274     break;
275
276     /* Two address bytes + offset from start of byte stream form the
277      * jump target
278      */

279     case Constants.GOTO: case Constants.IFEQ: case Constants.IFGE: case Constants.IFGT:
280     case Constants.IFLE: case Constants.IFLT: case Constants.JSR: case Constants.IFNE:
281     case Constants.IFNONNULL: case Constants.IFNULL: case Constants.IF_ACMPEQ:
282     case Constants.IF_ACMPNE: case Constants.IF_ICMPEQ: case Constants.IF_ICMPGE: case Constants.IF_ICMPGT:
283     case Constants.IF_ICMPLE: case Constants.IF_ICMPLT: case Constants.IF_ICMPNE:
284       buf.append("\t\t#" + ((bytes.getIndex() - 1) + bytes.readShort()));
285       break;
286       
287       /* 32-bit wide jumps
288        */

289     case Constants.GOTO_W: case Constants.JSR_W:
290       buf.append("\t\t#" + ((bytes.getIndex() - 1) + bytes.readInt()));
291       break;
292
293       /* Index byte references local variable (register)
294        */

295     case Constants.ALOAD: case Constants.ASTORE: case Constants.DLOAD: case Constants.DSTORE: case Constants.FLOAD:
296     case Constants.FSTORE: case Constants.ILOAD: case Constants.ISTORE: case Constants.LLOAD: case Constants.LSTORE:
297     case Constants.RET:
298       if(wide) {
299     vindex = bytes.readUnsignedShort();
300     wide=false; // Clear flag
301
}
302       else
303     vindex = bytes.readUnsignedByte();
304
305       buf.append("\t\t%" + vindex);
306       break;
307
308       /*
309        * Remember wide byte which is used to form a 16-bit address in the
310        * following instruction. Relies on that the method is called again with
311        * the following opcode.
312        */

313     case Constants.WIDE:
314       wide = true;
315       buf.append("\t(wide)");
316       break;
317
318       /* Array of basic type.
319        */

320     case Constants.NEWARRAY:
321       buf.append("\t\t<" + Constants.TYPE_NAMES[bytes.readByte()] + ">");
322       break;
323
324       /* Access object/class fields.
325        */

326     case Constants.GETFIELD: case Constants.GETSTATIC: case Constants.PUTFIELD: case Constants.PUTSTATIC:
327       index = bytes.readUnsignedShort();
328       buf.append("\t\t" +
329          constant_pool.constantToString(index, Constants.CONSTANT_Fieldref) +
330          (verbose? " (" + index + ")" : ""));
331       break;
332       
333       /* Operands are references to classes in constant pool
334        */

335     case Constants.NEW:
336     case Constants.CHECKCAST:
337       buf.append("\t");
338     case Constants.INSTANCEOF:
339       index = bytes.readUnsignedShort();
340       buf.append("\t<" + constant_pool.constantToString(index,
341                             Constants.CONSTANT_Class) +
342          ">" + (verbose? " (" + index + ")" : ""));
343       break;
344
345       /* Operands are references to methods in constant pool
346        */

347     case Constants.INVOKESPECIAL: case Constants.INVOKESTATIC: case Constants.INVOKEVIRTUAL:
348       index = bytes.readUnsignedShort();
349       buf.append("\t" + constant_pool.constantToString(index,
350                                Constants.CONSTANT_Methodref) +
351          (verbose? " (" + index + ")" : ""));
352       break;
353
354     case Constants.INVOKEINTERFACE:
355       index = bytes.readUnsignedShort();
356       int nargs = bytes.readUnsignedByte(); // historical, redundant
357
buf.append("\t" +
358          constant_pool.constantToString(index,
359                         Constants.CONSTANT_InterfaceMethodref) +
360          (verbose? " (" + index + ")\t" : "") + nargs + "\t" +
361          bytes.readUnsignedByte()); // Last byte is a reserved space
362
break;
363     
364       /* Operands are references to items in constant pool
365        */

366     case Constants.LDC_W: case Constants.LDC2_W:
367       index = bytes.readUnsignedShort();
368
369       buf.append("\t\t" + constant_pool.constantToString
370          (index, constant_pool.getConstant(index).getTag()) +
371          (verbose? " (" + index + ")" : ""));
372       break;
373
374     case Constants.LDC:
375       index = bytes.readUnsignedByte();
376
377       buf.append("\t\t" +
378          constant_pool.constantToString
379          (index, constant_pool.getConstant(index).getTag()) +
380          (verbose? " (" + index + ")" : ""));
381       break;
382     
383       /* Array of references.
384        */

385     case Constants.ANEWARRAY:
386       index = bytes.readUnsignedShort();
387       
388       buf.append("\t\t<" + compactClassName(constant_pool.getConstantString
389                       (index, Constants.CONSTANT_Class), false) +
390          ">" + (verbose? " (" + index + ")": ""));
391       break;
392     
393       /* Multidimensional array of references.
394        */

395     case Constants.MULTIANEWARRAY: {
396       index = bytes.readUnsignedShort();
397       int dimensions = bytes.readUnsignedByte();
398
399       buf.append("\t<" + compactClassName(constant_pool.getConstantString
400                       (index, Constants.CONSTANT_Class), false) +
401          ">\t" + dimensions + (verbose? " (" + index + ")" : ""));
402     }
403     break;
404
405     /* Increment local variable.
406      */

407     case Constants.IINC:
408       if(wide) {
409     vindex = bytes.readUnsignedShort();
410     constant = bytes.readShort();
411     wide = false;
412       }
413       else {
414     vindex = bytes.readUnsignedByte();
415     constant = bytes.readByte();
416       }
417       buf.append("\t\t%" + vindex + "\t" + constant);
418       break;
419
420     default:
421       if(Constants.NO_OF_OPERANDS[opcode] > 0) {
422     for(int i=0; i < Constants.TYPE_OF_OPERANDS[opcode].length; i++) {
423       buf.append("\t\t");
424       switch(Constants.TYPE_OF_OPERANDS[opcode][i]) {
425       case Constants.T_BYTE: buf.append(bytes.readByte()); break;
426       case Constants.T_SHORT: buf.append(bytes.readShort()); break;
427       case Constants.T_INT: buf.append(bytes.readInt()); break;
428                           
429       default: // Never reached
430
System.err.println("Unreachable default case reached!");
431         System.exit(-1);
432       }
433     }
434       }
435     }
436
437     return buf.toString();
438   }
439
440   public static final String JavaDoc codeToString(ByteSequence bytes, ConstantPool constant_pool)
441     throws IOException
442   {
443     return codeToString(bytes, constant_pool, true);
444   }
445
446   /**
447    * Shorten long class names, <em>java/lang/String</em> becomes
448    * <em>String</em>.
449    *
450    * @param str The long class name
451    * @return Compacted class name
452    */

453   public static final String JavaDoc compactClassName(String JavaDoc str) {
454     return compactClassName(str, true);
455   }
456  
457   /**
458    * Shorten long class name <em>str</em>, i.e., chop off the <em>prefix</em>,
459    * if the
460    * class name starts with this string and the flag <em>chopit</em> is true.
461    * Slashes <em>/</em> are converted to dots <em>.</em>.
462    *
463    * @param str The long class name
464    * @param prefix The prefix the get rid off
465    * @param chopit Flag that determines whether chopping is executed or not
466    * @return Compacted class name
467    */

468   public static final String JavaDoc compactClassName(String JavaDoc str,
469                           String JavaDoc prefix,
470                           boolean chopit)
471   {
472     int len = prefix.length();
473
474     str = str.replace('/', '.'); // Is `/' on all systems, even DOS
475

476     if(chopit) {
477       // If string starts with `prefix' and contains no further dots
478
if(str.startsWith(prefix) &&
479      (str.substring(len).indexOf('.') == -1))
480     str = str.substring(len);
481     }
482     
483     return str;
484   }
485
486   /**
487    * Shorten long class names, <em>java/lang/String</em> becomes
488    * <em>java.lang.String</em>,
489    * e.g.. If <em>chopit</em> is <em>true</em> the prefix <em>java.lang</em>
490    * is also removed.
491    *
492    * @param str The long class name
493    * @param chopit Flag that determines whether chopping is executed or not
494    * @return Compacted class name
495    */

496   public static final String JavaDoc compactClassName(String JavaDoc str, boolean chopit) {
497     return compactClassName(str, "java.lang.", chopit);
498   }
499
500   private static final boolean is_digit(char ch) {
501     return (ch >= '0') && (ch <= '9');
502   }
503   
504   private static final boolean is_space(char ch) {
505     return (ch == ' ') || (ch == '\t') || (ch == '\r') || (ch == '\n');
506   }
507
508   /**
509    * @return `flag' with bit `i' set to 1
510    */

511   public static final int setBit(int flag, int i) {
512     return flag | pow2(i);
513   }
514
515   /**
516    * @return `flag' with bit `i' set to 0
517    */

518   public static final int clearBit(int flag, int i) {
519     int bit = pow2(i);
520     return (flag & bit) == 0? flag : flag ^ bit;
521   }
522    
523   /**
524    * @return true, if bit `i' in `flag' is set
525    */

526   public static final boolean isSet(int flag, int i) {
527     return (flag & pow2(i)) != 0;
528   }
529
530   /**
531    * Converts string containing the method return and argument types
532    * to a byte code method signature.
533    *
534    * @param ret Return type of method
535    * @param argv Types of method arguments
536    * @return Byte code representation of method signature
537    */

538   public final static String JavaDoc methodTypeToSignature(String JavaDoc ret, String JavaDoc[] argv)
539     throws ClassFormatError JavaDoc
540   {
541     StringBuffer JavaDoc buf = new StringBuffer JavaDoc("(");
542     String JavaDoc str;
543
544     if(argv != null)
545       for(int i=0; i < argv.length; i++) {
546     str = getSignature(argv[i]);
547
548     if(str.endsWith("V")) // void can't be a method argument
549
throw new ClassFormatError JavaDoc("Invalid type: " + argv[i]);
550
551     buf.append(str);
552       }
553
554     str = getSignature(ret);
555
556     buf.append(")" + str);
557
558     return buf.toString();
559   }
560
561   /**
562    * @param signature Method signature
563    * @return Array of argument types
564    * @throw ClassFormatError
565    */

566   public static final String JavaDoc[] methodSignatureArgumentTypes(String JavaDoc signature)
567     throws ClassFormatError JavaDoc
568   {
569     return methodSignatureArgumentTypes(signature, true);
570   }
571
572   /**
573    * @param signature Method signature
574    * @param chopit Shorten class names ?
575    * @return Array of argument types
576    * @throw ClassFormatError
577    */

578   public static final String JavaDoc[] methodSignatureArgumentTypes(String JavaDoc signature,
579                                 boolean chopit)
580     throws ClassFormatError JavaDoc
581   {
582     ArrayList JavaDoc vec = new ArrayList JavaDoc();
583     int index;
584     String JavaDoc[] types;
585
586     try { // Read all declarations between for `(' and `)'
587
if(signature.charAt(0) != '(')
588     throw new ClassFormatError JavaDoc("Invalid method signature: " + signature);
589
590       index = 1; // current string position
591

592       while(signature.charAt(index) != ')') {
593     vec.add(signatureToString(signature.substring(index), chopit));
594     index += consumed_chars; // update position
595
}
596     } catch(StringIndexOutOfBoundsException JavaDoc e) { // Should never occur
597
throw new ClassFormatError JavaDoc("Invalid method signature: " + signature);
598     }
599     
600     types = new String JavaDoc[vec.size()];
601     vec.toArray(types);
602     return types;
603   }
604   /**
605    * @param signature Method signature
606    * @return return type of method
607    * @throw ClassFormatError
608    */

609   public static final String JavaDoc methodSignatureReturnType(String JavaDoc signature)
610        throws ClassFormatError JavaDoc
611   {
612     return methodSignatureReturnType(signature, true);
613   }
614   /**
615    * @param signature Method signature
616    * @param chopit Shorten class names ?
617    * @return return type of method
618    * @throw ClassFormatError
619    */

620   public static final String JavaDoc methodSignatureReturnType(String JavaDoc signature,
621                                boolean chopit)
622        throws ClassFormatError JavaDoc
623   {
624     int index;
625     String JavaDoc type;
626
627     try {
628       // Read return type after `)'
629
index = signature.lastIndexOf(')') + 1;
630       type = signatureToString(signature.substring(index), chopit);
631     } catch(StringIndexOutOfBoundsException JavaDoc e) { // Should never occur
632
throw new ClassFormatError JavaDoc("Invalid method signature: " + signature);
633     }
634
635     return type;
636   }
637
638   /**
639    * Converts method signature to string with all class names compacted.
640    *
641    * @param signature to convert
642    * @param name of method
643    * @param access flags of method
644    * @return Human readable signature
645    */

646   public static final String JavaDoc methodSignatureToString(String JavaDoc signature,
647                              String JavaDoc name,
648                              String JavaDoc access) {
649     return methodSignatureToString(signature, name, access, true);
650   }
651
652   public static final String JavaDoc methodSignatureToString(String JavaDoc signature,
653                              String JavaDoc name,
654                              String JavaDoc access,
655                              boolean chopit) {
656     return methodSignatureToString(signature, name, access, chopit, null);
657   }
658
659   /**
660    * A return&#255;type signature represents the return value from a method.
661    * It is a series of bytes in the following grammar:
662    *
663    * <return_signature> ::= <field_type> | V
664    *
665    * The character V indicates that the method returns no value. Otherwise, the
666    * signature indicates the type of the return value.
667    * An argument signature represents an argument passed to a method:
668    *
669    * <argument_signature> ::= <field_type>
670    *
671    * A method signature represents the arguments that the method expects, and
672    * the value that it returns.
673    * <method_signature> ::= (<arguments_signature>) <return_signature>
674    * <arguments_signature>::= <argument_signature>*
675    *
676    * This method converts such a string into a Java type declaration like
677    * `void main(String[])' and throws a `ClassFormatError' when the parsed
678    * type is invalid.
679    *
680    * @param signature Method signature
681    * @param name Method name
682    * @param access Method access rights
683    * @return Java type declaration
684    * @throw ClassFormatError
685    */

686   public static final String JavaDoc methodSignatureToString(String JavaDoc signature,
687                              String JavaDoc name,
688                              String JavaDoc access,
689                              boolean chopit,
690                              LocalVariableTable vars)
691     throws ClassFormatError JavaDoc
692   {
693     StringBuffer JavaDoc buf = new StringBuffer JavaDoc("(");
694     String JavaDoc type;
695     int index;
696     int var_index = (access.indexOf("static") >= 0)? 0 : 1;
697
698     try { // Read all declarations between for `(' and `)'
699
if(signature.charAt(0) != '(')
700     throw new ClassFormatError JavaDoc("Invalid method signature: " + signature);
701
702       index = 1; // current string position
703

704       while(signature.charAt(index) != ')') {
705     buf.append(signatureToString(signature.substring(index), chopit));
706
707     if(vars != null) {
708       LocalVariable l = vars.getLocalVariable(var_index);
709
710       if(l != null)
711         buf.append(" " + l.getName());
712     } else
713       buf.append(" arg" + var_index);
714
715     var_index++;
716     buf.append(", ");
717     index += consumed_chars; // update position
718
}
719
720       index++; // update position
721

722       // Read return type after `)'
723
type = signatureToString(signature.substring(index), chopit);
724
725     } catch(StringIndexOutOfBoundsException JavaDoc e) { // Should never occur
726
throw new ClassFormatError JavaDoc("Invalid method signature: " + signature);
727     }
728
729     if(buf.length() > 1) // Tack off the extra ", "
730
buf.setLength(buf.length() - 2);
731
732     buf.append(")");
733
734     return access + ((access.length() > 0)? " " : "") + // May be an empty string
735
type + " " + name + buf.toString();
736   }
737
738   // Guess what this does
739
private static final int pow2(int n) {
740     return 1 << n;
741   }
742     
743   /**
744    * Replace all occurences of <em>old</em> in <em>str</em> with <em>new</em>.
745    *
746    * @param str String to permute
747    * @param old String to be replaced
748    * @param new Replacement string
749    * @return new String object
750    */

751   public static final String JavaDoc replace(String JavaDoc str, String JavaDoc old, String JavaDoc new_) {
752     int index, old_index;
753     StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
754
755     try {
756       if((index = str.indexOf(old)) != -1) { // `old' found in str
757
old_index = 0; // String start offset
758

759     // While we have something to replace
760
while((index = str.indexOf(old, old_index)) != -1) {
761       buf.append(str.substring(old_index, index)); // append prefix
762
buf.append(new_); // append replacement
763

764       old_index = index + old.length(); // Skip `old'.length chars
765
}
766
767     buf.append(str.substring(old_index)); // append rest of string
768
str = buf.toString();
769       }
770     } catch(StringIndexOutOfBoundsException JavaDoc e) { // Should not occur
771
System.err.println(e);
772     }
773
774     return str;
775   }
776
777   /**
778    * Converts signature to string with all class names compacted.
779    *
780    * @param signature to convert
781    * @return Human readable signature
782    */

783   public static final String JavaDoc signatureToString(String JavaDoc signature) {
784     return signatureToString(signature, true);
785   }
786
787   /**
788    * The field signature represents the value of an argument to a function or
789    * the value of a variable. It is a series of bytes generated by the
790    * following grammar:
791    *
792    * <PRE>
793    * <field_signature> ::= <field_type>
794    * <field_type> ::= <base_type>|<object_type>|<array_type>
795    * <base_type> ::= B|C|D|F|I|J|S|Z
796    * <object_type> ::= L<fullclassname>;
797    * <array_type> ::= [<field_type>
798    *
799    * The meaning of the base types is as follows:
800    * B byte signed byte
801    * C char character
802    * D double double precision IEEE float
803    * F float single precision IEEE float
804    * I int integer
805    * J long long integer
806    * L<fullclassname>; ... an object of the given class
807    * S short signed short
808    * Z boolean true or false
809    * [<field sig> ... array
810    * </PRE>
811    *
812    * This method converts this string into a Java type declaration such as
813    * `String[]' and throws a `ClassFormatError' when the parsed type is
814    * invalid.
815    *
816    * @param signature Class signature
817    * @param chopit Flag that determines whether chopping is executed or not
818    * @return Java type declaration
819    * @throws ClassFormatError
820    */

821   public static final String JavaDoc signatureToString(String JavaDoc signature,
822                            boolean chopit)
823   {
824     consumed_chars = 1; // This is the default, read just one char like `B'
825

826     try {
827       switch(signature.charAt(0)) {
828       case 'B' : return "byte";
829       case 'C' : return "char";
830       case 'D' : return "double";
831       case 'F' : return "float";
832       case 'I' : return "int";
833       case 'J' : return "long";
834
835       case 'L' : { // Full class name
836
int index = signature.indexOf(';'); // Look for closing `;'
837

838     if(index < 0)
839       throw new ClassFormatError JavaDoc("Invalid signature: " + signature);
840     
841     consumed_chars = index + 1; // "Lblabla;" `L' and `;' are removed
842

843     return compactClassName(signature.substring(1, index), chopit);
844       }
845
846       case 'S' : return "short";
847       case 'Z' : return "boolean";
848
849       case '[' : { // Array declaration
850
int n;
851     StringBuffer JavaDoc buf, brackets;
852     String JavaDoc type;
853     char ch;
854     int consumed_chars; // Shadows global var
855

856     brackets = new StringBuffer JavaDoc(); // Accumulate []'s
857

858     // Count opening brackets and look for optional size argument
859
for(n=0; signature.charAt(n) == '['; n++)
860       brackets.append("[]");
861
862     consumed_chars = n; // Remember value
863

864     // The rest of the string denotes a `<field_type>'
865
type = signatureToString(signature.substring(n), chopit);
866     
867     Utility.consumed_chars += consumed_chars;
868     return type + brackets.toString();
869       }
870
871       case 'V' : return "void";
872
873       default : throw new ClassFormatError JavaDoc("Invalid signature: `" +
874                         signature + "'");
875       }
876     } catch(StringIndexOutOfBoundsException JavaDoc e) { // Should never occur
877
throw new ClassFormatError JavaDoc("Invalid signature: " + e + ":" + signature);
878     }
879   }
880
881   /** Parse Java type such as "char", or "java.lang.String[]" and return the
882    * signature in byte code format, e.g. "C" or "[Ljava/lang/String;" respectively.
883    *
884    * @param type Java type
885    * @return byte code signature
886    */

887   public static String JavaDoc getSignature(String JavaDoc type) {
888     StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
889     char[] chars = type.toCharArray();
890     boolean char_found = false, delim = false;
891     int index = -1;
892
893   loop:
894     for(int i=0; i < chars.length; i++) {
895       switch(chars[i]) {
896       case ' ': case '\t'